Release 1.4.0 with turn windowing, WorkBuddy timeline rail, and appearance settings

This commit is contained in:
QQ 2026-11-29 13:56:03 +08:00
parent ef5be0408c
commit 7d8dfb1e5d
20 changed files with 2844 additions and 532 deletions

View File

@ -1,5 +1,12 @@
# Changelog # Changelog
## 1.4.0 — 2026-11-29
- 长会话渲染窗口与性能隔离:默认仅渲染最近 `6` 轮对话(可在「设置 → Better Chat」配置 `4 / 6 / 10 / 20 / 全部` 或 `1–200` 自定义轮数),支持顶部「加载更早记录(还有 N 轮)」分批向上展开并保持视口滚动锚定;跳回早期区间时底部提供「向下展开 / 回到最新」控制条;`RetiringTurns` 区分窗口裁剪与真实撤回动画;`TurnGroup` 对已结束轮次进行快照隔离并稳定化分组引用,消除末尾流式输出时历史对话重算与重绘卡顿。
- WorkBuddy 风格可展开右侧目录时间轴:日常收起为右缘极简短线,悬停、聚焦或点击即展开圆角浮动可滚动对话目录(提示词右对齐截断、当前轮加粗文字与加长粗横线并直接通过 `scrollTop` 居中对齐),点击任意轮次可一键跳转(支持窗口切换与未加载历史 `loadThrough` 按需拉取)。
- 设置面板新增个性化外观配置:支持在「设置 → Better Chat」切换外观样式(`跟随宿主` / `浅色` / `深色` / `毛玻璃`,兼容迁移旧版 `frostedGlass`)、AI 回复气泡样式(`柔灰` / `描边卡片` / `无气泡`)与最大宽度(`70%` / `80%` / `90%` / `100%`)。
- 验证:`tsc --noEmit`、`vitest run`(36 个文件 / 270 个用例)、`tsdown` 构建通过。
## 1.3.0 — 2026-11-28 ## 1.3.0 — 2026-11-28
- 新增左侧 AI 回复气泡(柔灰底色、左下对话尾角,适配浅色 / 深色 / 毛玻璃主题),多段回复合并在同一个气泡内、无段间横线,内部代码块自动提亮底色。 - 新增左侧 AI 回复气泡(柔灰底色、左下对话尾角,适配浅色 / 深色 / 毛玻璃主题),多段回复合并在同一个气泡内、无段间横线,内部代码块自动提亮底色。

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "dsh-better-chat", "name": "dsh-better-chat",
"version": "1.3.0", "version": "1.4.0",
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新、默认自动审查。", "description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新、默认自动审查。",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",

View File

@ -19,6 +19,63 @@
that underlay, so the stock theme does not change. */ that underlay, so the stock theme does not change. */
--reader-lane-plate: linear-gradient(var(--dsw-alias-bg-base), var(--dsw-alias-bg-base)), linear-gradient(var(--dsw-alias-bg-layer-1, transparent), var(--dsw-alias-bg-layer-1, transparent)); --reader-lane-plate: linear-gradient(var(--dsw-alias-bg-base), var(--dsw-alias-bg-base)), linear-gradient(var(--dsw-alias-bg-layer-1, transparent), var(--dsw-alias-bg-layer-1, transparent));
} }
.root[data-reader-bubble-width="70"] { --reader-ai-max-width: min(calc(var(--dsh-chat-content-width, 748px) * 0.702), 82%); }
.root[data-reader-bubble-width="80"] { --reader-ai-max-width: min(calc(var(--dsh-chat-content-width, 748px) * 0.80), 85%); }
.root[data-reader-bubble-width="90"] { --reader-ai-max-width: 90%; }
.root[data-reader-bubble-width="100"] { --reader-ai-max-width: 100%; }
.root[data-reader-theme="light"],
.root[data-reader-theme="dark"] {
min-height: 100%;
background: var(--dsw-alias-bg-base);
}
.root[data-reader-theme="light"] {
color-scheme: light;
--dsw-alias-bg-base: #ffffff;
--dsw-alias-bg-layer-1: #f7f8fa;
--dsw-alias-bg-module-platform: #f5f6f8;
--dsw-alias-bg-mask-photo: rgba(15, 23, 42, 0.45);
--dsw-alias-button-floating-fill: #ffffff;
--dsw-alias-button-floating-hover: #f3f4f6;
--dsw-alias-interactive-bg-hover: rgba(15, 23, 42, 0.055);
--dsw-alias-label-primary: #1a1d24;
--dsw-alias-label-secondary: #525966;
--dsw-alias-label-tertiary: #858d99;
--dsw-alias-label-caption: #9ca3af;
--dsw-alias-border-l1: rgba(15, 23, 42, 0.08);
--dsw-alias-border-l2: rgba(15, 23, 42, 0.13);
--dsw-alias-border-l3: rgba(15, 23, 42, 0.22);
--dsw-alias-state-business-primary: #4d6bfe;
--dsw-alias-state-success-primary: #2f9e63;
--dsw-alias-state-error-primary: #d1483c;
--dsw-alias-state-warning-primary: #d8862c;
--dsw-specific-bubble: #eff3fb;
--dsw-alias-markdown-code-block: #f6f7f9;
--dsw-elevation-panel: 0 2px 12px rgba(15, 23, 42, 0.08);
}
.root[data-reader-theme="dark"] {
color-scheme: dark;
--dsw-alias-bg-base: #15171c;
--dsw-alias-bg-layer-1: #1c1f26;
--dsw-alias-bg-module-platform: #1d2027;
--dsw-alias-bg-mask-photo: rgba(0, 0, 0, 0.72);
--dsw-alias-button-floating-fill: #1f232b;
--dsw-alias-button-floating-hover: #292e38;
--dsw-alias-interactive-bg-hover: rgba(255, 255, 255, 0.07);
--dsw-alias-label-primary: #ebedf2;
--dsw-alias-label-secondary: #a8afbd;
--dsw-alias-label-tertiary: #7d8594;
--dsw-alias-label-caption: #636b78;
--dsw-alias-border-l1: rgba(255, 255, 255, 0.08);
--dsw-alias-border-l2: rgba(255, 255, 255, 0.14);
--dsw-alias-border-l3: rgba(255, 255, 255, 0.22);
--dsw-alias-state-business-primary: #6b85ff;
--dsw-alias-state-success-primary: #45c47f;
--dsw-alias-state-error-primary: #f06559;
--dsw-alias-state-warning-primary: #e8a449;
--dsw-specific-bubble: #252d40;
--dsw-alias-markdown-code-block: #1b1e25;
--dsw-elevation-panel: 0 4px 18px rgba(0, 0, 0, 0.45);
}
:global([data-conversation-tabs] > button[data-better-chat-duplicate-tab]) { display: none !important; } :global([data-conversation-tabs] > button[data-better-chat-duplicate-tab]) { display: none !important; }
.column { max-width: var(--dsh-chat-content-width, 748px); width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 22px; min-width: 0; } .column { max-width: var(--dsh-chat-content-width, 748px); width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 22px; min-width: 0; }
/* The column is only a programmatic focus-restore target (tabIndex -1), never a /* The column is only a programmatic focus-restore target (tabIndex -1), never a
@ -80,6 +137,33 @@
background: var(--dsw-alias-bg-base); background: var(--dsw-alias-bg-base);
border: 1px solid var(--dsw-alias-border-l2); border: 1px solid var(--dsw-alias-border-l2);
} }
.root[data-reader-bubble-style="card"] .answerBubble {
background: var(--dsw-alias-bg-base);
border: 1px solid var(--dsw-alias-border-l2);
box-shadow: 0 1px 4px var(--dsw-alias-border-l1);
}
.root[data-reader-bubble-style="card"] .answerBubble :global(.md-code-block) {
background: var(--dsw-alias-bg-module-platform);
}
.root[data-reader-glass][data-reader-bubble-style="card"] .answerBubble {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, .8)) 65%, transparent);
backdrop-filter: blur(12px);
border-color: color-mix(in srgb, var(--dsw-alias-border-l2, rgba(128, 128, 128, .3)) 65%, transparent);
}
.root[data-reader-bubble-style="plain"] .answerBubble,
.root[data-reader-glass][data-reader-bubble-style="plain"] .answerBubble {
width: 100%;
max-width: var(--reader-ai-max-width);
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
backdrop-filter: none;
box-shadow: none;
}
.root[data-reader-bubble-style="plain"] .answerBubble :global(.md-code-block) {
background: var(--dsw-alias-markdown-code-block, var(--dsw-alias-bg-module-platform));
}
.answer { display: flex; flex-direction: column; min-width: 0; overflow-wrap: anywhere; } .answer { display: flex; flex-direction: column; min-width: 0; overflow-wrap: anywhere; }
.readingText { min-width: 0; } .readingText { min-width: 0; }
.reasonPlain { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; color: inherit; } .reasonPlain { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; color: inherit; }
@ -438,8 +522,67 @@
.attention span { color: var(--dsw-alias-label-secondary); } .attention span { color: var(--dsw-alias-label-secondary); }
.unknown { background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; padding: 12px 14px; font-size: 13px; line-height: 22px; } .unknown { background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; padding: 12px 14px; font-size: 13px; line-height: 22px; }
.unknown p { margin: 0 0 6px; } .unknown p { margin: 0 0 6px; }
.historyButton { align-self: center; background: transparent; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px; padding: 4px 12px; font-size: 12px; color: var(--dsw-alias-label-secondary); } .historyButton {
align-self: center;
background: var(--dsw-alias-bg-module-platform);
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 999px;
padding: 5px 14px;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-secondary);
transition: background-color 140ms ease, border-color 140ms ease, color 140ms ease;
}
.historyButton:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
border-color: var(--dsw-alias-border-l3, var(--dsw-alias-border-l2));
color: var(--dsw-alias-label-primary);
}
.historyButton:disabled { opacity: .55; cursor: default; } .historyButton:disabled { opacity: .55; cursor: default; }
.newerBar {
align-self: center;
display: inline-flex;
align-items: center;
flex-wrap: wrap;
justify-content: center;
gap: 8px 12px;
padding: 6px 14px;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 999px;
background: var(--dsw-alias-bg-module-platform);
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-secondary);
}
.newerBarText { white-space: nowrap; }
.newerBarActions { display: inline-flex; align-items: center; gap: 6px; }
.newerBarButton {
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 999px;
background: var(--dsw-alias-bg-base);
color: var(--dsw-alias-label-secondary);
font: inherit;
font-size: 12px;
line-height: 18px;
padding: 2px 10px;
cursor: pointer;
}
.newerBarButton:hover {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-primary);
}
.newerBarPrimary {
color: var(--dsw-alias-state-business-primary);
border-color: color-mix(in srgb, var(--dsw-alias-state-business-primary) 35%, transparent);
}
.root[data-reader-glass] .historyButton,
.root[data-reader-glass] .newerBar {
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform, rgba(128, 128, 128, .12)) 45%, transparent);
backdrop-filter: blur(12px);
}
.root[data-reader-glass] .newerBarButton {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, .8)) 35%, transparent);
}
.empty { padding: 40px 0; color: var(--dsw-alias-label-tertiary); text-align: center; } .empty { padding: 40px 0; color: var(--dsw-alias-label-tertiary); text-align: center; }
.answerActions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin: -4px 0 0 -6px; min-height: 28px; max-width: calc(100% + 6px); min-width: 0; } .answerActions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin: -4px 0 0 -6px; min-height: 28px; max-width: calc(100% + 6px); min-width: 0; }
.userActions { display: flex; flex-wrap: wrap; align-items: center; align-self: flex-end; justify-content: flex-end; width: fit-content; max-width: 100%; gap: 4px 8px; min-height: 28px; } .userActions { display: flex; flex-wrap: wrap; align-items: center; align-self: flex-end; justify-content: flex-end; width: fit-content; max-width: 100%; gap: 4px 8px; min-height: 28px; }
@ -522,7 +665,7 @@
[data-motion=off] .turnStatusLabel { animation: none !important; color: var(--dsw-static-deepseek-500, #4d6bfe) !important; -webkit-text-fill-color: var(--dsw-static-deepseek-500, #4d6bfe) !important; } [data-motion=off] .turnStatusLabel { animation: none !important; color: var(--dsw-static-deepseek-500, #4d6bfe) !important; -webkit-text-fill-color: var(--dsw-static-deepseek-500, #4d6bfe) !important; }
@media (prefers-reduced-motion: reduce) { .turnStatusLabel { animation: none !important; color: var(--dsw-static-deepseek-500, #4d6bfe) !important; -webkit-text-fill-color: var(--dsw-static-deepseek-500, #4d6bfe) !important; } } @media (prefers-reduced-motion: reduce) { .turnStatusLabel { animation: none !important; color: var(--dsw-static-deepseek-500, #4d6bfe) !important; -webkit-text-fill-color: var(--dsw-static-deepseek-500, #4d6bfe) !important; } }
@media (pointer: coarse) { .disclosureButton { min-height: 44px; } } @media (pointer: coarse) { .disclosureButton { min-height: 44px; } }
@media (max-width: 600px) { .root { padding-inline: 20px; --reader-ai-max-width: 92%; } .column { gap: 18px; } .toolbar { font-size: 11px; } } @media (max-width: 600px) { .root { padding-inline: 20px; --reader-ai-max-width: 92%; } .root[data-reader-bubble-width] { --reader-ai-max-width: 92%; } .root[data-reader-bubble-width="100"] { --reader-ai-max-width: 100%; } .column { gap: 18px; } .toolbar { font-size: 11px; } }
@container (max-width: 480px) { .choreographedFlow { --reader-ai-max-width: 92%; } } @container (max-width: 480px) { .choreographedFlow { --reader-ai-max-width: 92%; } }
/* Measured flow owns geometry; steps never change React parents when folded. */ /* Measured flow owns geometry; steps never change React parents when folded. */

View File

@ -2,7 +2,8 @@ import type {} from '@deepseek-ai/dsh-session-turn-outline/types';
import type {} from '@deepseek-ai/dsh-agent/types'; import type {} from '@deepseek-ai/dsh-agent/types';
import { Fragment, memo, useCallback, useEffect, useId, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'; import { Fragment, memo, useCallback, useEffect, useId, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import type { ReactNode, RefObject } from 'react'; import type { ReactNode, RefObject } from 'react';
import type { ChatConversationViewNode, ChatNode, ChatNodeKind, ChatNodeOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client'; import type { ChatConversationViewNode, ChatNode, ChatNodeKind, ChatNodeOwnerProps, ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client';
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'; import { createSnapshotStore } from '@deepseek-ai/dsh-client-store';
import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'; import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives';
import { BlockBoundary, Blocks, contentBlocks, CopyAnswer, UserMessageActions } from './Blocks.js'; import { BlockBoundary, Blocks, contentBlocks, CopyAnswer, UserMessageActions } from './Blocks.js';
@ -21,11 +22,11 @@ import { WaitingStatus } from './WaitingStatus.js';
import { handsBackToModel, waitingAnchor } from './waiting-clock.js'; import { handsBackToModel, waitingAnchor } from './waiting-clock.js';
import { ContextInjectionRow } from './native/ContextInjectionRow.js'; import { ContextInjectionRow } from './native/ContextInjectionRow.js';
import { TimelineRail } from './TimelineRail.js'; import { TimelineRail } from './TimelineRail.js';
import { landTurn, scrollerOf } from './conversation-scroll.js'; import { flowTop, landTurn, scrollerOf } from './conversation-scroll.js';
import { mergeTimelineItems, type TimelineItem } from './timeline.js'; import { mergeTimelineItems, type TimelineItem } from './timeline.js';
import { presentLiveTurn, segmentLiveTurn } from './live-turn.js'; import { presentLiveTurn, segmentLiveTurn } from './live-turn.js';
import type { LiveStep } from './live-turn.js'; import type { LiveStep } from './live-turn.js';
import { frostedGlassOf } from './fold-intensity.js'; import { aiBubbleStyleOf, aiBubbleWidthOf, readerThemeOf } from './appearance.js';
import { ChoreographedFlow, useFlowChat } from './ChoreographedFlow.js'; import { ChoreographedFlow, useFlowChat } from './ChoreographedFlow.js';
import { ClosedProcessSummary } from './ClosedProcessSummary.js'; import { ClosedProcessSummary } from './ClosedProcessSummary.js';
import { ReaderLaneScope, StickyLane } from './StickyLane.js'; import { ReaderLaneScope, StickyLane } from './StickyLane.js';
@ -36,6 +37,18 @@ import { markdownLabels, truncatedJsonLabel } from './primitive-labels.js';
import { chatSeatProps } from './chat-seat.js'; import { chatSeatProps } from './chat-seat.js';
import { visibleChatKeys, visibleChatSignature } from './rewind-cut.js'; import { visibleChatKeys, visibleChatSignature } from './rewind-cut.js';
import { ensureStyles } from './styles.js'; import { ensureStyles } from './styles.js';
import {
batchSizeForLimit,
countTurnsInSlice,
expandNewerInWindow,
expandOlderInWindow,
initialTurnWindow,
jumpToTurnInWindow,
renderTurnLimitOf,
sliceTurnWindow,
stabilizeGroups,
type TurnWindowState,
} from './turn-window.js';
function isNode<K extends ChatNodeKind>(node: ChatConversationViewNode, kind: K): node is ChatNode<K> { function isNode<K extends ChatNodeKind>(node: ChatConversationViewNode, kind: K): node is ChatNode<K> {
return node.kind === kind; return node.kind === kind;
@ -470,8 +483,51 @@ function DeliverablesRow({ deliverables, openFile, revealFile, openMode }: {
); );
} }
type ClosedSnapshotCache = {
snapshot: ChatSnapshot;
keys: readonly string[];
turnNum: number | null;
turn: TurnLocation | undefined;
turnStatus: string | undefined;
turnEndSeq: number | undefined;
turnStepCount: number;
nodes: ReadonlyArray<ChatConversationViewNode | undefined>;
};
const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel = false, ...props }: ReaderProps & { group: ReaderGroup; motion: boolean; autoFold: boolean; pinnedKeys: readonly string[]; selectedProcessKeys: readonly string[]; isAwaitingModel?: boolean }) { const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel = false, ...props }: ReaderProps & { group: ReaderGroup; motion: boolean; autoFold: boolean; pinnedKeys: readonly string[]; selectedProcessKeys: readonly string[]; isAwaitingModel?: boolean }) {
const snapshot = props.useChat(snapshot => snapshot); const turnCache = useRef<ClosedSnapshotCache | null>(null);
const selectTurnSnapshot = useCallback((current: ChatSnapshot): ChatSnapshot => {
const prev = turnCache.current;
const turn = group.turn === null ? undefined : current.timeline.turns.get(group.turn);
const turnStatus = turn?.status;
const turnEndSeq = turn?.end?.seq;
const turnStepCount = turn?.steps.length ?? 0;
if (
prev
&& turnStatus === 'closed'
&& prev.turnStatus === 'closed'
&& prev.keys === group.keys
&& prev.turnNum === group.turn
&& prev.turn === turn
&& prev.turnEndSeq === turnEndSeq
&& prev.turnStepCount === turnStepCount
&& group.keys.every((key, index) => current.nodes.get(key) === prev.nodes[index])
) {
return prev.snapshot;
}
turnCache.current = {
snapshot: current,
keys: group.keys,
turnNum: group.turn,
turn,
turnStatus,
turnEndSeq,
turnStepCount,
nodes: group.keys.map(key => current.nodes.get(key)),
};
return current;
}, [group.keys, group.turn]);
const snapshot = props.useChat(selectTurnSnapshot);
const nodes = snapshot.nodes; const nodes = snapshot.nodes;
const turn = group.turn === null ? undefined : snapshot.timeline.turns.get(group.turn); const turn = group.turn === null ? undefined : snapshot.timeline.turns.get(group.turn);
const interaction = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction); const interaction = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction);
@ -483,9 +539,9 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
const processButton = useRef<HTMLButtonElement>(null); const processButton = useRef<HTMLButtonElement>(null);
const setExpanded = useCallback((value: boolean) => props.actions.setExpanded(choiceKey, value), [props.actions, choiceKey]); const setExpanded = useCallback((value: boolean) => props.actions.setExpanded(choiceKey, value), [props.actions, choiceKey]);
const pinProcess = useCallback(() => setExpanded(true), [setExpanded]); const pinProcess = useCallback(() => setExpanded(true), [setExpanded]);
const firstKind = props.useChat(snapshot => snapshot.nodes.get(group.keys[0])?.kind); const firstKind = nodes.get(group.keys[0])?.kind;
const startsWithUser = firstKind === 'user'; const startsWithUser = firstKind === 'user';
const mainKeys = startsWithUser ? group.keys.slice(1) : group.keys; const mainKeys = useMemo(() => (startsWithUser ? group.keys.slice(1) : group.keys), [startsWithUser, group.keys]);
const flow = useMemo(() => readerFlow({ ...group, keys: mainKeys }, turn, key => nodes.get(key), snapshot.order), [nodes, group, mainKeys, turn, snapshot.order]); const flow = useMemo(() => readerFlow({ ...group, keys: mainKeys }, turn, key => nodes.get(key), snapshot.order), [nodes, group, mainKeys, turn, snapshot.order]);
const steps = useMemo(() => segmentLiveTurn(flow, key => nodes.get(key)), [flow, nodes]); const steps = useMemo(() => segmentLiveTurn(flow, key => nodes.get(key)), [flow, nodes]);
const liveItems = useMemo(() => presentLiveTurn(steps, boundary, autoFold), [steps, boundary, autoFold]); const liveItems = useMemo(() => presentLiveTurn(steps, boundary, autoFold), [steps, boundary, autoFold]);
@ -613,7 +669,7 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
<BlockBoundary><MainNode {...shared} boundary={boundary} nodeKey={step.nodeKey} pinned={pinnedKeys.includes(step.nodeKey)} processOpen={processOpen} /></BlockBoundary> <BlockBoundary><MainNode {...shared} boundary={boundary} nodeKey={step.nodeKey} pinned={pinnedKeys.includes(step.nodeKey)} processOpen={processOpen} /></BlockBoundary>
</Fragment>; </Fragment>;
}; };
return <section className={css.turn} data-reader-turn={group.turn ?? 'unresolved'} data-reader-turn-state={boundary.status} data-reader-turn-result={boundary.reason ?? undefined}> return <section className={css.turn} data-reader-group-key={group.key} data-reader-turn={group.turn ?? 'unresolved'} data-reader-turn-state={boundary.status} data-reader-turn-result={boundary.reason ?? undefined}>
{startsWithUser && <BlockBoundary><MainNode {...shared} useChat={props.useChat} boundary={boundary} nodeKey={group.keys[0]} /></BlockBoundary>} {startsWithUser && <BlockBoundary><MainNode {...shared} useChat={props.useChat} boundary={boundary} nodeKey={group.keys[0]} /></BlockBoundary>}
<div className={css.turnStickyRegion} data-reader-sticky-region> <div className={css.turnStickyRegion} data-reader-sticky-region>
<ChoreographedFlow id={flowId} frame={presentation} motion={motion} enabled={autoFold && boundary.status === 'open' && !holdingSelection} <ChoreographedFlow id={flowId} frame={presentation} motion={motion} enabled={autoFold && boundary.status === 'open' && !holdingSelection}
@ -695,9 +751,18 @@ export function Reader(props: ReaderProps) {
// Reading while folding is off must not pin completed process content forever. // Reading while folding is off must not pin completed process content forever.
if (restored) props.actions.resetExpanded(); if (restored) props.actions.resetExpanded();
}, [autoFold, props.actions]); }, [autoFold, props.actions]);
const frostedGlass = frostedGlassOf(prefsSnap); const readerTheme = readerThemeOf(prefsSnap);
const frostedGlass = readerTheme === 'glass';
const aiBubbleStyle = aiBubbleStyleOf(prefsSnap);
const aiBubbleWidth = aiBubbleWidthOf(prefsSnap);
const streamMotion = useMemo(() => ({ enabled: motion, activatedAt: activatedAt.current }), [motion]); const streamMotion = useMemo(() => ({ enabled: motion, activatedAt: activatedAt.current }), [motion]);
const groups = useMemo(() => groupNodes(renderKeys, key => nodes.get(key)), [renderKeys, nodes, timeline]); const previousGroupsRef = useRef<readonly ReaderGroup[]>([]);
const groups = useMemo(() => {
const next = groupNodes(renderKeys, key => nodes.get(key));
const stabilized = stabilizeGroups(previousGroupsRef.current, next);
previousGroupsRef.current = stabilized;
return stabilized;
}, [renderKeys, nodes, timeline]);
const isAwaitingModel = useMemo(() => { const isAwaitingModel = useMemo(() => {
// 状态机铁律:「深度求索中」与「正在处理/思考」永远互斥。 // 状态机铁律:「深度求索中」与「正在处理/思考」永远互斥。
// 1. 仅空闲发送(!running)的本地回显窗口:用户按下回车第 0 毫秒立即反馈。 // 1. 仅空闲发送(!running)的本地回显窗口:用户按下回车第 0 毫秒立即反馈。
@ -757,11 +822,219 @@ export function Reader(props: ReaderProps) {
[turnNavigationItems, turnOutline, turnsWithDeliverables], [turnNavigationItems, turnOutline, turnsWithDeliverables],
); );
// 5. Active & busy turn tracking // 5. Active & busy turn tracking + configurable render window
const [activeTurn, setActiveTurn] = useState<number | null>(null); const [activeTurn, setActiveTurn] = useState<number | null>(null);
const [busyTurn, setBusyTurn] = useState<number | null>(null); const [busyTurn, setBusyTurn] = useState<number | null>(null);
const renderTurnLimit = renderTurnLimitOf(prefsSnap);
const [windowTrack, setWindowTrack] = useState<{
sessionId: ReaderProps['sessionId'];
limit: number;
state: TurnWindowState;
}>(() => ({
sessionId: props.sessionId,
limit: renderTurnLimit,
state: initialTurnWindow(renderTurnLimit),
}));
const windowState = (
windowTrack.sessionId === props.sessionId && windowTrack.limit === renderTurnLimit
) ? windowTrack.state : initialTurnWindow(renderTurnLimit);
const setWindowState = useCallback(
(updater: TurnWindowState | ((current: TurnWindowState) => TurnWindowState)) => {
setWindowTrack(current => {
const baseState = current.sessionId === props.sessionId && current.limit === renderTurnLimit
? current.state
: initialTurnWindow(renderTurnLimit);
const nextState = typeof updater === 'function' ? updater(baseState) : updater;
return { sessionId: props.sessionId, limit: renderTurnLimit, state: nextState };
});
},
[props.sessionId, renderTurnLimit],
);
// Scroll spy to update activeTurn type PendingPrependAnchor = {
anchorKey: string | null;
anchorFlowTop: number;
scrollHeight: number;
scrollTop: number;
};
type PendingJumpTarget = {
turn: number;
seq: number | null;
expiresAt: number;
};
const pendingPrependRef = useRef<PendingPrependAnchor | null>(null);
const awaitingHostLoadRef = useRef(false);
const prevGroupCountRef = useRef(groups.length);
const pendingJumpRef = useRef<PendingJumpTarget | null>(null);
const pendingScrollBottomRef = useRef(false);
useLayoutEffect(() => {
if (windowTrack.sessionId !== props.sessionId || windowTrack.limit !== renderTurnLimit) {
pendingPrependRef.current = null;
awaitingHostLoadRef.current = false;
pendingJumpRef.current = null;
pendingScrollBottomRef.current = false;
prevGroupCountRef.current = groups.length;
setWindowTrack({
sessionId: props.sessionId,
limit: renderTurnLimit,
state: initialTurnWindow(renderTurnLimit),
});
}
}, [props.sessionId, renderTurnLimit, windowTrack.sessionId, windowTrack.limit, groups.length]);
const windowSlice = useMemo(
() => sliceTurnWindow(groups, windowState, renderTurnLimit),
[groups, windowState, renderTurnLimit],
);
const renderedGroups = windowSlice.visible;
const allGroupKeys = useMemo(() => new Set(groups.map(group => group.key)), [groups]);
const shouldRetire = useCallback((key: string) => !allGroupKeys.has(key), [allGroupKeys]);
const hiddenOlderTurns = useMemo(
() => countTurnsInSlice(groups, 0, windowSlice.start),
[groups, windowSlice.start],
);
const hiddenNewerTurns = useMemo(
() => countTurnsInSlice(groups, windowSlice.end, groups.length),
[groups, windowSlice.end],
);
const unloadedOlderCount = useMemo(() => {
let count = 0;
for (const item of timelineItems) {
if (item.anchor.kind === 'unloaded') count++;
else break;
}
return count;
}, [timelineItems]);
const totalOlderHint = hiddenOlderTurns + unloadedOlderCount;
const canLoadOlder = windowSlice.hiddenOlder > 0 || hasMore;
useLayoutEffect(() => {
const prevCount = prevGroupCountRef.current;
prevGroupCountRef.current = groups.length;
if (awaitingHostLoadRef.current && groups.length > prevCount) {
awaitingHostLoadRef.current = false;
const added = groups.length - prevCount;
const step = Math.min(added, batchSizeForLimit(renderTurnLimit));
setWindowState(cur => expandOlderInWindow(groups, cur, renderTurnLimit, step));
}
}, [groups, renderTurnLimit, setWindowState]);
const jumpToLatest = useCallback(() => {
pendingJumpRef.current = null;
if (windowState.kind === 'range') {
pendingScrollBottomRef.current = true;
setWindowState(initialTurnWindow(renderTurnLimit));
}
scroll.jump();
}, [windowState.kind, renderTurnLimit, setWindowState, scroll.jump]);
const capturePrependAnchor = (): PendingPrependAnchor | null => {
const el = root.current;
if (!el) return null;
const port = scrollerOf(el);
const firstVisibleRow = el.querySelector<HTMLElement>('[data-reader-group-key]');
return {
anchorKey: firstVisibleRow?.dataset.readerGroupKey ?? null,
anchorFlowTop: firstVisibleRow ? flowTop(firstVisibleRow, port) : 0,
scrollHeight: port.scrollHeight,
scrollTop: port.scrollTop,
};
};
const handleLoadOlder = useCallback(async () => {
scroll.release();
pendingPrependRef.current = capturePrependAnchor();
if (windowSlice.hiddenOlder > 0) {
setHistoryError(false);
setWindowState(cur => expandOlderInWindow(groups, cur, renderTurnLimit));
return;
}
if (!hasMore) {
pendingPrependRef.current = null;
return;
}
awaitingHostLoadRef.current = true;
prevGroupCountRef.current = groups.length;
setHistoryError(false);
try {
await props.loadOlder();
} catch {
awaitingHostLoadRef.current = false;
pendingPrependRef.current = null;
setHistoryError(true);
}
}, [scroll.release, windowSlice.hiddenOlder, setWindowState, groups, renderTurnLimit, hasMore, props.loadOlder]);
const flushPendingScrollActions = useCallback(() => {
const el = root.current;
if (!el) return;
const port = scrollerOf(el);
if (pendingScrollBottomRef.current) {
pendingScrollBottomRef.current = false;
scroll.jump();
}
const pendingPrepend = pendingPrependRef.current;
if (pendingPrepend) {
const renderedRows = el.querySelectorAll<HTMLElement>('[data-reader-group-key]');
const firstDomKey = renderedRows[0]?.dataset.readerGroupKey ?? null;
const prepended = pendingPrepend.anchorKey === null || (firstDomKey !== null && firstDomKey !== pendingPrepend.anchorKey);
if (prepended) {
pendingPrependRef.current = null;
const anchorEl = pendingPrepend.anchorKey
? Array.from(renderedRows).find(node => node.dataset.readerGroupKey === pendingPrepend.anchorKey)
: undefined;
if (anchorEl) {
const delta = flowTop(anchorEl, port) - pendingPrepend.anchorFlowTop;
if (Math.abs(delta) > 0.5) {
port.scrollTop += delta;
}
} else {
const heightDelta = port.scrollHeight - pendingPrepend.scrollHeight;
if (Math.abs(heightDelta) > 0.5) {
port.scrollTop = pendingPrepend.scrollTop + heightDelta;
}
}
}
}
const pendingTarget = pendingJumpRef.current;
if (pendingTarget) {
if (Date.now() > pendingTarget.expiresAt) {
pendingJumpRef.current = null;
} else {
const targetRow = el.querySelector<HTMLElement>(`[data-reader-turn="${pendingTarget.turn}"]`);
if (targetRow) {
pendingJumpRef.current = null;
const last = timelineItems.at(-1);
if (last !== undefined && last.turn === pendingTarget.turn) {
pendingScrollBottomRef.current = false;
scroll.jump();
} else {
scroll.release();
landTurn(targetRow, port);
}
setActiveTurn(pendingTarget.turn);
} else if (groups.some(group => group.turn === pendingTarget.turn)) {
setWindowState(cur => jumpToTurnInWindow(groups, cur, pendingTarget.turn, renderTurnLimit));
}
}
}
if (!loadingOlder && awaitingHostLoadRef.current) {
awaitingHostLoadRef.current = false;
pendingPrependRef.current = null;
}
}, [groups, renderTurnLimit, timelineItems, loadingOlder, setWindowState, scroll.jump, scroll.release]);
useLayoutEffect(() => {
flushPendingScrollActions();
}, [groups, renderedGroups, flushPendingScrollActions]);
// Scroll spy to update activeTurn over the rendered window
useEffect(() => { useEffect(() => {
const el = root.current; const el = root.current;
if (!el) return; if (!el) return;
@ -797,33 +1070,50 @@ export function Reader(props: ReaderProps) {
scroller.addEventListener('scroll', updateActive, { passive: true }); scroller.addEventListener('scroll', updateActive, { passive: true });
updateActive(); updateActive();
return () => scroller.removeEventListener('scroll', updateActive); return () => scroller.removeEventListener('scroll', updateActive);
}, [groups]); }, [renderedGroups]);
// Navigation handler (supports loaded jump & unloaded loadThrough). // Navigation handler (supports loaded window jump & unloaded loadThrough).
// Land on the conversation scroller only — scrollIntoView also moves // Land on the conversation scroller only — scrollIntoView also moves
// ancestor boxes and can lift the sticky composer after a top→bottom jump. // ancestor boxes and can lift the sticky composer after a top→bottom jump.
const onNavigateTurn = useCallback(async (item: TimelineItem) => { const onNavigateTurn = useCallback(async (item: TimelineItem) => {
const el = root.current; const el = root.current;
if (!el) return; if (!el) return;
const port = scrollerOf(el); const port = scrollerOf(el);
const reveal = (turn: number) => { const existingRow = el.querySelector<HTMLElement>(`[data-reader-turn="${item.turn}"]`);
const targetRow = el.querySelector<HTMLElement>(`[data-reader-turn="${turn}"]`); const last = timelineItems.at(-1);
if (!targetRow) return; const isLastTurn = last !== undefined && last.turn === item.turn;
const last = timelineItems.at(-1);
if (last !== undefined && last.turn === turn) { if (existingRow) {
scroll.jump(); pendingJumpRef.current = null;
if (isLastTurn) {
jumpToLatest();
} else { } else {
scroll.release(); scroll.release();
landTurn(targetRow, port); landTurn(existingRow, port);
} }
setActiveTurn(turn); setActiveTurn(item.turn);
};
if (item.anchor.kind === 'loaded') {
reveal(item.turn);
return; return;
} }
if (item.anchor.kind === 'loaded') {
pendingJumpRef.current = {
turn: item.turn,
seq: null,
expiresAt: Date.now() + 3000,
};
if (!isLastTurn) {
scroll.release();
}
setWindowState(cur => jumpToTurnInWindow(groups, cur, item.turn, renderTurnLimit));
return;
}
pendingJumpRef.current = {
turn: item.turn,
seq: item.anchor.seq,
expiresAt: Date.now() + 10000,
};
scroll.release();
setBusyTurn(item.turn); setBusyTurn(item.turn);
try { try {
if (props.loadThrough) { if (props.loadThrough) {
@ -831,11 +1121,10 @@ export function Reader(props: ReaderProps) {
} else { } else {
await props.loadOlder(); await props.loadOlder();
} }
setTimeout(() => { reveal(item.turn); }, 50);
} finally { } finally {
setBusyTurn(null); setBusyTurn(null);
} }
}, [props.loadThrough, props.loadOlder, scroll.jump, scroll.release, timelineItems]); }, [props.loadThrough, props.loadOlder, groups, renderTurnLimit, timelineItems, setWindowState, jumpToLatest, scroll.release]);
const lastKey = renderKeys.at(-1); const lastKey = renderKeys.at(-1);
const lastNode = lastKey ? nodes.get(lastKey) : undefined; const lastNode = lastKey ? nodes.get(lastKey) : undefined;
@ -850,16 +1139,20 @@ export function Reader(props: ReaderProps) {
lastSubmissionRef.current = lastSubmissionId; lastSubmissionRef.current = lastSubmissionId;
if (appendedUser || appendedSubmission) { if (appendedUser || appendedSubmission) {
if (windowState.kind === 'range') {
pendingScrollBottomRef.current = true;
setWindowState(initialTurnWindow(renderTurnLimit));
}
scroll.jump(); scroll.jump();
} }
}, [lastKey, lastNode?.kind, lastSubmissionId, scroll]); }, [lastKey, lastNode?.kind, lastSubmissionId, scroll, windowState.kind, renderTurnLimit, setWindowState]);
// ChatView publishes data-chat-flow="" on its column. Skins treat a // ChatView publishes data-chat-flow="" on its column. Skins treat a
// scrollport without that hook as inspect-only and hide [data-composer-seat]. // scrollport without that hook as inspect-only and hide [data-composer-seat].
// dsh-claude-style 0.19.x also hides the host seat whenever the first tab // dsh-claude-style 0.19.x also hides the host seat whenever the first tab
// is not 对话. Reader.module.css restores that seat only while this root // is not 对话. Reader.module.css restores that seat only while this root
// (data-dsh-better-display) is mounted. // (data-dsh-better-display) is mounted.
return <StreamMotionContext.Provider value={streamMotion}><ReaderLaneScope><div ref={root} className={css.root} data-reader-build="0.3.4" data-dsh-better-display="0.3.4" data-reader-wait-clock-version="input-v1" data-reader-wait-start={waitAnchor.time ?? undefined} data-motion={motion ? 'on' : 'off'} data-reader-glass={frostedGlass || undefined} data-reader-auto-fold={autoFold ? 'on' : 'off'}> return <StreamMotionContext.Provider value={streamMotion}><ReaderLaneScope><div ref={root} className={css.root} data-reader-build="0.3.4" data-dsh-better-display="0.3.4" data-reader-wait-clock-version="input-v1" data-reader-wait-start={waitAnchor.time ?? undefined} data-motion={motion ? 'on' : 'off'} data-reader-glass={frostedGlass || undefined} data-reader-theme={readerTheme === 'light' || readerTheme === 'dark' ? readerTheme : undefined} data-reader-bubble-style={aiBubbleStyle} data-reader-bubble-width={aiBubbleWidth} data-reader-auto-fold={autoFold ? 'on' : 'off'}>
<TimelineRail items={timelineItems} activeTurn={activeTurn} busyTurn={busyTurn} onNavigate={onNavigateTurn} /> <TimelineRail items={timelineItems} activeTurn={activeTurn} busyTurn={busyTurn} onNavigate={onNavigateTurn} />
<div className={css.column} data-chat-flow="" tabIndex={-1}> <div className={css.column} data-chat-flow="" tabIndex={-1}>
<StickyLane kind="toolbar" className={css.toolbar}> <StickyLane kind="toolbar" className={css.toolbar}>
@ -876,14 +1169,48 @@ export function Reader(props: ReaderProps) {
{`自动折叠${autoFold ? '开' : '关'}`} {`自动折叠${autoFold ? '开' : '关'}`}
</button> </button>
</StickyLane> </StickyLane>
{hasMore && <button type="button" className={css.historyButton} disabled={loadingOlder} onClick={async () => { {canLoadOlder && (
setHistoryError(false); <button
try { await props.loadOlder(); } catch { setHistoryError(true); } type="button"
}}>{loadingOlder ? '正在加载更早记录' : '加载更早记录'}</button>} className={css.historyButton}
disabled={loadingOlder}
data-reader-load-older
onClick={handleLoadOlder}
>
{loadingOlder
? '正在加载更早记录'
: totalOlderHint > 0
? `加载更早记录(还有 ${totalOlderHint} 轮)`
: '加载更早记录'}
</button>
)}
{historyError && <div className={css.notice}>历史记录加载失败,可再次尝试;现有内容未改变。</div>} {historyError && <div className={css.notice}>历史记录加载失败,可再次尝试;现有内容未改变。</div>}
{openError && <div className={css.error} role="alert">会话暂时无法读取:{openError.message}</div>} {openError && <div className={css.error} role="alert">会话暂时无法读取:{openError.message}</div>}
{loading && groups.length === 0 && <p className={css.empty} role="status">正在读取会话…</p>} {loading && groups.length === 0 && <p className={css.empty} role="status">正在读取会话…</p>}
<RetiringTurns groups={groups} render={group => <TurnGroup {...props} group={group} motion={motion} autoFold={autoFold} pinnedKeys={pinnedKeys} selectedProcessKeys={selectedProcessKeys} isAwaitingModel={isAwaitingModel && group.key === groups.at(-1)?.key} />} /> <RetiringTurns groups={renderedGroups} shouldRetire={shouldRetire} onCommitted={flushPendingScrollActions} render={group => <TurnGroup {...props} group={group} motion={motion} autoFold={autoFold} pinnedKeys={pinnedKeys} selectedProcessKeys={selectedProcessKeys} isAwaitingModel={isAwaitingModel && group.key === groups.at(-1)?.key} />} />
{windowSlice.hiddenNewer > 0 && (
<div className={css.newerBar} data-reader-newer-bar>
<span className={css.newerBarText}>以下还有 {hiddenNewerTurns} 轮较新对话</span>
<div className={css.newerBarActions}>
<button
type="button"
className={css.newerBarButton}
onClick={() => {
setWindowState(cur => expandNewerInWindow(groups, cur, renderTurnLimit));
}}
>
向下展开
</button>
<button
type="button"
className={`${css.newerBarButton} ${css.newerBarPrimary}`}
onClick={jumpToLatest}
>
回到最新
</button>
</div>
</div>
)}
{pendingInputs.map((item, index) => { {pendingInputs.map((item, index) => {
const submission = 'requestId' in item ? item : undefined; const submission = 'requestId' in item ? item : undefined;
const text = submission?.text ?? inboxText(item as PendingInboxItem); const text = submission?.text ?? inboxText(item as PendingInboxItem);
@ -917,7 +1244,7 @@ export function Reader(props: ReaderProps) {
<strong>{pending.kind === 'question' ? '需要你回答一个问题' : '需要你的确认'}</strong> <strong>{pending.kind === 'question' ? '需要你回答一个问题' : '需要你的确认'}</strong>
<span>请在下方原生操作区处理。此提示不会收进执行过程。</span> <span>请在下方原生操作区处理。此提示不会收进执行过程。</span>
</div>} </div>}
{scroll.detached && <div className={css.jumpDock}><button type="button" className={css.jump} aria-label="回到底部" title="回到底部" onClick={scroll.jump}> {(scroll.detached || windowSlice.hiddenNewer > 0) && <div className={css.jumpDock}><button type="button" className={css.jump} aria-label="回到底部" title="回到底部" onClick={jumpToLatest}>
<svg viewBox="0 0 14 14" width="14" height="14" aria-hidden="true"><path d="M3 5.5 7 9.5 11 5.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg> <svg viewBox="0 0 14 14" width="14" height="14" aria-hidden="true"><path d="M3 5.5 7 9.5 11 5.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
</button></div>} </button></div>}
</div> </div>

View File

@ -14,6 +14,76 @@
border-bottom: 0.5px solid var(--dsw-alias-border-l2); border-bottom: 0.5px solid var(--dsw-alias-border-l2);
} }
.rowBlock {
display: flex;
flex-direction: column;
gap: 10px;
padding: 16px 0;
border-bottom: 0.5px solid var(--dsw-alias-border-l2);
}
.rowBlock .rowText {
padding-right: 0;
}
.turnLimitControls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
}
.turnLimitControls .segment {
flex: 1 1 280px;
width: auto;
margin-top: 0;
}
.customTurnWrap {
display: inline-flex;
align-items: center;
gap: 6px;
height: 36px;
padding: 0 10px;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: 10px;
background: var(--dsw-alias-bg-module-platform);
color: var(--dsw-alias-label-secondary);
font-size: 12px;
line-height: 18px;
box-sizing: border-box;
}
.customTurnWrap[data-active] {
border-color: var(--dsw-alias-state-business-primary);
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-bg-base);
}
.customTurnLabel,
.customTurnUnit {
white-space: nowrap;
}
.customTurnInput {
width: 52px;
height: 24px;
padding: 0 6px;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: 6px;
background: var(--dsw-alias-bg-base);
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 12px;
font-variant-numeric: tabular-nums;
text-align: center;
outline: none;
}
.customTurnInput:focus {
border-color: var(--dsw-alias-state-business-primary);
}
.rowText { .rowText {
flex: 1; flex: 1;
min-width: 0; min-width: 0;

View File

@ -1,5 +1,16 @@
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react'; import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
import { frostedGlassOf, type FoldIntensity } from './fold-intensity.js'; import {
AI_BUBBLE_STYLES,
AI_BUBBLE_WIDTHS,
READER_THEMES,
aiBubbleStyleOf,
aiBubbleWidthOf,
readerThemeOf,
type AiBubbleStyle,
type AiBubbleWidth,
type ReaderTheme,
} from './appearance.js';
import { type FoldIntensity } from './fold-intensity.js';
import { import {
BINDINGS_CHANGED_EVENT, BINDINGS_CHANGED_EVENT,
bindingKeycap, bindingKeycap,
@ -11,14 +22,25 @@ import {
import type { ChatPrefs } from './chat/bindings-store.js'; import type { ChatPrefs } from './chat/bindings-store.js';
import { deliverableOpenModeOf, type DeliverableOpenMode } from './open-file.js'; import { deliverableOpenModeOf, type DeliverableOpenMode } from './open-file.js';
import { settingsCopyFor, type SettingsCopy, type SettingsCopyKey } from './settings-copy.js'; import { settingsCopyFor, type SettingsCopy, type SettingsCopyKey } from './settings-copy.js';
import {
MAX_RENDER_TURNS,
MIN_RENDER_TURNS,
normalizeRenderTurnLimit,
RENDER_TURN_PRESETS,
renderTurnLimitOf,
} from './turn-window.js';
import css from './SettingsSection.module.css'; import css from './SettingsSection.module.css';
export interface ReaderPrefsSnapshot { export interface ReaderPrefsSnapshot {
deliverableOpenMode?: DeliverableOpenMode; deliverableOpenMode?: DeliverableOpenMode;
frostedGlass?: boolean; frostedGlass?: boolean;
readerTheme?: ReaderTheme;
aiBubbleStyle?: AiBubbleStyle;
aiBubbleWidth?: AiBubbleWidth;
foldIntensity?: FoldIntensity; foldIntensity?: FoldIntensity;
autoFold?: boolean; autoFold?: boolean;
processOnly?: boolean; processOnly?: boolean;
renderTurnLimit?: number;
} }
export interface OpenPrefs { export interface OpenPrefs {
@ -27,8 +49,12 @@ export interface OpenPrefs {
actions: { actions: {
setDeliverableOpenMode: (value: DeliverableOpenMode) => void; setDeliverableOpenMode: (value: DeliverableOpenMode) => void;
setFrostedGlass: (value: boolean) => void; setFrostedGlass: (value: boolean) => void;
setReaderTheme?: (value: ReaderTheme) => void;
setAiBubbleStyle?: (value: AiBubbleStyle) => void;
setAiBubbleWidth?: (value: AiBubbleWidth) => void;
setFoldIntensity?: (value: FoldIntensity) => void; setFoldIntensity?: (value: FoldIntensity) => void;
setAutoFold?: (value: boolean) => void; setAutoFold?: (value: boolean) => void;
setRenderTurnLimit?: (value: number) => void;
}; };
} }
@ -65,8 +91,30 @@ export function SettingsSection(props: SettingsProps) {
() => ({} as ReaderPrefsSnapshot), () => ({} as ReaderPrefsSnapshot),
); );
const mode = deliverableOpenModeOf(snap.deliverableOpenMode); const mode = deliverableOpenModeOf(snap.deliverableOpenMode);
const glass = frostedGlassOf(snap); const readerTheme = readerThemeOf(snap);
const aiBubbleStyle = aiBubbleStyleOf(snap);
const aiBubbleWidth = aiBubbleWidthOf(snap);
const autoFold = snap.autoFold !== false && snap.foldIntensity !== 0; const autoFold = snap.autoFold !== false && snap.foldIntensity !== 0;
const renderTurnLimit = renderTurnLimitOf(snap);
const [turnDraft, setTurnDraft] = useState(() => (renderTurnLimit > 0 ? String(renderTurnLimit) : ''));
useEffect(() => {
setTurnDraft(renderTurnLimit > 0 ? String(renderTurnLimit) : '');
}, [renderTurnLimit]);
const commitTurnDraft = () => {
const trimmed = turnDraft.trim();
if (!/^\d+$/.test(trimmed)) {
setTurnDraft(renderTurnLimit > 0 ? String(renderTurnLimit) : '');
return;
}
const parsed = Number(trimmed);
if (parsed < MIN_RENDER_TURNS) {
setTurnDraft(renderTurnLimit > 0 ? String(renderTurnLimit) : '');
return;
}
const next = normalizeRenderTurnLimit(parsed);
props.prefs.actions.setRenderTurnLimit?.(next);
setTurnDraft(String(next));
};
const setMode = (value: DeliverableOpenMode) => { const setMode = (value: DeliverableOpenMode) => {
props.prefs.actions.setDeliverableOpenMode(value); props.prefs.actions.setDeliverableOpenMode(value);
}; };
@ -142,20 +190,98 @@ export function SettingsSection(props: SettingsProps) {
/> />
</div> </div>
<div className={css.row}> <div
className={css.rowBlock}
data-better-display-theme={readerTheme}
data-better-display-glass={readerTheme === 'glass' ? 'on' : 'off'}
>
<div className={css.rowText}> <div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'glassTitle')}</div> <div className={css.title}>{text(props, copy, 'themeTitle')}</div>
<div className={css.desc}>{text(props, copy, 'glassDescription')}</div> <div className={css.desc}>{text(props, copy, 'themeDescription')}</div>
</div>
<div className={css.segment} role="group" aria-label={text(props, copy, 'themeTitle')}>
{READER_THEMES.map(themeOption => {
const labelKey: keyof SettingsCopy = themeOption === 'host'
? 'themeHost'
: themeOption === 'light'
? 'themeLight'
: themeOption === 'dark'
? 'themeDark'
: 'themeGlass';
const active = readerTheme === themeOption;
return (
<button
key={themeOption}
type="button"
className={css.segmentStop}
data-on={active || undefined}
aria-pressed={active}
onClick={() => {
if (props.prefs.actions.setReaderTheme) {
props.prefs.actions.setReaderTheme(themeOption);
} else {
props.prefs.actions.setFrostedGlass(themeOption === 'glass');
}
}}
>
{text(props, copy, labelKey)}
</button>
);
})}
</div>
</div>
<div className={css.rowBlock} data-better-display-bubble-style={aiBubbleStyle}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'bubbleStyleTitle')}</div>
<div className={css.desc}>{text(props, copy, 'bubbleStyleDescription')}</div>
</div>
<div className={css.segment} role="group" aria-label={text(props, copy, 'bubbleStyleTitle')}>
{AI_BUBBLE_STYLES.map(styleOption => {
const labelKey: keyof SettingsCopy = styleOption === 'soft'
? 'bubbleStyleSoft'
: styleOption === 'card'
? 'bubbleStyleCard'
: 'bubbleStylePlain';
const active = aiBubbleStyle === styleOption;
return (
<button
key={styleOption}
type="button"
className={css.segmentStop}
data-on={active || undefined}
aria-pressed={active}
onClick={() => { props.prefs.actions.setAiBubbleStyle?.(styleOption); }}
>
{text(props, copy, labelKey)}
</button>
);
})}
</div>
</div>
<div className={css.rowBlock} data-better-display-bubble-width={aiBubbleWidth}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'bubbleWidthTitle')}</div>
<div className={css.desc}>{text(props, copy, 'bubbleWidthDescription')}</div>
</div>
<div className={css.segment} role="group" aria-label={text(props, copy, 'bubbleWidthTitle')}>
{AI_BUBBLE_WIDTHS.map(widthOption => {
const active = aiBubbleWidth === widthOption;
return (
<button
key={widthOption}
type="button"
className={css.segmentStop}
data-on={active || undefined}
aria-pressed={active}
onClick={() => { props.prefs.actions.setAiBubbleWidth?.(widthOption); }}
>
{`${widthOption}%`}
</button>
);
})}
</div> </div>
<button
type="button"
role="switch"
aria-checked={glass}
className={css.switch}
data-on={glass || undefined}
data-better-display-glass={glass ? 'on' : 'off'}
onClick={() => { props.prefs.actions.setFrostedGlass(!glass); }}
/>
</div> </div>
<div className={css.row}> <div className={css.row}>
@ -177,6 +303,56 @@ export function SettingsSection(props: SettingsProps) {
/> />
</div> </div>
<div className={css.rowBlock} data-better-display-render-turns={renderTurnLimit}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'renderTurnsTitle')}</div>
<div className={css.desc}>{text(props, copy, 'renderTurnsDescription')}</div>
</div>
<div className={css.turnLimitControls}>
<div className={css.segment} role="group" aria-label={text(props, copy, 'renderTurnsTitle')}>
{RENDER_TURN_PRESETS.map(preset => (
<button
key={preset}
type="button"
className={css.segmentStop}
data-on={renderTurnLimit === preset || undefined}
aria-pressed={renderTurnLimit === preset}
onClick={() => { props.prefs.actions.setRenderTurnLimit?.(preset); }}
>
{preset === 0 ? text(props, copy, 'renderTurnsAll') : `${preset} ${text(props, copy, 'renderTurnsUnit')}`}
</button>
))}
</div>
<label
className={css.customTurnWrap}
data-active={(renderTurnLimit > 0 && !RENDER_TURN_PRESETS.includes(renderTurnLimit as (typeof RENDER_TURN_PRESETS)[number])) || undefined}
>
<span className={css.customTurnLabel}>{text(props, copy, 'renderTurnsCustom')}</span>
<input
type="number"
inputMode="numeric"
min={MIN_RENDER_TURNS}
max={MAX_RENDER_TURNS}
className={css.customTurnInput}
aria-label={text(props, copy, 'renderTurnsCustom')}
value={turnDraft}
placeholder={String(renderTurnLimit || 6)}
onChange={event => { setTurnDraft(event.target.value); }}
onBlur={commitTurnDraft}
onKeyDown={event => {
if (event.key === 'Enter') {
event.currentTarget.blur();
} else if (event.key === 'Escape') {
setTurnDraft(renderTurnLimit > 0 ? String(renderTurnLimit) : '');
event.currentTarget.blur();
}
}}
/>
<span className={css.customTurnUnit}>{text(props, copy, 'renderTurnsUnit')}</span>
</label>
</div>
</div>
{chat ? ( {chat ? (
<section className={css.block} data-better-chat-shortcuts> <section className={css.block} data-better-chat-shortcuts>
<div className={css.title}>{text(props, copy, 'shortcutTitle')}</div> <div className={css.title}>{text(props, copy, 'shortcutTitle')}</div>

View File

@ -2,7 +2,7 @@
.slot { .slot {
position: sticky; position: sticky;
top: 0; top: 0;
z-index: 10; z-index: 20;
height: 0; height: 0;
pointer-events: none; pointer-events: none;
} }
@ -11,27 +11,33 @@
--turn-rail-band: calc( --turn-rail-band: calc(
var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px) var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px)
); );
--turn-preview-height: 100px;
position: absolute; position: absolute;
top: calc(var(--turn-rail-band) / 2); top: calc(var(--turn-rail-band) / 2);
/* .root is the containing block (container-type creates layout containment) right: 8px;
and already reserves the right gutter via its own padding, so a small width: 24px;
positive inset keeps the rail inside the gutter, clear of the text. */
right: 6px;
width: 26px;
height: min( height: min(
var(--turn-natural-height), var(--turn-natural-height),
max(0px, calc(var(--turn-rail-band) - 64px)), max(48px, calc(var(--turn-rail-band) - 64px)),
420px 380px
); );
cursor: pointer;
pointer-events: auto; pointer-events: auto;
transform: translateY(-50%); transform: translateY(-50%);
transition: height 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
.scroller { .collapsedFrame {
position: relative;
width: 100%;
height: 100%;
transition: opacity 120ms ease;
}
.frame[data-open] .collapsedFrame {
opacity: 0;
pointer-events: none;
}
.collapsedScroller {
position: absolute; position: absolute;
inset: 0; inset: 0;
overflow-y: auto; overflow-y: auto;
@ -39,65 +45,69 @@
scrollbar-width: none; scrollbar-width: none;
} }
.scroller::-webkit-scrollbar { .collapsedScroller::-webkit-scrollbar {
display: none; display: none;
} }
.fadeTop { .fadeTop {
mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%); mask-image: linear-gradient(to bottom, transparent 0, #000 20px, #000 100%);
-webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%); -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 20px, #000 100%);
} }
.fadeBottom { .fadeBottom {
mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%); mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 20px), transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%); -webkit-mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 20px), transparent 100%);
} }
.fadeTop.fadeBottom { .fadeTop.fadeBottom {
mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 calc(100% - 24px), transparent 100%); mask-image: linear-gradient(to bottom, transparent 0, #000 20px, #000 calc(100% - 20px), transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 calc(100% - 24px), transparent 100%); -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 20px, #000 calc(100% - 20px), transparent 100%);
} }
.marks { .collapsedMarks {
position: relative; position: relative;
height: var(--turn-natural-height); height: var(--turn-natural-height);
} }
.markPosition { .collapsedItem {
position: absolute; position: absolute;
top: calc(var(--turn-natural-position) + var(--turn-rail-inset)); top: calc(var(--turn-natural-position) + var(--turn-rail-inset));
right: 0; right: 0;
left: 0;
height: 12px;
transform: translateY(-50%);
transition: top 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.mark {
position: absolute;
inset: 0 0 0 auto;
width: 24px; width: 24px;
height: 10px;
padding: 0; padding: 0;
border: 0; border: 0;
background: transparent; background: transparent;
cursor: pointer; cursor: pointer;
pointer-events: none; transform: translateY(-50%);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end; justify-content: flex-end;
} }
.tick { .collapsedTick {
width: 10px;
height: 2px;
border-radius: 2px; border-radius: 2px;
flex: none; background: var(--dsw-alias-label-tertiary);
transition: width 100ms cubic-bezier(0.16, 1, 0.3, 1), opacity: 0.45;
height 100ms cubic-bezier(0.16, 1, 0.3, 1), transition: width 140ms ease, height 140ms ease, opacity 140ms ease, background-color 140ms ease;
opacity 100ms ease,
background-color 140ms ease;
} }
.markBusy .tick { .collapsedItem[data-unloaded] .collapsedTick {
animation: markBusyPulse 1s ease-in-out infinite alternate; opacity: 0.24;
}
.collapsedItem[data-active] .collapsedTick {
width: 12px;
height: 2.5px;
opacity: 1;
background: var(--dsw-alias-label-primary);
}
.collapsedItem[data-busy] .collapsedTick,
.row[data-busy] .rowTick {
animation: markBusyPulse 0.9s ease-in-out infinite alternate;
} }
@keyframes markBusyPulse { @keyframes markBusyPulse {
@ -105,65 +115,174 @@
to { width: 18px; opacity: 1; } to { width: 18px; opacity: 1; }
} }
.preview { .card {
position: absolute; position: absolute;
top: clamp( top: 50%;
0px, right: 0;
calc( transform: translateY(-50%);
var(--turn-natural-position) + var(--turn-rail-inset) width: min(320px, calc(100cqw - 32px));
- var(--turn-scroll-top, 0px) - var(--turn-preview-height) / 2 max-height: min(440px, max(180px, calc(var(--turn-rail-band) - 48px)));
), display: flex;
calc(100% - var(--turn-preview-height)) flex-direction: column;
);
right: calc(100% + 10px);
box-sizing: border-box; box-sizing: border-box;
width: min(280px, calc(100cqw - 120px)); border: 1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.08));
max-height: var(--turn-preview-height); border-radius: 14px;
background: var(--dsw-alias-bg-base, #ffffff);
box-shadow: var(--dsw-elevation-panel, 0 8px 28px rgba(0, 0, 0, 0.12));
backdrop-filter: blur(16px);
overflow: hidden; overflow: hidden;
padding: 10px 12px; animation: cardReveal 140ms cubic-bezier(0.16, 1, 0.3, 1);
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 10px;
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-bg-base);
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.12);
backdrop-filter: blur(12px);
pointer-events: none;
animation: previewFadeIn 120ms ease-out;
transition: top 140ms cubic-bezier(0.2, 0.8, 0.2, 1);
z-index: 40;
} }
@keyframes previewFadeIn { :global([data-reader-glass]) .card {
from { opacity: 0; transform: translateX(4px); } background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255, 255, 255, 0.85)) 86%, transparent);
to { opacity: 1; transform: translateX(0); } backdrop-filter: blur(18px);
} }
.previewPrompt { @keyframes cardReveal {
font-size: 12px; from {
opacity: 0;
transform: translateY(-50%) translateX(6px);
}
to {
opacity: 1;
transform: translateY(-50%) translateX(0);
}
}
.list {
position: relative;
display: flex;
flex-direction: column;
gap: 2px;
padding: 6px 6px;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-width: thin;
scrollbar-color: rgba(128, 128, 128, 0.35) transparent;
}
.list::-webkit-scrollbar {
width: 5px;
}
.list::-webkit-scrollbar-track {
background: transparent;
}
.list::-webkit-scrollbar-thumb {
border-radius: 999px;
background: rgba(128, 128, 128, 0.32);
}
.list::-webkit-scrollbar-thumb:hover {
background: rgba(128, 128, 128, 0.5);
}
.row {
flex: none;
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
width: 100%;
min-height: 30px;
padding: 5px 10px 5px 14px;
border: 0;
border-radius: 8px;
background: transparent;
cursor: pointer;
text-align: right;
font: inherit;
transition: background-color 120ms ease;
}
.row:hover {
background: var(--dsw-alias-interactive-bg-hover);
}
.rowLabel {
flex: 1 1 auto;
min-width: 0;
font-size: 12.5px;
line-height: 18px; line-height: 18px;
font-weight: 500; font-weight: 400;
display: -webkit-box; color: var(--dsw-alias-label-secondary);
-webkit-line-clamp: 2; white-space: nowrap;
-webkit-box-orient: vertical;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
word-break: break-word; text-align: right;
} }
.previewResponse { .row:hover .rowLabel {
margin-top: 4px; color: var(--dsw-alias-label-primary);
}
.row[data-unloaded] .rowLabel {
color: var(--dsw-alias-label-tertiary); color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 16px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
} }
@media (max-width: 960px) { .row[data-active] .rowLabel {
color: var(--dsw-alias-label-primary);
font-weight: 600;
}
.rowTickSlot {
flex: none;
width: 24px;
height: 14px;
display: flex;
align-items: center;
justify-content: flex-end;
}
.rowTick {
width: 8px;
height: 2px;
border-radius: 2px;
background: var(--dsw-alias-label-tertiary);
opacity: 0.45;
transition: width 140ms ease, opacity 140ms ease, background-color 140ms ease;
}
.row:hover .rowTick {
width: 14px;
opacity: 0.8;
background: var(--dsw-alias-label-primary);
}
.row[data-unloaded]:not(:hover):not([data-active]) .rowTick {
opacity: 0.25;
}
.row[data-active] .rowTick {
width: 24px;
height: 2px;
opacity: 1;
background: var(--dsw-alias-label-primary);
}
:global([data-motion=off]) .card,
:global([data-motion=off]) .collapsedFrame,
:global([data-motion=off]) .collapsedTick,
:global([data-motion=off]) .row,
:global([data-motion=off]) .rowTick {
transition: none !important;
animation: none !important;
}
@media (prefers-reduced-motion: reduce) {
.card,
.collapsedFrame,
.collapsedTick,
.row,
.rowTick {
transition: none !important;
animation: none !important;
}
}
@media (max-width: 640px) {
.slot { .slot {
display: none !important; display: none !important;
} }

View File

@ -1,6 +1,6 @@
import { import {
memo, useEffect, useId, useRef, useState, memo, useCallback, useEffect, useId, useLayoutEffect, useRef, useState,
type CSSProperties, type MouseEvent, type PointerEvent, type CSSProperties, type FocusEvent, type KeyboardEvent,
} from 'react'; } from 'react';
import type { TimelineItem } from './timeline.js'; import type { TimelineItem } from './timeline.js';
import css from './TimelineRail.module.css'; import css from './TimelineRail.module.css';
@ -12,94 +12,112 @@ interface TimelineRailProps {
onNavigate: (item: TimelineItem) => void; onNavigate: (item: TimelineItem) => void;
} }
const TURN_SPACING_PX = 12; const TURN_SPACING_PX = 10;
const RAIL_INSET_PX = 6; const RAIL_INSET_PX = 6;
const FADE_PX = 24; const FADE_PX = 20;
const CLOSE_GRACE_MS = 160;
type TurnPositionStyle = CSSProperties & { type RailFrameStyle = CSSProperties & {
readonly '--turn-natural-height': string;
readonly '--turn-rail-inset': string;
};
type CollapsedItemStyle = CSSProperties & {
readonly '--turn-natural-position': string; readonly '--turn-natural-position': string;
}; };
type TurnFrameStyle = CSSProperties & { function frameStyle(count: number): RailFrameStyle {
readonly '--turn-natural-height': string;
readonly '--turn-rail-inset': string;
readonly '--turn-scroll-top': string;
};
function itemPosition(index: number): TurnPositionStyle {
return { '--turn-natural-position': `${index * TURN_SPACING_PX}px` };
}
function frameStyle(count: number, scrollTop: number): TurnFrameStyle {
return { return {
'--turn-natural-height': `${(count - 1) * TURN_SPACING_PX + 2 * RAIL_INSET_PX}px`, '--turn-natural-height': `${Math.max(1, count - 1) * TURN_SPACING_PX + 2 * RAIL_INSET_PX}px`,
'--turn-rail-inset': `${RAIL_INSET_PX}px`, '--turn-rail-inset': `${RAIL_INSET_PX}px`,
'--turn-scroll-top': `${scrollTop}px`,
}; };
} }
function itemIndexAtPointer( function collapsedPosition(index: number): CollapsedItemStyle {
items: readonly TimelineItem[], return { '--turn-natural-position': `${index * TURN_SPACING_PX}px` };
frame: HTMLElement,
scrollTop: number,
clientY: number,
): number {
const rect = frame.getBoundingClientRect();
const offset = clientY - rect.top + scrollTop - RAIL_INSET_PX;
return Math.max(0, Math.min(items.length - 1, Math.round(offset / TURN_SPACING_PX)));
} }
interface RailScrollState { interface RailScrollState {
readonly top: number;
readonly canScrollUp: boolean; readonly canScrollUp: boolean;
readonly canScrollDown: boolean; readonly canScrollDown: boolean;
} }
const RAIL_AT_REST: RailScrollState = { top: 0, canScrollUp: false, canScrollDown: false }; const RAIL_AT_REST: RailScrollState = { canScrollUp: false, canScrollDown: false };
function railScrollState(scroller: HTMLElement): RailScrollState { function railScrollState(scroller: HTMLElement): RailScrollState {
const top = scroller.scrollTop; const top = scroller.scrollTop;
return { return {
top,
canScrollUp: top > 1, canScrollUp: top > 1,
canScrollDown: top < scroller.scrollHeight - scroller.clientHeight - 1, canScrollDown: top < scroller.scrollHeight - scroller.clientHeight - 1,
}; };
} }
function promptLabelFor(item: TimelineItem): string {
const text = item.prompt.trim().replace(/\s+/g, ' ');
return text.length > 0 ? text : `第 ${item.turn + 1} 轮`;
}
export const TimelineRail = memo(function TimelineRail({ export const TimelineRail = memo(function TimelineRail({
items, items,
activeTurn, activeTurn,
busyTurn, busyTurn,
onNavigate, onNavigate,
}: TimelineRailProps) { }: TimelineRailProps) {
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null); const [open, setOpen] = useState(false);
const [scrollState, setScrollState] = useState<RailScrollState>(RAIL_AT_REST); const [collapsedScroll, setCollapsedScroll] = useState<RailScrollState>(RAIL_AT_REST);
const scrollerRef = useRef<HTMLDivElement | null>(null); const frameRef = useRef<HTMLElement | null>(null);
const pointerInsideRef = useRef(false); const collapsedScrollerRef = useRef<HTMLDivElement | null>(null);
const previewId = useId(); const listRef = useRef<HTMLDivElement | null>(null);
const closeTimerRef = useRef<number>(0);
const cardId = useId();
const syncScrollState = () => { const cancelClose = useCallback(() => {
const scroller = scrollerRef.current; if (closeTimerRef.current) {
if (!scroller) return; window.clearTimeout(closeTimerRef.current);
const next = railScrollState(scroller); closeTimerRef.current = 0;
setScrollState(cur => (cur.top === next.top && cur.canScrollUp === next.canScrollUp && cur.canScrollDown === next.canScrollDown ? cur : next)); }
};
useEffect(() => {
const scroller = scrollerRef.current;
if (!scroller || typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(syncScrollState);
observer.observe(scroller);
return () => observer.disconnect();
}, []); }, []);
useEffect(syncScrollState, [items.length]); const openPopover = useCallback(() => {
cancelClose();
setOpen(true);
}, [cancelClose]);
const scheduleClose = useCallback(() => {
cancelClose();
closeTimerRef.current = window.setTimeout(() => {
closeTimerRef.current = 0;
setOpen(false);
}, CLOSE_GRACE_MS);
}, [cancelClose]);
useEffect(() => () => cancelClose(), [cancelClose]);
const syncCollapsedScroll = useCallback(() => {
const scroller = collapsedScrollerRef.current;
if (!scroller) return;
const next = railScrollState(scroller);
setCollapsedScroll(cur =>
cur.canScrollUp === next.canScrollUp && cur.canScrollDown === next.canScrollDown ? cur : next,
);
}, []);
// Keep active mark visible
useEffect(() => { useEffect(() => {
const scroller = scrollerRef.current; const scroller = collapsedScrollerRef.current;
if (!scroller || typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(syncCollapsedScroll);
observer.observe(scroller);
return () => observer.disconnect();
}, [syncCollapsedScroll]);
useEffect(syncCollapsedScroll, [items.length, syncCollapsedScroll]);
// Keep the active dash visible inside the collapsed mini-rail.
useEffect(() => {
if (open) return;
const scroller = collapsedScrollerRef.current;
const index = items.findIndex(item => item.turn === activeTurn); const index = items.findIndex(item => item.turn === activeTurn);
if (!scroller || index < 0 || pointerInsideRef.current) return; if (!scroller || index < 0) return;
const markTop = index * TURN_SPACING_PX + RAIL_INSET_PX; const markTop = index * TURN_SPACING_PX + RAIL_INSET_PX;
const viewTop = scroller.scrollTop; const viewTop = scroller.scrollTop;
const viewHeight = scroller.clientHeight; const viewHeight = scroller.clientHeight;
@ -110,150 +128,141 @@ export const TimelineRail = memo(function TimelineRail({
} else { } else {
scroller.scrollTop = target; scroller.scrollTop = target;
} }
syncScrollState(); syncCollapsedScroll();
}, [activeTurn, items]); }, [activeTurn, items, open, syncCollapsedScroll]);
// Center the active row directly via scrollTop when the floating list opens.
useLayoutEffect(() => {
if (!open) return;
const list = listRef.current;
if (!list) return;
const target = activeTurn === null
? null
: list.querySelector<HTMLElement>(`[data-turn-row="${activeTurn}"]`);
if (target) {
const desiredTop = target.offsetTop - Math.max(0, (list.clientHeight - target.offsetHeight) / 2);
list.scrollTop = Math.max(0, desiredTop);
} else {
list.scrollTop = list.scrollHeight;
}
}, [open]);
if (items.length < 2) return null; if (items.length < 2) return null;
const preview = hoveredIndex !== null && hoveredIndex >= 0 ? items[hoveredIndex] : undefined; const fadeClasses = [css.collapsedScroller];
const previewPosition = hoveredIndex !== null && hoveredIndex >= 0 ? itemPosition(hoveredIndex) : undefined; if (collapsedScroll.canScrollUp) fadeClasses.push(css.fadeTop);
if (collapsedScroll.canScrollDown) fadeClasses.push(css.fadeBottom);
const onPointerMove = (event: PointerEvent<HTMLElement>) => { const onBlurCapture = (event: FocusEvent<HTMLElement>) => {
const scroller = scrollerRef.current; if (!frameRef.current?.contains(event.relatedTarget as Node | null)) {
const scrollTop = scroller?.scrollTop ?? 0; cancelClose();
const idx = itemIndexAtPointer(items, event.currentTarget, scrollTop, event.clientY); setOpen(false);
setHoveredIndex(idx); }
}; };
const onPointerLeave = () => { const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
pointerInsideRef.current = false; if (event.key === 'Escape' && open) {
setHoveredIndex(null); event.stopPropagation();
cancelClose();
setOpen(false);
}
}; };
const navigateAtPointer = (event: MouseEvent<HTMLElement>) => {
const scroller = scrollerRef.current;
const scrollTop = scroller?.scrollTop ?? 0;
const idx = itemIndexAtPointer(items, event.currentTarget, scrollTop, event.clientY);
const item = items[idx];
if (item !== undefined) onNavigate(item);
};
const fadeClasses = [css.scroller];
if (scrollState.canScrollUp) fadeClasses.push(css.fadeTop);
if (scrollState.canScrollDown) fadeClasses.push(css.fadeBottom);
return ( return (
<div className={css.slot}> <div className={css.slot}>
<nav <nav
ref={frameRef}
className={css.frame} className={css.frame}
style={frameStyle(items.length, scrollState.top)} style={frameStyle(items.length)}
aria-label="轮次导航时间轴" aria-label="对话轮次目录"
onClick={navigateAtPointer} data-open={open || undefined}
onPointerMove={onPointerMove} onPointerEnter={openPopover}
onPointerEnter={() => { pointerInsideRef.current = true; }} onPointerLeave={scheduleClose}
onPointerLeave={onPointerLeave} onFocusCapture={openPopover}
onMouseDown={event => { event.preventDefault(); }} onBlurCapture={onBlurCapture}
onKeyDown={onKeyDown}
> >
<div <div
ref={scrollerRef} className={css.collapsedFrame}
className={fadeClasses.join(' ')} aria-hidden={open || undefined}
onScroll={syncScrollState}
> >
<div className={css.marks}> <div
{items.map((item, index) => { ref={collapsedScrollerRef}
const isBusy = busyTurn === item.turn; className={fadeClasses.join(' ')}
const isActive = activeTurn === item.turn; onScroll={syncCollapsedScroll}
const isUnloaded = item.anchor.kind === 'unloaded'; >
<div className={css.collapsedMarks}>
// Wave calculation: peak at cursor, smoothly tapering off in width and height {items.map((item, index) => {
let width = isUnloaded ? 6 : 8; const isActive = activeTurn === item.turn;
let height = 2; const isBusy = busyTurn === item.turn;
let opacity = isUnloaded ? 0.3 : 0.45; const isUnloaded = item.anchor.kind === 'unloaded';
let background = 'var(--dsw-alias-label-tertiary)'; return (
if (hoveredIndex !== null) {
const diff = Math.abs(index - hoveredIndex);
if (diff === 0) {
// Cursor peak (最长最高)
width = 26;
height = 2.8;
opacity = 1.0;
background = 'var(--dsw-alias-label-primary)';
} else if (diff === 1) {
// 旁边第 1 阶 (次长次高)
width = 18;
height = 2.2;
opacity = 0.8;
background = 'var(--dsw-alias-label-primary)';
} else if (diff === 2) {
// 旁边第 2 阶 (继续变矮变短)
width = 13;
height = 1.8;
opacity = 0.6;
background = 'var(--dsw-alias-label-secondary)';
} else if (diff === 3) {
// 旁边第 3 阶 (平缓过渡)
width = 9;
height = 1.6;
opacity = 0.45;
background = 'var(--dsw-alias-label-tertiary)';
} else {
// 远离光标的基线
width = 8;
height = 2;
opacity = 0.35;
background = 'var(--dsw-alias-label-tertiary)';
}
} else if (isActive) {
width = 20;
height = 2.4;
opacity = 0.95;
background = 'var(--dsw-alias-label-primary)';
}
const tickStyle: CSSProperties = {
width: `${width}px`,
height: `${height}px`,
opacity,
backgroundColor: background,
};
const markClasses = [css.mark];
if (isBusy) markClasses.push(css.markBusy);
return (
<div key={item.turn} className={css.markPosition} style={itemPosition(index)}>
<button <button
key={item.turn}
type="button" type="button"
className={markClasses.join(' ')} tabIndex={open ? -1 : 0}
aria-label={`第 ${item.turn + 1} 轮`} className={css.collapsedItem}
aria-current={isActive ? 'true' : undefined} style={collapsedPosition(index)}
aria-busy={isBusy ? 'true' : undefined} data-active={isActive || undefined}
aria-describedby={hoveredIndex === index ? previewId : undefined} data-busy={isBusy || undefined}
data-unloaded={isUnloaded || undefined}
aria-label={promptLabelFor(item)}
aria-expanded={open}
aria-controls={open ? cardId : undefined}
onMouseDown={event => { event.preventDefault(); }} onMouseDown={event => { event.preventDefault(); }}
onClick={(e) => { onClick={() => {
e.stopPropagation(); openPopover();
onNavigate(item);
}} }}
onFocus={() => setHoveredIndex(index)}
onBlur={() => setHoveredIndex(null)}
> >
<span className={css.tick} style={tickStyle} /> <span className={css.collapsedTick} />
</button> </button>
</div> );
); })}
})} </div>
</div> </div>
</div> </div>
{preview !== undefined && previewPosition !== undefined && ( {open && (
<div id={previewId} role="tooltip" className={css.preview} style={previewPosition}> <div
<div className={css.previewPrompt}> id={cardId}
{preview.prompt || `第 ${preview.turn + 1} 轮`} className={css.card}
role="region"
aria-label="选择对话轮次"
data-reader-timeline-popover
>
<div ref={listRef} className={css.list}>
{items.map(item => {
const isActive = activeTurn === item.turn;
const isBusy = busyTurn === item.turn;
const isUnloaded = item.anchor.kind === 'unloaded';
const label = promptLabelFor(item);
return (
<button
key={item.turn}
type="button"
className={css.row}
data-turn-row={item.turn}
data-active={isActive || undefined}
data-busy={isBusy || undefined}
data-unloaded={isUnloaded || undefined}
aria-current={isActive ? 'true' : undefined}
aria-busy={isBusy ? 'true' : undefined}
title={label}
onMouseDown={event => { event.preventDefault(); }}
onClick={() => {
cancelClose();
setOpen(false);
onNavigate(item);
}}
>
<span className={css.rowLabel}>{label}</span>
<span className={css.rowTickSlot} aria-hidden="true">
<span className={css.rowTick} />
</span>
</button>
);
})}
</div> </div>
{preview.response !== '' && (
<div className={css.previewResponse}>{preview.response}</div>
)}
</div> </div>
)} )}
</nav> </nav>

70
src/client/appearance.ts Normal file
View File

@ -0,0 +1,70 @@
/** Reader appearance theme persisted on `dsh.reader.v1`. Default follows the host. */
export type ReaderTheme = 'host' | 'light' | 'dark' | 'glass';
export const READER_THEME_DEFAULT: ReaderTheme = 'host';
export const READER_THEMES: readonly ReaderTheme[] = ['host', 'light', 'dark', 'glass'] as const;
/** AI response bubble surface style persisted on `dsh.reader.v1`. Default is soft. */
export type AiBubbleStyle = 'soft' | 'card' | 'plain';
export const AI_BUBBLE_STYLE_DEFAULT: AiBubbleStyle = 'soft';
export const AI_BUBBLE_STYLES: readonly AiBubbleStyle[] = ['soft', 'card', 'plain'] as const;
/** Max width percentage shared by AI bubbles and bottom process frames. Default is 90%. */
export type AiBubbleWidth = 70 | 80 | 90 | 100;
export const AI_BUBBLE_WIDTH_DEFAULT: AiBubbleWidth = 90;
export const AI_BUBBLE_WIDTHS: readonly AiBubbleWidth[] = [70, 80, 90, 100] as const;
export function normalizeReaderTheme(value: unknown): ReaderTheme {
if (value === 'host' || value === 'light' || value === 'dark' || value === 'glass') {
return value;
}
return READER_THEME_DEFAULT;
}
export function readerThemeOf(state: unknown): ReaderTheme {
if (state && typeof state === 'object') {
const rec = state as { readerTheme?: unknown; frostedGlass?: unknown };
if (rec.readerTheme === 'host' || rec.readerTheme === 'light' || rec.readerTheme === 'dark' || rec.readerTheme === 'glass') {
return rec.readerTheme;
}
if (rec.frostedGlass === true) return 'glass';
}
return READER_THEME_DEFAULT;
}
export function normalizeAiBubbleStyle(value: unknown): AiBubbleStyle {
if (value === 'soft' || value === 'card' || value === 'plain') {
return value;
}
return AI_BUBBLE_STYLE_DEFAULT;
}
export function aiBubbleStyleOf(state: unknown): AiBubbleStyle {
if (state && typeof state === 'object' && 'aiBubbleStyle' in state) {
return normalizeAiBubbleStyle((state as { aiBubbleStyle?: unknown }).aiBubbleStyle);
}
return AI_BUBBLE_STYLE_DEFAULT;
}
export function normalizeAiBubbleWidth(value: unknown): AiBubbleWidth {
if (value === 70 || value === 80 || value === 90 || value === 100) {
return value;
}
if (typeof value === 'string') {
const trimmed = value.trim().replace(/%$/, '');
if (trimmed === '70') return 70;
if (trimmed === '80') return 80;
if (trimmed === '90') return 90;
if (trimmed === '100') return 100;
}
return AI_BUBBLE_WIDTH_DEFAULT;
}
export function aiBubbleWidthOf(state: unknown): AiBubbleWidth {
if (state && typeof state === 'object' && 'aiBubbleWidth' in state) {
return normalizeAiBubbleWidth((state as { aiBubbleWidth?: unknown }).aiBubbleWidth);
}
return AI_BUBBLE_WIDTH_DEFAULT;
}

View File

@ -261,19 +261,28 @@ export function RetiringContent({ visible, children, onRetired }: { visible: boo
* drops the slot, so a departing turn lives for one collapse and no longer — * drops the slot, so a departing turn lives for one collapse and no longer —
* and a key that comes back later is re-added as a live slot. * and a key that comes back later is re-added as a live slot.
*/ */
export function RetiringTurns<T extends { readonly key: string }>({ groups, render }: { export function RetiringTurns<T extends { readonly key: string }>({ groups, render, shouldRetire, onCommitted }: {
groups: readonly T[]; groups: readonly T[];
render: (group: T) => ReactNode; render: (group: T) => ReactNode;
shouldRetire?: (key: string) => boolean;
onCommitted?: () => void;
}) { }) {
const [slots, setSlots] = useState<readonly TurnSlot<T>[]>(() => const [slots, setSlots] = useState<readonly TurnSlot<T>[]>(() =>
groups.map((group) => ({ group, live: true })), groups.map((group) => ({ group, live: true })),
); );
const shouldRetireRef = useRef(shouldRetire);
shouldRetireRef.current = shouldRetire;
const onCommittedRef = useRef(onCommitted);
onCommittedRef.current = onCommitted;
// Reconcile after every commit rather than during render: a key that left the // Reconcile after every commit rather than during render: a key that left the
// order becomes `live: false` and keeps its index, which is what lets the // order becomes `live: false` and keeps its index, which is what lets the
// collapse play in place instead of jumping the turn to the bottom. // collapse play in place instead of jumping the turn to the bottom.
useLayoutEffect(() => { useLayoutEffect(() => {
setSlots(current => reconcileTurnSlots(current, groups)); setSlots(current => reconcileTurnSlots(current, groups, shouldRetireRef.current));
}, [groups]); }, [groups]);
useLayoutEffect(() => {
onCommittedRef.current?.();
}, [slots]);
return ( return (
<> <>
{slots.map((slot) => ( {slots.map((slot) => (

View File

@ -4,11 +4,29 @@ export type SettingsCopyKey =
| 'openDescription' | 'openDescription'
| 'glassTitle' | 'glassTitle'
| 'glassDescription' | 'glassDescription'
| 'themeTitle'
| 'themeDescription'
| 'themeHost'
| 'themeLight'
| 'themeDark'
| 'themeGlass'
| 'bubbleStyleTitle'
| 'bubbleStyleDescription'
| 'bubbleStyleSoft'
| 'bubbleStyleCard'
| 'bubbleStylePlain'
| 'bubbleWidthTitle'
| 'bubbleWidthDescription'
| 'foldTitle' | 'foldTitle'
| 'foldDescription' | 'foldDescription'
| 'foldNone' | 'foldNone'
| 'foldStandard' | 'foldStandard'
| 'foldSummary' | 'foldSummary'
| 'renderTurnsTitle'
| 'renderTurnsDescription'
| 'renderTurnsAll'
| 'renderTurnsUnit'
| 'renderTurnsCustom'
| 'shortcutTitle' | 'shortcutTitle'
| 'shortcutDescription' | 'shortcutDescription'
| 'shortcutAllow' | 'shortcutAllow'
@ -30,11 +48,29 @@ export const en: SettingsCopy = {
openDescription: 'Off by default: chips and inline file mentions open in the system app. Turn this on to preview them in the right Sidebar, matching official chat. Reveal and folder actions still use the system file manager.', openDescription: 'Off by default: chips and inline file mentions open in the system app. Turn this on to preview them in the right Sidebar, matching official chat. Reveal and folder actions still use the system file manager.',
glassTitle: 'Translucent frosted glass', glassTitle: 'Translucent frosted glass',
glassDescription: 'Off by default: reading chrome stays opaque, matching the current Host look. Turn this on to let wallpaper and skins show through the panel; path and count chips stay clear until hover or focus.', glassDescription: 'Off by default: reading chrome stays opaque, matching the current Host look. Turn this on to let wallpaper and skins show through the panel; path and count chips stay clear until hover or focus.',
themeTitle: 'Appearance mode',
themeDescription: 'Follows the Host theme by default. Choose Light or Dark to override locally, or Frosted Glass to let wallpapers and skins show through with translucent panels.',
themeHost: 'Follow host',
themeLight: 'Light',
themeDark: 'Dark',
themeGlass: 'Frosted glass',
bubbleStyleTitle: 'AI reply bubble style',
bubbleStyleDescription: 'Default is Soft tint. Switch to Bordered card for stronger surface contrast, or Plain for a borderless stream layout.',
bubbleStyleSoft: 'Soft',
bubbleStyleCard: 'Bordered card',
bubbleStylePlain: 'Plain',
bubbleWidthTitle: 'AI reply max width',
bubbleWidthDescription: 'Controls the maximum width shared by AI reply bubbles and bottom process frames (90% by default).',
foldTitle: 'Auto-fold process', foldTitle: 'Auto-fold process',
foldDescription: 'Default on: collapses earlier steps when new thoughts appear. Turn off to keep all thinking and tools expanded in full.', foldDescription: 'Default on: collapses earlier steps when new thoughts appear. Turn off to keep all thinking and tools expanded in full.',
foldNone: 'Off', foldNone: 'Off',
foldStandard: 'On', foldStandard: 'On',
foldSummary: 'Summary', foldSummary: 'Summary',
renderTurnsTitle: 'Recent turns rendered per session',
renderTurnsDescription: 'Default is 6 turns to keep long conversations fast and smooth. Older turns stay one click away via "Load older" or the right-edge timeline jump list.',
renderTurnsAll: 'All',
renderTurnsUnit: 'turns',
renderTurnsCustom: 'Custom',
shortcutTitle: 'Approval card shortcuts', shortcutTitle: 'Approval card shortcuts',
shortcutDescription: 'Click a keycap and press the new combination. Allow-type actions use Enter, reject uses Esc; modifiers are free. Esc alone cancels while recording. Stored in the plugin config.', shortcutDescription: 'Click a keycap and press the new combination. Allow-type actions use Enter, reject uses Esc; modifiers are free. Esc alone cancels while recording. Stored in the plugin config.',
shortcutAllow: 'Allow once', shortcutAllow: 'Allow once',
@ -55,11 +91,29 @@ export const zh: SettingsCopy = {
openDescription: '默认关闭:产物芯片和正文中的文件提及会用系统应用打开。打开后与官方对话一致,在右侧栏预览。访达 / 资源管理器中的显示与打开所在文件夹不受此开关控制。', openDescription: '默认关闭:产物芯片和正文中的文件提及会用系统应用打开。打开后与官方对话一致,在右侧栏预览。访达 / 资源管理器中的显示与打开所在文件夹不受此开关控制。',
glassTitle: '半透明毛玻璃', glassTitle: '半透明毛玻璃',
glassDescription: '默认关闭:阅读栏保持不透明,和现在的 Host 观感一致。打开后透出宿主壁纸与皮肤;路径、行数等标签静止时透明,悬停或聚焦才显出轮廓。', glassDescription: '默认关闭:阅读栏保持不透明,和现在的 Host 观感一致。打开后透出宿主壁纸与皮肤;路径、行数等标签静止时透明,悬停或聚焦才显出轮廓。',
themeTitle: '外观样式',
themeDescription: '默认跟随宿主当前主题。也可手动指定浅色、深色,或开启半透明毛玻璃模式,让底层壁纸与皮肤透过对话区域柔和透出。',
themeHost: '跟随宿主',
themeLight: '浅色',
themeDark: '深色',
themeGlass: '毛玻璃',
bubbleStyleTitle: 'AI 回复气泡样式',
bubbleStyleDescription: '默认为柔灰气泡。可按偏好切换为更清晰的浅底描边卡片,或去掉外壳恢复无气泡纯文本流式阅读。',
bubbleStyleSoft: '柔灰',
bubbleStyleCard: '描边卡片',
bubbleStylePlain: '无气泡',
bubbleWidthTitle: 'AI 回复最大宽度',
bubbleWidthDescription: '同时作用于 AI 回复气泡与下方执行过程框的最大宽度比例,默认为 90%。',
foldTitle: '自动折叠过程', foldTitle: '自动折叠过程',
foldDescription: '默认开启:新思考产生时自动折叠此前步骤。关闭后全程展开,完整保留原始思考与工具流。', foldDescription: '默认开启:新思考产生时自动折叠此前步骤。关闭后全程展开,完整保留原始思考与工具流。',
foldNone: '关闭', foldNone: '关闭',
foldStandard: '开启', foldStandard: '开启',
foldSummary: '摘要', foldSummary: '摘要',
renderTurnsTitle: '默认渲染最近对话轮数',
renderTurnsDescription: '默认渲染最近 6 轮,大幅降低长会话打开与流式输出时的卡顿。更早的对话可在顶部点击「加载更早记录」,或通过右侧目录时间轴直接跳转查看。',
renderTurnsAll: '全部',
renderTurnsUnit: '轮',
renderTurnsCustom: '自定义',
shortcutTitle: '审批卡快捷键', shortcutTitle: '审批卡快捷键',
shortcutDescription: '点键帽后按下新的组合键。允许类只能用 Enter,拒绝只能用 Esc,修饰键随意;录制时单独按 Esc 取消。保存在插件配置里,重启后仍在。', shortcutDescription: '点键帽后按下新的组合键。允许类只能用 Enter,拒绝只能用 Esc,修饰键随意;录制时单独按 Esc 取消。保存在插件配置里,重启后仍在。',
shortcutAllow: '允许(单次)', shortcutAllow: '允许(单次)',

View File

@ -6,7 +6,19 @@ import {
processOnlyFromIntensity, processOnlyFromIntensity,
type FoldIntensity, type FoldIntensity,
} from './fold-intensity.js'; } from './fold-intensity.js';
import {
AI_BUBBLE_STYLE_DEFAULT,
AI_BUBBLE_WIDTH_DEFAULT,
READER_THEME_DEFAULT,
normalizeAiBubbleStyle,
normalizeAiBubbleWidth,
normalizeReaderTheme,
type AiBubbleStyle,
type AiBubbleWidth,
type ReaderTheme,
} from './appearance.js';
import type { DeliverableOpenMode } from './open-file.js'; import type { DeliverableOpenMode } from './open-file.js';
import { DEFAULT_RENDER_TURNS, normalizeRenderTurnLimit } from './turn-window.js';
export interface ReaderState { export interface ReaderState {
expanded: Record<string, boolean>; expanded: Record<string, boolean>;
@ -22,8 +34,16 @@ export interface ReaderState {
foldIntensity: FoldIntensity; foldIntensity: FoldIntensity;
/** Translucent frosted chrome. Default off so opaque main chrome stays. */ /** Translucent frosted chrome. Default off so opaque main chrome stays. */
frostedGlass: boolean; frostedGlass: boolean;
/** Appearance mode: follow host (default), forced light/dark, or frosted glass. */
readerTheme: ReaderTheme;
/** AI response bubble surface style (`soft` default). */
aiBubbleStyle: AiBubbleStyle;
/** Max width percentage shared by AI bubbles and process frames (`90` default). */
aiBubbleWidth: AiBubbleWidth;
/** Derived from foldIntensity === 2; kept for older #14 snapshots. */ /** Derived from foldIntensity === 2; kept for older #14 snapshots. */
processOnly: boolean; processOnly: boolean;
/** Max recent turns to render initially (`0` = render all loaded turns). */
renderTurnLimit: number;
} }
type ReaderActions = { type ReaderActions = {
setExpanded: (draft: ReaderState, key: string, value: boolean) => void; setExpanded: (draft: ReaderState, key: string, value: boolean) => void;
@ -33,6 +53,10 @@ type ReaderActions = {
setDeliverableOpenMode: (draft: ReaderState, value: DeliverableOpenMode) => void; setDeliverableOpenMode: (draft: ReaderState, value: DeliverableOpenMode) => void;
setFoldIntensity: (draft: ReaderState, value: FoldIntensity) => void; setFoldIntensity: (draft: ReaderState, value: FoldIntensity) => void;
setFrostedGlass: (draft: ReaderState, value: boolean) => void; setFrostedGlass: (draft: ReaderState, value: boolean) => void;
setReaderTheme: (draft: ReaderState, value: ReaderTheme) => void;
setAiBubbleStyle: (draft: ReaderState, value: AiBubbleStyle) => void;
setAiBubbleWidth: (draft: ReaderState, value: AiBubbleWidth) => void;
setRenderTurnLimit: (draft: ReaderState, value: number) => void;
}; };
function applyFoldIntensity(draft: ReaderState, value: FoldIntensity): void { function applyFoldIntensity(draft: ReaderState, value: FoldIntensity): void {
@ -50,7 +74,11 @@ export function createReaderStore(): EngineStoreHandle<ReaderState, ReaderAction
deliverableOpenMode: 'external', deliverableOpenMode: 'external',
foldIntensity: FOLD_INTENSITY_DEFAULT, foldIntensity: FOLD_INTENSITY_DEFAULT,
frostedGlass: false, frostedGlass: false,
readerTheme: READER_THEME_DEFAULT,
aiBubbleStyle: AI_BUBBLE_STYLE_DEFAULT,
aiBubbleWidth: AI_BUBBLE_WIDTH_DEFAULT,
processOnly: false, processOnly: false,
renderTurnLimit: DEFAULT_RENDER_TURNS,
}), }),
persist: 'dsh.reader.v1', persist: 'dsh.reader.v1',
actions: { actions: {
@ -64,7 +92,18 @@ export function createReaderStore(): EngineStoreHandle<ReaderState, ReaderAction
}, },
setDeliverableOpenMode: (draft, value: DeliverableOpenMode) => { draft.deliverableOpenMode = value; }, setDeliverableOpenMode: (draft, value: DeliverableOpenMode) => { draft.deliverableOpenMode = value; },
setFoldIntensity: (draft, value: FoldIntensity) => { applyFoldIntensity(draft, value); }, setFoldIntensity: (draft, value: FoldIntensity) => { applyFoldIntensity(draft, value); },
setFrostedGlass: (draft, value: boolean) => { draft.frostedGlass = value; }, setFrostedGlass: (draft, value: boolean) => {
draft.frostedGlass = value;
draft.readerTheme = value ? 'glass' : (draft.readerTheme === 'glass' ? 'host' : draft.readerTheme);
},
setReaderTheme: (draft, value: ReaderTheme) => {
const next = normalizeReaderTheme(value);
draft.readerTheme = next;
draft.frostedGlass = next === 'glass';
},
setAiBubbleStyle: (draft, value: AiBubbleStyle) => { draft.aiBubbleStyle = normalizeAiBubbleStyle(value); },
setAiBubbleWidth: (draft, value: AiBubbleWidth) => { draft.aiBubbleWidth = normalizeAiBubbleWidth(value); },
setRenderTurnLimit: (draft, value: number) => { draft.renderTurnLimit = normalizeRenderTurnLimit(value); },
}, },
}); });
} }

View File

@ -25,11 +25,13 @@ export interface TurnSlot<T extends { readonly key: string }> {
export function reconcileTurnSlots<T extends { readonly key: string }>( export function reconcileTurnSlots<T extends { readonly key: string }>(
current: readonly TurnSlot<T>[], current: readonly TurnSlot<T>[],
groups: readonly T[], groups: readonly T[],
shouldRetire?: (key: string) => boolean,
): readonly TurnSlot<T>[] { ): readonly TurnSlot<T>[] {
const incoming = new Map(groups.map(group => [group.key, group])); const incoming = new Map(groups.map(group => [group.key, group]));
const next: TurnSlot<T>[] = groups.map(group => ({ group, live: true })); const next: TurnSlot<T>[] = groups.map(group => ({ group, live: true }));
for (const slot of current) { for (const slot of current) {
if (incoming.has(slot.group.key)) continue; if (incoming.has(slot.group.key)) continue;
if (shouldRetire && !shouldRetire(slot.group.key)) continue;
insertDeparting(next, { group: slot.group, live: false }, precedingLiveKey(current, incoming, slot.group.key)); insertDeparting(next, { group: slot.group, live: false }, precedingLiveKey(current, incoming, slot.group.key));
} }
const same = const same =

236
src/client/turn-window.ts Normal file
View File

@ -0,0 +1,236 @@
import type { ReaderGroup } from './projection.js';
export const DEFAULT_RENDER_TURNS = 6;
export const MIN_RENDER_TURNS = 1;
export const MAX_RENDER_TURNS = 200;
/** Preset turn counts shown in Settings; `0` means render all loaded turns. */
export const RENDER_TURN_PRESETS = [4, 6, 10, 20, 0] as const;
export type TurnWindowState =
| { readonly kind: 'tail'; readonly count: number }
| { readonly kind: 'range'; readonly startKey: string; readonly endKey: string };
export interface TurnWindowSlice<T extends { readonly key: string; readonly turn: number | null }> {
readonly visible: readonly T[];
readonly start: number;
readonly end: number;
readonly hiddenOlder: number;
readonly hiddenNewer: number;
}
/**
* Normalize a persisted or user-entered turn render limit.
* `0`, `'0'`, `'all'`, and `null` mean unlimited (`0`). Invalid inputs fall back
* to `DEFAULT_RENDER_TURNS` (6).
*/
export function normalizeRenderTurnLimit(value: unknown): number {
if (value === 0 || value === null) return 0;
if (typeof value === 'string') {
const trimmed = value.trim().toLowerCase();
if (trimmed === '0' || trimmed === 'all') return 0;
if (/^\d+$/.test(trimmed)) {
const parsed = Number(trimmed);
if (parsed >= MIN_RENDER_TURNS) {
return Math.min(MAX_RENDER_TURNS, parsed);
}
}
return DEFAULT_RENDER_TURNS;
}
if (typeof value === 'number' && Number.isFinite(value)) {
const truncated = Math.trunc(value);
if (truncated >= MIN_RENDER_TURNS) {
return Math.min(MAX_RENDER_TURNS, truncated);
}
}
return DEFAULT_RENDER_TURNS;
}
/** Read and normalize `renderTurnLimit` from a prefs snapshot. */
export function renderTurnLimitOf(state: unknown): number {
if (state && typeof state === 'object' && 'renderTurnLimit' in state) {
return normalizeRenderTurnLimit((state as { renderTurnLimit?: unknown }).renderTurnLimit);
}
return DEFAULT_RENDER_TURNS;
}
/** Batch size used when expanding older/newer turns inside the window. */
export function batchSizeForLimit(limit: number): number {
const normalized = normalizeRenderTurnLimit(limit);
return normalized > 0 ? normalized : DEFAULT_RENDER_TURNS;
}
/** Build the default tail-anchored render window for a configured limit. */
export function initialTurnWindow(limit: number): TurnWindowState {
return { kind: 'tail', count: normalizeRenderTurnLimit(limit) };
}
/** Resolve the visible slice of `groups` for the current window state and limit. */
export function sliceTurnWindow<T extends { readonly key: string; readonly turn: number | null }>(
groups: readonly T[],
state: TurnWindowState,
limit: number,
): TurnWindowSlice<T> {
const normalizedLimit = normalizeRenderTurnLimit(limit);
if (groups.length === 0 || normalizedLimit === 0) {
return {
visible: groups,
start: 0,
end: groups.length,
hiddenOlder: 0,
hiddenNewer: 0,
};
}
if (state.kind === 'range') {
const startIdx = groups.findIndex(group => group.key === state.startKey);
const endIdx = groups.findIndex(group => group.key === state.endKey);
if (startIdx >= 0 && endIdx >= startIdx) {
const end = endIdx + 1;
return {
visible: startIdx === 0 && end === groups.length ? groups : groups.slice(startIdx, end),
start: startIdx,
end,
hiddenOlder: startIdx,
hiddenNewer: groups.length - end,
};
}
}
const count = state.kind === 'tail' && state.count > 0 ? state.count : normalizedLimit;
const start = Math.max(0, groups.length - count);
return {
visible: start === 0 ? groups : groups.slice(start),
start,
end: groups.length,
hiddenOlder: start,
hiddenNewer: 0,
};
}
/** Expand the window upward toward older turns by `step` (or one batch). */
export function expandOlderInWindow<T extends { readonly key: string; readonly turn: number | null }>(
groups: readonly T[],
state: TurnWindowState,
limit: number,
step?: number,
): TurnWindowState {
const slice = sliceTurnWindow(groups, state, limit);
if (slice.start <= 0) return state;
const delta = typeof step === 'number' && Number.isFinite(step) && step > 0
? Math.trunc(step)
: batchSizeForLimit(limit);
const nextStart = Math.max(0, slice.start - delta);
if (slice.end >= groups.length) {
return { kind: 'tail', count: groups.length - nextStart };
}
return {
kind: 'range',
startKey: groups[nextStart]!.key,
endKey: groups[slice.end - 1]!.key,
};
}
/** Expand the window downward toward newer turns by `step` (or one batch). */
export function expandNewerInWindow<T extends { readonly key: string; readonly turn: number | null }>(
groups: readonly T[],
state: TurnWindowState,
limit: number,
step?: number,
): TurnWindowState {
const slice = sliceTurnWindow(groups, state, limit);
if (slice.end >= groups.length) return state;
const delta = typeof step === 'number' && Number.isFinite(step) && step > 0
? Math.trunc(step)
: batchSizeForLimit(limit);
const nextEnd = Math.min(groups.length, slice.end + delta);
if (nextEnd >= groups.length) {
return { kind: 'tail', count: groups.length - slice.start };
}
return {
kind: 'range',
startKey: groups[slice.start]!.key,
endKey: groups[nextEnd - 1]!.key,
};
}
/**
* Adjust the window so `targetTurn` becomes visible when jumping from the rail.
* Nearby jumps extend the tail directly; far jumps center a window around the target.
*/
export function jumpToTurnInWindow<T extends { readonly key: string; readonly turn: number | null }>(
groups: readonly T[],
state: TurnWindowState,
targetTurn: number,
limit: number,
): TurnWindowState {
const normalizedLimit = normalizeRenderTurnLimit(limit);
if (normalizedLimit === 0) return { kind: 'tail', count: 0 };
const slice = sliceTurnWindow(groups, state, normalizedLimit);
const targetIndex = groups.findIndex(group => group.turn === targetTurn);
if (targetIndex < 0) return state;
if (targetIndex >= slice.start && targetIndex < slice.end) return state;
const cap = batchSizeForLimit(normalizedLimit);
const distanceFromTail = groups.length - targetIndex;
const directExpandCeiling = Math.max(cap * 2, 12);
if (distanceFromTail <= cap) {
return { kind: 'tail', count: cap };
}
if (distanceFromTail <= directExpandCeiling) {
const baseCount = state.kind === 'tail' ? Math.max(state.count, cap) : cap;
return { kind: 'tail', count: Math.max(baseCount, distanceFromTail) };
}
const endIdx = Math.min(groups.length - 1, targetIndex + cap - 1);
if (endIdx >= groups.length - 1) {
return { kind: 'tail', count: groups.length - targetIndex };
}
return {
kind: 'range',
startKey: groups[targetIndex]!.key,
endKey: groups[endIdx]!.key,
};
}
/** Count logical turns in `[start, end)`, falling back to group count when turn is null. */
export function countTurnsInSlice<T extends { readonly turn: number | null }>(
groups: readonly T[],
start: number,
end: number,
): number {
const clampedStart = Math.max(0, start);
const clampedEnd = Math.min(groups.length, end);
if (clampedEnd <= clampedStart) return 0;
let turns = 0;
for (let index = clampedStart; index < clampedEnd; index++) {
if (groups[index]!.turn !== null) turns++;
}
return turns > 0 ? turns : clampedEnd - clampedStart;
}
/**
* Keep previous `ReaderGroup` instances for unchanged turns so streaming tail
* updates do not break `memo(TurnGroup)` on settled historical turns.
*/
export function stabilizeGroups(
previous: readonly ReaderGroup[],
next: readonly ReaderGroup[],
): readonly ReaderGroup[] {
if (previous.length === 0) return next;
const prevByKey = new Map<string, ReaderGroup>();
for (const group of previous) prevByKey.set(group.key, group);
let allIdentical = previous.length === next.length;
const result: ReaderGroup[] = new Array(next.length);
for (let index = 0; index < next.length; index++) {
const candidate = next[index]!;
const prev = prevByKey.get(candidate.key);
const unchanged = prev !== undefined
&& prev.turn === candidate.turn
&& prev.keys.length === candidate.keys.length
&& prev.keys.every((key, keyIndex) => key === candidate.keys[keyIndex]);
const stabilized = unchanged ? prev : candidate;
result[index] = stabilized;
if (allIdentical && stabilized !== previous[index]) {
allIdentical = false;
}
}
return allIdentical ? previous : result;
}

View File

@ -60,16 +60,24 @@ export interface ReaderInjected {
getSnapshot: () => { getSnapshot: () => {
deliverableOpenMode?: import('./open-file.js').DeliverableOpenMode; deliverableOpenMode?: import('./open-file.js').DeliverableOpenMode;
frostedGlass?: boolean; frostedGlass?: boolean;
readerTheme?: import('./appearance.js').ReaderTheme;
aiBubbleStyle?: import('./appearance.js').AiBubbleStyle;
aiBubbleWidth?: import('./appearance.js').AiBubbleWidth;
foldIntensity?: import('./fold-intensity.js').FoldIntensity; foldIntensity?: import('./fold-intensity.js').FoldIntensity;
autoFold?: boolean; autoFold?: boolean;
processOnly?: boolean; processOnly?: boolean;
renderTurnLimit?: number;
}; };
subscribe: (fn: () => void) => () => void; subscribe: (fn: () => void) => () => void;
actions?: { actions?: {
setFoldIntensity?: (value: import('./fold-intensity.js').FoldIntensity) => void; setFoldIntensity?: (value: import('./fold-intensity.js').FoldIntensity) => void;
setAutoFold?: (value: boolean) => void; setAutoFold?: (value: boolean) => void;
setFrostedGlass?: (value: boolean) => void; setFrostedGlass?: (value: boolean) => void;
setReaderTheme?: (value: import('./appearance.js').ReaderTheme) => void;
setAiBubbleStyle?: (value: import('./appearance.js').AiBubbleStyle) => void;
setAiBubbleWidth?: (value: import('./appearance.js').AiBubbleWidth) => void;
setDeliverableOpenMode?: (value: import('./open-file.js').DeliverableOpenMode) => void; setDeliverableOpenMode?: (value: import('./open-file.js').DeliverableOpenMode) => void;
setRenderTurnLimit?: (value: number) => void;
}; };
}; };
/** Reveal and highlight a workspace file in macOS Finder or Windows Explorer. */ /** Reveal and highlight a workspace file in macOS Finder or Windows Explorer. */

50
tests/appearance.test.ts Normal file
View File

@ -0,0 +1,50 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import {
AI_BUBBLE_STYLE_DEFAULT,
AI_BUBBLE_WIDTH_DEFAULT,
READER_THEME_DEFAULT,
aiBubbleStyleOf,
aiBubbleWidthOf,
normalizeAiBubbleStyle,
normalizeAiBubbleWidth,
normalizeReaderTheme,
readerThemeOf,
} from '../src/client/appearance.js';
test('reader theme defaults to host, migrates legacy frostedGlass, and normalizes inputs', () => {
assert.equal(READER_THEME_DEFAULT, 'host');
assert.equal(normalizeReaderTheme(undefined), 'host');
assert.equal(normalizeReaderTheme('unknown'), 'host');
assert.equal(normalizeReaderTheme('light'), 'light');
assert.equal(normalizeReaderTheme('dark'), 'dark');
assert.equal(normalizeReaderTheme('glass'), 'glass');
assert.equal(readerThemeOf(undefined), 'host');
assert.equal(readerThemeOf({}), 'host');
assert.equal(readerThemeOf({ frostedGlass: false }), 'host');
assert.equal(readerThemeOf({ frostedGlass: true }), 'glass');
assert.equal(readerThemeOf({ readerTheme: 'dark', frostedGlass: true }), 'dark');
assert.equal(readerThemeOf({ readerTheme: 'light' }), 'light');
});
test('ai bubble style and max width normalize with safe defaults', () => {
assert.equal(AI_BUBBLE_STYLE_DEFAULT, 'soft');
assert.equal(normalizeAiBubbleStyle(undefined), 'soft');
assert.equal(normalizeAiBubbleStyle('card'), 'card');
assert.equal(normalizeAiBubbleStyle('plain'), 'plain');
assert.equal(aiBubbleStyleOf({ aiBubbleStyle: 'card' }), 'card');
assert.equal(aiBubbleStyleOf({ aiBubbleStyle: 'bogus' }), 'soft');
assert.equal(AI_BUBBLE_WIDTH_DEFAULT, 90);
assert.equal(normalizeAiBubbleWidth(undefined), 90);
assert.equal(normalizeAiBubbleWidth(70), 70);
assert.equal(normalizeAiBubbleWidth(80), 80);
assert.equal(normalizeAiBubbleWidth(90), 90);
assert.equal(normalizeAiBubbleWidth(100), 100);
assert.equal(normalizeAiBubbleWidth('80%'), 80);
assert.equal(normalizeAiBubbleWidth('100'), 100);
assert.equal(normalizeAiBubbleWidth(75), 90);
assert.equal(aiBubbleWidthOf({ aiBubbleWidth: 70 }), 70);
assert.equal(aiBubbleWidthOf({}), 90);
});

View File

@ -17,6 +17,9 @@ const blocks = await readFile(new URL('../src/client/Blocks.tsx', import.meta.ur
const readerCss = await readFile(new URL('../src/client/Reader.module.css', import.meta.url), 'utf8'); const readerCss = await readFile(new URL('../src/client/Reader.module.css', import.meta.url), 'utf8');
const turnMetricsCss = await readFile(new URL('../src/client/TurnMetrics.module.css', import.meta.url), 'utf8'); const turnMetricsCss = await readFile(new URL('../src/client/TurnMetrics.module.css', import.meta.url), 'utf8');
const markdown = await readFile(new URL('../src/client/markdown/MarkdownText.tsx', import.meta.url), 'utf8'); const markdown = await readFile(new URL('../src/client/markdown/MarkdownText.tsx', import.meta.url), 'utf8');
const timelineRail = await readFile(new URL('../src/client/TimelineRail.tsx', import.meta.url), 'utf8');
const settingsSection = await readFile(new URL('../src/client/SettingsSection.tsx', import.meta.url), 'utf8');
const storeSource = await readFile(new URL('../src/client/store.ts', import.meta.url), 'utf8');
test('the reader occupies the built-in 对话 View at a shadowing priority', () => { test('the reader occupies the built-in 对话 View at a shadowing priority', () => {
assert.match(source, /name: 'conversation\.view'/u); assert.match(source, /name: 'conversation\.view'/u);
@ -118,3 +121,42 @@ test('answer actions and turn metric pills stay intact when the chat column narr
assert.match(turnMetricsCss, /\.timeButton \{[^}]*flex: none;[^}]*height: 28px;[^}]*white-space: nowrap;/u); assert.match(turnMetricsCss, /\.timeButton \{[^}]*flex: none;[^}]*height: 28px;[^}]*white-space: nowrap;/u);
assert.match(turnMetricsCss, /\.metricsPop \{[^}]*width: min\(260px,/u); assert.match(turnMetricsCss, /\.metricsPop \{[^}]*width: min\(260px,/u);
}); });
test('turn windowing (default 6), settings persistence, and closed-turn snapshot isolation are wired', () => {
assert.match(storeSource, /renderTurnLimit:\s*DEFAULT_RENDER_TURNS/u);
assert.match(storeSource, /setRenderTurnLimit/u);
assert.match(settingsSection, /data-better-display-render-turns=\{renderTurnLimit\}/u);
assert.match(settingsSection, /RENDER_TURN_PRESETS/u);
assert.match(reader, /sliceTurnWindow\(groups,\s*windowState,\s*renderTurnLimit\)/u);
assert.match(reader, /stabilizeGroups\(previousGroupsRef\.current,\s*next\)/u);
assert.match(reader, /shouldRetire=\{shouldRetire\}/u);
assert.match(reader, /data-reader-load-older/u);
assert.match(reader, /data-reader-newer-bar/u);
assert.match(reader, /prev\.turnStatus === 'closed'/u);
});
test('timeline rail renders WorkBuddy-style expandable popover without scrollIntoView', () => {
assert.match(timelineRail, /data-reader-timeline-popover/u);
assert.match(timelineRail, /data-turn-row=\{item\.turn\}/u);
assert.doesNotMatch(timelineRail, /scrollIntoView/u);
});
test('theme, bubble style, and bubble width preferences are wired into Settings and Reader', () => {
assert.match(storeSource, /readerTheme:\s*READER_THEME_DEFAULT/u);
assert.match(storeSource, /aiBubbleStyle:\s*AI_BUBBLE_STYLE_DEFAULT/u);
assert.match(storeSource, /aiBubbleWidth:\s*AI_BUBBLE_WIDTH_DEFAULT/u);
assert.match(storeSource, /setReaderTheme/u);
assert.match(storeSource, /setAiBubbleStyle/u);
assert.match(storeSource, /setAiBubbleWidth/u);
assert.match(settingsSection, /data-better-display-theme=\{readerTheme\}/u);
assert.match(settingsSection, /data-better-display-bubble-style=\{aiBubbleStyle\}/u);
assert.match(settingsSection, /data-better-display-bubble-width=\{aiBubbleWidth\}/u);
assert.match(reader, /data-reader-theme=\{/u);
assert.match(reader, /data-reader-bubble-style=\{aiBubbleStyle\}/u);
assert.match(reader, /data-reader-bubble-width=\{aiBubbleWidth\}/u);
assert.match(readerCss, /\.root\[data-reader-theme="light"\]/u);
assert.match(readerCss, /\.root\[data-reader-theme="dark"\]/u);
assert.match(readerCss, /\.root\[data-reader-bubble-style="card"\] \.answerBubble/u);
assert.match(readerCss, /\.root\[data-reader-bubble-style="plain"\] \.answerBubble/u);
assert.match(readerCss, /\.root\[data-reader-bubble-width="100"\]/u);
});

199
tests/turn-window.test.ts Normal file
View File

@ -0,0 +1,199 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import {
DEFAULT_RENDER_TURNS,
MAX_RENDER_TURNS,
batchSizeForLimit,
countTurnsInSlice,
expandNewerInWindow,
expandOlderInWindow,
initialTurnWindow,
jumpToTurnInWindow,
normalizeRenderTurnLimit,
renderTurnLimitOf,
sliceTurnWindow,
stabilizeGroups,
} from '../src/client/turn-window.js';
import type { ReaderGroup } from '../src/client/projection.js';
import { reconcileTurnSlots } from '../src/client/turn-slots.js';
function makeGroups(count: number): ReaderGroup[] {
return Array.from({ length: count }, (_, index) => ({
key: `turn:${index}`,
turn: index,
keys: [`user-${index}`, `assistant-${index}`],
}));
}
test('normalizeRenderTurnLimit defaults to 6, supports unlimited 0, and clamps bounds', () => {
assert.equal(DEFAULT_RENDER_TURNS, 6);
assert.equal(normalizeRenderTurnLimit(undefined), 6);
assert.equal(normalizeRenderTurnLimit(-3), 6);
assert.equal(normalizeRenderTurnLimit(Number.NaN), 6);
assert.equal(normalizeRenderTurnLimit('invalid'), 6);
assert.equal(normalizeRenderTurnLimit(0.5), 6);
assert.equal(normalizeRenderTurnLimit(0), 0);
assert.equal(normalizeRenderTurnLimit('0'), 0);
assert.equal(normalizeRenderTurnLimit(' all '), 0);
assert.equal(normalizeRenderTurnLimit(null), 0);
assert.equal(normalizeRenderTurnLimit(4), 4);
assert.equal(normalizeRenderTurnLimit(' 12 '), 12);
assert.equal(normalizeRenderTurnLimit(999), MAX_RENDER_TURNS);
assert.equal(renderTurnLimitOf(undefined), 6);
assert.equal(renderTurnLimitOf({ renderTurnLimit: 10 }), 10);
assert.equal(renderTurnLimitOf({ renderTurnLimit: 0 }), 0);
assert.equal(batchSizeForLimit(10), 10);
assert.equal(batchSizeForLimit(0), 6);
});
test('sliceTurnWindow keeps only the latest 6 turns by default and supports unlimited mode', () => {
const groups = makeGroups(20);
const initial = initialTurnWindow(6);
const sliced = sliceTurnWindow(groups, initial, 6);
assert.equal(sliced.visible.length, 6);
assert.deepEqual(sliced.visible.map(g => g.turn), [14, 15, 16, 17, 18, 19]);
assert.equal(sliced.start, 14);
assert.equal(sliced.end, 20);
assert.equal(sliced.hiddenOlder, 14);
assert.equal(sliced.hiddenNewer, 0);
const shortGroups = makeGroups(4);
const shortSlice = sliceTurnWindow(shortGroups, initial, 6);
assert.equal(shortSlice.visible, shortGroups);
assert.equal(shortSlice.hiddenOlder, 0);
const unlimited = sliceTurnWindow(groups, initialTurnWindow(0), 0);
assert.equal(unlimited.visible, groups);
assert.equal(unlimited.hiddenOlder, 0);
assert.equal(unlimited.hiddenNewer, 0);
});
test('expandOlderInWindow and expandNewerInWindow step smoothly and merge back into tail', () => {
const groups = makeGroups(20);
let state = initialTurnWindow(6);
// Expand older from tail (14..19 -> 8..19)
state = expandOlderInWindow(groups, state, 6);
let slice = sliceTurnWindow(groups, state, 6);
assert.deepEqual(slice.visible.map(g => g.turn), [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
assert.equal(slice.hiddenOlder, 8);
assert.equal(slice.hiddenNewer, 0);
// Jump far into middle (turns 6..11), then expand older & newer within range
state = jumpToTurnInWindow(groups, initialTurnWindow(6), 6, 6);
assert.equal(state.kind, 'range');
slice = sliceTurnWindow(groups, state, 6);
assert.deepEqual(slice.visible.map(g => g.turn), [6, 7, 8, 9, 10, 11]);
assert.equal(slice.hiddenOlder, 6);
assert.equal(slice.hiddenNewer, 8);
state = expandOlderInWindow(groups, state, 6);
slice = sliceTurnWindow(groups, state, 6);
assert.deepEqual(slice.visible.map(g => g.turn), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
assert.equal(slice.hiddenOlder, 0);
assert.equal(slice.hiddenNewer, 8);
// Expanding newer once -> 0..17, twice -> 0..19 merged back to tail
state = expandNewerInWindow(groups, state, 6);
assert.equal(state.kind, 'range');
state = expandNewerInWindow(groups, state, 6);
assert.equal(state.kind, 'tail');
slice = sliceTurnWindow(groups, state, 6);
assert.equal(slice.visible, groups);
assert.equal(slice.hiddenNewer, 0);
});
test('jumpToTurnInWindow opens nearby turns without splitting tail and isolates far turns', () => {
const groups = makeGroups(25);
const initial = initialTurnWindow(6); // shows 19..24
// Already visible -> no-op
assert.equal(jumpToTurnInWindow(groups, initial, 20, 6), initial);
// Nearby jump (distance 10 <= directExpandCeiling 12) -> stays in tail mode (15..24)
const near = jumpToTurnInWindow(groups, initial, 15, 6);
assert.equal(near.kind, 'tail');
const nearSlice = sliceTurnWindow(groups, near, 6);
assert.deepEqual(nearSlice.visible.map(g => g.turn), [15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
assert.equal(nearSlice.hiddenNewer, 0);
// Far jump -> range centered forward from target (2..7)
const far = jumpToTurnInWindow(groups, initial, 2, 6);
assert.equal(far.kind, 'range');
const farSlice = sliceTurnWindow(groups, far, 6);
assert.deepEqual(farSlice.visible.map(g => g.turn), [2, 3, 4, 5, 6, 7]);
assert.equal(farSlice.hiddenOlder, 2);
assert.equal(farSlice.hiddenNewer, 17);
// Jumping to tail turn resets cleanly to 6-turn tail (19..24)
const backToTail = jumpToTurnInWindow(groups, far, 23, 6);
assert.deepEqual(backToTail, { kind: 'tail', count: 6 });
// Stale rewound range key falls back safely to tail
const trimmedGroups = makeGroups(8);
const rewoundSlice = sliceTurnWindow(
trimmedGroups,
{ kind: 'range', startKey: 'turn:5', endKey: 'turn:10' },
6,
);
assert.deepEqual(rewoundSlice.visible.map(g => g.turn), [2, 3, 4, 5, 6, 7]);
});
test('countTurnsInSlice counts logical turns properly', () => {
const mixed: ReaderGroup[] = [
{ key: 'turn:0', turn: 0, keys: ['u0', 'a0'] },
{ key: 'node:misc', turn: null, keys: ['c0'] },
{ key: 'turn:1', turn: 1, keys: ['u1', 'a1'] },
];
assert.equal(countTurnsInSlice(mixed, 0, 3), 2);
assert.equal(countTurnsInSlice(mixed, 1, 2), 1);
assert.equal(countTurnsInSlice(mixed, 2, 2), 0);
});
test('stabilizeGroups keeps unchanged group references across tail updates', () => {
const prev: ReaderGroup[] = [
{ key: 'turn:0', turn: 0, keys: ['u0', 'a0'] },
{ key: 'turn:1', turn: 1, keys: ['u1', 'a1'] },
];
const identicalCopy: ReaderGroup[] = [
{ key: 'turn:0', turn: 0, keys: ['u0', 'a0'] },
{ key: 'turn:1', turn: 1, keys: ['u1', 'a1'] },
];
assert.equal(stabilizeGroups(prev, identicalCopy), prev);
const appended: ReaderGroup[] = [
{ key: 'turn:0', turn: 0, keys: ['u0', 'a0'] },
{ key: 'turn:1', turn: 1, keys: ['u1', 'a1', 'a1b'] },
{ key: 'turn:2', turn: 2, keys: ['u2'] },
];
const next = stabilizeGroups(prev, appended);
assert.equal(next[0], prev[0]);
assert.notEqual(next[1], prev[1]);
assert.equal(next[2], appended[2]);
});
test('reconcileTurnSlots skips retire animation when clipped by render window', () => {
const t0 = { key: 'turn:0' };
const t1 = { key: 'turn:1' };
const t2 = { key: 'turn:2' };
const initial = reconcileTurnSlots([], [t0, t1]);
// Simulate t0 clipped out of the render window while still in session history (`shouldRetire('turn:0') === false`),
// and later simulate t1 genuinely rewound (`shouldRetire('turn:1') === true`).
const clipped = reconcileTurnSlots(initial, [t1, t2], key => key !== 'turn:0');
assert.deepEqual(clipped.map(s => [s.group.key, s.live]), [
['turn:1', true],
['turn:2', true],
]);
const rewound = reconcileTurnSlots(clipped, [t2], key => key === 'turn:1');
assert.deepEqual(rewound.map(s => [s.group.key, s.live]), [
['turn:1', false],
['turn:2', true],
]);
});