Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(thread): sync id allocation + ChatMiniMap polish (#14000)

Arvin Xu569dcc876517
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 134fa7401a2..72f28b0580e 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -224,6 +224,7 @@
"messages.tokenDetails.speed.ttft.tooltip": "Time To First Token (TTFT). This refers to the time interval from when you send a message to when the client receives the first Token.",
"messages.tokenDetails.title": "Generation Details",
"messages.tokenDetails.total": "Total Consumption",
+ "minimap.emptyPreview": "(No text content)",
"minimap.jumpToMessage": "Jump to message {{index}}",
"minimap.nextMessage": "Next message",
"minimap.previousMessage": "Previous message",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 14ef0a1cfc3..944275da5fa 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -224,6 +224,7 @@
"messages.tokenDetails.speed.ttft.tooltip": "Time To First Token(TTFT):从发送消息到接收到首个 Token 的时间。",
"messages.tokenDetails.title": "生成明细",
"messages.tokenDetails.total": "总消耗",
+ "minimap.emptyPreview": "(无文本内容)",
"minimap.jumpToMessage": "跳转到第 {{index}} 条消息",
"minimap.nextMessage": "下一条消息",
"minimap.previousMessage": "上一条消息",
diff --git a/packages/builtin-tool-claude-code/src/client/Inspector/TodoWrite.tsx b/packages/builtin-tool-claude-code/src/client/Inspector/TodoWrite.tsx
index 67e240806b1..a229bbd0402 100644
--- a/packages/builtin-tool-claude-code/src/client/Inspector/TodoWrite.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Inspector/TodoWrite.tsx
@@ -1,10 +1,6 @@
'use client';
-import {
- highlightTextStyles,
- inspectorTextStyles,
- shinyTextStyles,
-} from '@lobechat/shared-tool-ui/styles';
+import { inspectorTextStyles, shinyTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinInspectorProps } from '@lobechat/types';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { memo, useMemo } from 'react';
@@ -31,6 +27,22 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
stroke-dashoffset 240ms ease,
stroke 240ms ease;
`,
+ chip: css`
+ overflow: hidden;
+ flex-shrink: 1;
+
+ min-width: 0;
+ margin-inline-start: 4px;
+ padding-block: 1px;
+ padding-inline: 8px;
+ border-radius: 999px;
+
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ background: ${cssVar.colorFillSecondary};
+ `,
}));
interface TodoStats {
@@ -120,8 +132,8 @@ export const TodoWriteInspector = memo<BuiltinInspectorProps<TodoWriteArgs>>(
<span>{label}</span>
{detail && (
<>
- <span>: </span>
- <span className={highlightTextStyles.primary}>{detail}</span>
+ <span>:</span>
+ <span className={styles.chip}>{detail}</span>
</>
)}
</div>
diff --git a/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx
index e4370c312b0..0926cc98da6 100644
--- a/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx
+++ b/packages/builtin-tool-claude-code/src/client/Render/TodoWrite/index.tsx
@@ -1,6 +1,5 @@
'use client';
-import { highlightTextStyles } from '@lobechat/shared-tool-ui/styles';
import type { BuiltinRenderProps } from '@lobechat/types';
import { Block, Checkbox, Icon } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
@@ -35,6 +34,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
+ headerDetail: css`
+ overflow: hidden;
+ min-width: 0;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ `,
headerCount: css`
flex-shrink: 0;
@@ -146,7 +151,7 @@ const TodoHeader = memo<TodoHeaderProps>(({ completed, total, inProgress }) => {
{detail && (
<>
<span>: </span>
- <span className={highlightTextStyles.primary}>{detail}</span>
+ <span className={styles.headerDetail}>{detail}</span>
</>
)}
</div>
diff --git a/packages/builtin-tool-claude-code/src/types.ts b/packages/builtin-tool-claude-code/src/types.ts
index a84b6afddbc..9b8993c9912 100644
--- a/packages/builtin-tool-claude-code/src/types.ts
+++ b/packages/builtin-tool-claude-code/src/types.ts
@@ -17,6 +17,16 @@ export enum ClaudeCodeApiName {
Grep = 'Grep',
Read = 'Read',
Skill = 'Skill',
+ /**
+ * Spawns a subagent. CC emits this as a regular `tool_use`; downstream
+ * events for the subagent's internal turns are tagged with
+ * `parent_tool_use_id` pointing back at this tool_use's id, and the
+ * subagent's final answer arrives as the `tool_result` for this id.
+ * The executor turns this into a Thread (linked via
+ * `metadata.sourceToolCallId = tool_use.id`) instead of a separate
+ * `role: 'task'` message.
+ */
+ Task = 'Task',
TodoWrite = 'TodoWrite',
ToolSearch = 'ToolSearch',
Write = 'Write',
@@ -60,3 +70,15 @@ export interface ToolSearchArgs {
max_results?: number;
query?: string;
}
+
+/**
+ * Arguments for CC's built-in `Task` tool. The model fills these in when it
+ * decides to delegate work to a subagent: the description shows up in the
+ * folded header, the prompt becomes the subagent's initial user message, and
+ * `subagent_type` selects which subagent template handles it.
+ */
+export interface TaskArgs {
+ description?: string;
+ prompt?: string;
+ subagent_type?: string;
+}
diff --git a/packages/database/src/models/__tests__/thread.test.ts b/packages/database/src/models/__tests__/thread.test.ts
index 8c48492f805..8f6834311dd 100644
--- a/packages/database/src/models/__tests__/thread.test.ts
+++ b/packages/database/src/models/__tests__/thread.test.ts
@@ -56,6 +56,37 @@ describe('ThreadModel', () => {
expect(result.title).toBe('Test Thread');
expect(result.type).toBe(ThreadType.Continuation);
});
+
+ it('should honor caller-provided id', async () => {
+ const customId = 'thd_custom_abc';
+ const result = await threadModel.create({
+ id: customId,
+ topicId,
+ type: ThreadType.Standalone,
+ });
+
+ expect(result.id).toBe(customId);
+ });
+
+ it('should return undefined when caller-provided id collides (onConflictDoNothing)', async () => {
+ const customId = 'thd_collide_xyz';
+ const first = await threadModel.create({
+ id: customId,
+ topicId,
+ type: ThreadType.Standalone,
+ });
+ expect(first.id).toBe(customId);
+
+ // The router layer translates this undefined into TRPCError(CONFLICT)
+ // so callers using client-provided ids see an explicit error instead
+ // of writing follow-up rows against a missing thread.
+ const second = await threadModel.create({
+ id: customId,
+ topicId,
+ type: ThreadType.Standalone,
+ });
+ expect(second).toBeUndefined();
+ });
});
describe('query', () => {
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 2f8d928db71..843f2cf05d3 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -41,6 +41,47 @@ export interface ChatFileItem {
url: string;
}
+/**
+ * A subagent execution embedded inline in the parent assistant block.
+ *
+ * Used for Claude Code's `Task` tool (and equivalent subagent-spawning tools):
+ * the LLM emits a Task tool_use, the executor creates a Thread to run the
+ * subagent, and the rendered block shows a folded header + (on expand) the
+ * Thread's child messages — instead of producing a separate `role: 'task'`
+ * ChatItem bubble.
+ *
+ * Derived view, not persisted: the MessageTransformer reconstructs
+ * `block.tasks[]` by joining Threads (`threads.sourceMessageId = msg.id`,
+ * matched by `metadata.sourceToolCallId === tool_use.id`) onto the parent
+ * message's tool_use entries.
+ */
+export interface TaskBlock {
+ /** Execution duration in milliseconds (`Thread.metadata.duration`) */
+ duration?: number;
+ /** Error details when subagent failed (`Thread.metadata.error`) */
+ error?: any;
+ /** Equals the parent tool_use id that spawned this subagent */
+ id: string;
+ /** Thread execution status */
+ status?: ThreadStatus;
+ /** Subagent type, e.g. CC's `subagent_type` input (Explore, Plan, ...) */
+ subagentType?: string;
+ threadId: string;
+ /**
+ * Short summary rendered in the folded header — sourced from `Thread.title`
+ * (for CC Task spawns, the executor persists the tool_use's `description`
+ * input there at create time, so there is no separate `description` field
+ * on this block).
+ */
+ title?: string;
+ /** Total cost in dollars */
+ totalCost?: number;
+ /** Total tokens consumed */
+ totalTokens?: number;
+ /** Total tool calls made by the subagent */
+ totalToolCalls?: number;
+}
+
export interface AssistantContentBlock {
content: string;
error?: ChatMessageError | null;
@@ -50,6 +91,13 @@ export interface AssistantContentBlock {
metadata?: Record<string, any>;
performance?: ModelPerformance;
reasoning?: ModelReasoning;
+ /**
+ * Subagent executions embedded inline. Disambiguated from regular tools
+ * because each task carries a Thread reference and renders as a folded
+ * panel (showing the Thread's child messages on expand) instead of a
+ * standalone tool result.
+ */
+ tasks?: TaskBlock[];
tools?: ChatToolPayloadWithResult[];
usage?: ModelUsage;
}
diff --git a/packages/types/src/topic/thread.ts b/packages/types/src/topic/thread.ts
index ba933cb3f3a..9a687126994 100644
--- a/packages/types/src/topic/thread.ts
+++ b/packages/types/src/topic/thread.ts
@@ -40,8 +40,18 @@ export interface ThreadMetadata {
error?: any;
/** Operation ID for tracking */
operationId?: string;
+ /**
+ * The specific tool_use id within `sourceMessageId` that spawned this thread.
+ * Used to position the thread inline as a `task` block within the parent
+ * message's content stream — e.g. CC's `Task` tool_use spawning a subagent.
+ * Multiple threads can share the same `sourceMessageId` (parallel subagents),
+ * disambiguated by this field.
+ */
+ sourceToolCallId?: string;
/** Task start time, used to calculate duration */
startedAt?: string;
+ /** Subagent type identifier, e.g. CC's `subagent_type` input (Explore, Plan, ...) */
+ subagentType?: string;
/** Total cost in dollars */
totalCost?: number;
/** Total messages created during execution */
@@ -77,6 +87,14 @@ export interface CreateThreadParams {
agentId?: string;
/** Group ID for group chat context */
groupId?: string;
+ /**
+ * Optional client-provided id. Lets the caller derive the thread id
+ * synchronously (e.g. when wiring CC subagent threads from the stream
+ * adapter, where the id needs to be known before the create call returns
+ * so subagent inner messages can be persisted with the right `threadId`).
+ * Falls back to the schema's `idGenerator` when omitted.
+ */
+ id?: string;
/** Initial metadata for the thread */
metadata?: ThreadMetadata;
parentThreadId?: string;
@@ -94,7 +112,9 @@ export const threadMetadataSchema = z.object({
duration: z.number().optional(),
error: z.any().optional(),
operationId: z.string().optional(),
+ sourceToolCallId: z.string().optional(),
startedAt: z.string().optional(),
+ subagentType: z.string().optional(),
totalCost: z.number().optional(),
totalMessages: z.number().optional(),
totalTokens: z.number().optional(),
@@ -104,6 +124,7 @@ export const threadMetadataSchema = z.object({
export const createThreadSchema = z.object({
agentId: z.string().optional(),
groupId: z.string().optional(),
+ id: z.string().optional(),
metadata: threadMetadataSchema.optional(),
parentThreadId: z.string().optional(),
sourceMessageId: z.string().optional(),
diff --git a/src/features/ChatMiniMap/MinimapIndicator.tsx b/src/features/ChatMiniMap/MinimapIndicator.tsx
index e5ab7d17f32..30cbdd6a540 100644
--- a/src/features/ChatMiniMap/MinimapIndicator.tsx
+++ b/src/features/ChatMiniMap/MinimapIndicator.tsx
@@ -1,4 +1,3 @@
-import { Block, Popover, Text } from '@lobehub/ui';
import { cx } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -7,56 +6,23 @@ import { indicatorStyles } from './styles';
import { type MinimapIndicatorProps } from './types';
export const MinimapIndicator = memo<MinimapIndicatorProps>(
- ({ id, width, preview, role, virtuosoIndex, position, activePosition, onJump }) => {
+ ({ id, width, virtuosoIndex, position, activePosition, onJump }) => {
const { t } = useTranslation('chat');
const styles = indicatorStyles;
const isActive = activePosition === position;
- const senderLabel = role === 'user' ? t('minimap.senderUser') : t('minimap.senderAssistant');
-
- const popoverContent = preview ? (
- <>
- <Text fontSize={12} style={{ marginBottom: 4 }} type={'secondary'} weight={500}>
- {senderLabel}
- </Text>
- <Text as={'p'} fontSize={12}>
- {preview}
- </Text>
- </>
- ) : undefined;
return (
- <Popover
- content={popoverContent}
- key={id}
- mouseEnterDelay={0.1}
- placement={'left'}
- styles={{
- content: {
- width: 320,
- },
- }}
+ <div
+ aria-current={isActive ? 'true' : undefined}
+ aria-label={t('minimap.jumpToMessage', { index: position + 1 })}
+ className={styles.indicator}
+ id={id}
+ style={{ width }}
+ onClick={() => onJump(virtuosoIndex)}
>
- <Block
- clickable
- align={'flex-end'}
- style={{ borderRadius: 4 }}
- variant={'borderless'}
- width={'100%'}
- >
- <div
- aria-current={isActive ? 'true' : undefined}
- aria-label={t('minimap.jumpToMessage', { index: position + 1 })}
- className={styles.indicator}
- style={{ width }}
- onClick={() => onJump(virtuosoIndex)}
- >
- <div
- className={cx(styles.indicatorContent, isActive && styles.indicatorContentActive)}
- />
- </div>
- </Block>
- </Popover>
+ <div className={cx(styles.indicatorContent, isActive && styles.indicatorContentActive)} />
+ </div>
);
},
);
diff --git a/src/features/ChatMiniMap/MinimapPreview.tsx b/src/features/ChatMiniMap/MinimapPreview.tsx
new file mode 100644
index 00000000000..7675fceef4e
--- /dev/null
+++ b/src/features/ChatMiniMap/MinimapPreview.tsx
@@ -0,0 +1,47 @@
+import { Flexbox } from '@lobehub/ui';
+import { cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { previewStyles } from './styles';
+import { type MinimapIndicator } from './types';
+
+interface MinimapPreviewProps {
+ activePosition: number | null;
+ indicators: MinimapIndicator[];
+ onJump: (virtuosoIndex: number) => void;
+}
+
+export const MinimapPreview = memo<MinimapPreviewProps>(
+ ({ indicators, activePosition, onJump }) => {
+ const { t } = useTranslation('chat');
+ const styles = previewStyles;
+
+ return (
+ <Flexbox className={styles.list} gap={2}>
+ {indicators.map(({ id, preview, virtuosoIndex, width }, position) => {
+ const isActive = activePosition === position;
+ const label = preview || t('minimap.emptyPreview');
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-current={isActive ? 'true' : undefined}
+ className={cx(styles.item, isActive && styles.itemActive)}
+ gap={10}
+ justify={'flex-end'}
+ key={id}
+ onClick={() => onJump(virtuosoIndex)}
+ >
+ <span className={cx(styles.label, isActive && styles.labelActive)}>{label}</span>
+ <div className={cx(styles.dash, isActive && styles.dashActive)} style={{ width }} />
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ );
+ },
+);
+
+MinimapPreview.displayName = 'MinimapPreview';
diff --git a/src/features/ChatMiniMap/index.tsx b/src/features/ChatMiniMap/index.tsx
index 25a853c6f65..cd1428ee673 100644
--- a/src/features/ChatMiniMap/index.tsx
+++ b/src/features/ChatMiniMap/index.tsx
@@ -1,64 +1,74 @@
'use client';
-import { ActionIcon, Flexbox, PopoverGroup } from '@lobehub/ui';
+import { Flexbox } from '@lobehub/ui';
import { cx } from 'antd-style';
-import { ChevronDown, ChevronUp } from 'lucide-react';
-import { memo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
+import { memo, useRef, useState } from 'react';
import { MinimapIndicator } from './MinimapIndicator';
+import { MinimapPreview } from './MinimapPreview';
import { minimapStyles } from './styles';
import { useMinimapData } from './useMinimapData';
import { MIN_MESSAGES_THRESHOLD } from './utils';
+const CLOSE_DELAY_MS = 120;
+
const ChatMinimap = memo(() => {
- const { t } = useTranslation('chat');
const styles = minimapStyles;
- const [isHovered, setIsHovered] = useState(false);
+ const [hovered, setHovered] = useState(false);
+ const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const { indicators, activeIndicatorPosition, handleJump, handleStep } = useMinimapData();
+ const { indicators, activeIndicatorPosition, handleJump } = useMinimapData();
if (indicators.length <= MIN_MESSAGES_THRESHOLD) return null;
+ const handleEnter = () => {
+ if (closeTimerRef.current) {
+ clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = null;
+ }
+ setHovered(true);
+ };
+
+ const handleLeave = () => {
+ if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = setTimeout(() => {
+ setHovered(false);
+ closeTimerRef.current = null;
+ }, CLOSE_DELAY_MS);
+ };
+
+ const handleJumpAndClose = (virtuosoIndex: number) => {
+ handleJump(virtuosoIndex);
+ if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
+ setHovered(false);
+ };
+
return (
- <Flexbox align={'center'} className={styles.container} justify={'center'}>
- <Flexbox
- className={styles.rail}
- role={'group'}
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- >
- <ActionIcon
- aria-label={t('minimap.previousMessage')}
- className={cx(styles.arrow, isHovered && styles.arrowVisible)}
- icon={ChevronUp}
- size={14}
- onClick={() => handleStep('prev')}
- />
- <Flexbox className={styles.railContent}>
- <PopoverGroup contentLayoutAnimation>
- {indicators.map(({ id, width, preview, role, virtuosoIndex }, position) => (
- <MinimapIndicator
- activePosition={activeIndicatorPosition}
- id={id}
- key={id}
- position={position}
- preview={preview}
- role={role}
- virtuosoIndex={virtuosoIndex}
- width={width}
- onJump={handleJump}
- />
- ))}
- </PopoverGroup>
+ <Flexbox className={styles.container}>
+ <Flexbox className={styles.hoverArea} onMouseEnter={handleEnter} onMouseLeave={handleLeave}>
+ <Flexbox className={cx(styles.rail, hovered && styles.railFaded)} role={'group'}>
+ {indicators.map(({ id, width, virtuosoIndex }, position) => (
+ <MinimapIndicator
+ activePosition={activeIndicatorPosition}
+ id={id}
+ key={id}
+ position={position}
+ virtuosoIndex={virtuosoIndex}
+ width={width}
+ onJump={handleJump}
+ />
+ ))}
</Flexbox>
- <ActionIcon
- aria-label={t('minimap.nextMessage')}
- className={cx(styles.arrow, isHovered && styles.arrowVisible)}
- icon={ChevronDown}
- size={14}
- onClick={() => handleStep('next')}
- />
+ <div
+ aria-hidden={!hovered}
+ className={cx(styles.previewPanel, hovered && styles.previewPanelVisible)}
+ >
+ <MinimapPreview
+ activePosition={activeIndicatorPosition}
+ indicators={indicators}
+ onJump={handleJumpAndClose}
+ />
+ </div>
</Flexbox>
</Flexbox>
);
diff --git a/src/features/ChatMiniMap/styles.ts b/src/features/ChatMiniMap/styles.ts
index f3608757fad..4801362a6cf 100644
--- a/src/features/ChatMiniMap/styles.ts
+++ b/src/features/ChatMiniMap/styles.ts
@@ -1,23 +1,6 @@
import { createStaticStyles } from 'antd-style';
export const minimapStyles = createStaticStyles(({ css, cssVar }) => ({
- arrow: css`
- opacity: 0;
- transition: opacity ${cssVar.motionDurationMid} ease;
-
- &:hover {
- color: ${cssVar.colorText};
- background: ${cssVar.colorFill};
- }
-
- &:focus-visible {
- outline: none;
- box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBorder};
- }
- `,
- arrowVisible: css`
- opacity: 1;
- `,
container: css`
pointer-events: none;
@@ -26,27 +9,54 @@ export const minimapStyles = createStaticStyles(({ css, cssVar }) => ({
inset-block: 16px 120px;
inset-inline-end: 8px;
- width: 32px;
+ display: flex;
+ flex-direction: column;
+ align-items: end;
+ justify-content: center;
`,
- rail: css`
+ hoverArea: css`
pointer-events: auto;
+ position: relative;
+
display: flex;
flex-direction: column;
- gap: 0;
align-items: end;
- justify-content: space-between;
+ `,
+ previewPanel: css`
+ pointer-events: none;
- width: 100%;
- height: fit-content;
- margin-block: 0;
- margin-inline: auto;
+ position: absolute;
+ inset-block-start: 50%;
+ inset-inline-end: 0;
+ transform-origin: 100% 50%;
+ transform: translateY(-50%) scale(0.96);
- &:hover .arrow {
- opacity: 1;
- }
+ overflow: hidden;
+ display: flex;
+
+ min-width: 240px;
+ max-width: 360px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 8px;
+
+ opacity: 0;
+ background: ${cssVar.colorBgElevated};
+ box-shadow:
+ 0 6px 16px 0 rgb(0 0 0 / 8%),
+ 0 3px 6px -4px rgb(0 0 0 / 12%),
+ 0 9px 28px 8px rgb(0 0 0 / 5%);
+
+ transition:
+ opacity ${cssVar.motionDurationMid} ease,
+ transform ${cssVar.motionDurationMid} ease;
`,
- railContent: css`
+ previewPanelVisible: css`
+ pointer-events: auto;
+ transform: translateY(-50%) scale(1);
+ opacity: 1;
+ `,
+ rail: css`
scrollbar-width: none;
overflow-y: auto;
@@ -54,10 +64,11 @@ export const minimapStyles = createStaticStyles(({ css, cssVar }) => ({
flex-direction: column;
gap: 0;
align-items: end;
- justify-content: space-between;
max-height: 50vh;
+ transition: opacity ${cssVar.motionDurationMid} ease;
+
/* Hide scrollbar for IE, Edge and Firefox */
-ms-overflow-style: none;
@@ -66,29 +77,94 @@ export const minimapStyles = createStaticStyles(({ css, cssVar }) => ({
display: none;
}
`,
+ railFaded: css`
+ pointer-events: none;
+ opacity: 0;
+ `,
}));
export const indicatorStyles = createStaticStyles(({ css, cssVar }) => ({
indicator: css`
+ cursor: pointer;
+
flex-shrink: 0;
- min-width: 12px;
+ min-width: 5px;
height: 12px;
padding-block: 5px;
- padding-inline: 4px;
- `,
- indicatorActive: css`
- transform: scaleX(1.1);
- background: ${cssVar.colorPrimary};
- box-shadow: 0 0 0 1px ${cssVar.colorPrimaryHover};
`,
indicatorContent: css`
width: 100%;
height: 100%;
- border-radius: 3px;
+ border-radius: 2px;
background: ${cssVar.colorFillSecondary};
`,
indicatorContentActive: css`
background: ${cssVar.colorPrimary};
`,
}));
+
+export const previewStyles = createStaticStyles(({ css, cssVar }) => ({
+ dash: css`
+ flex-shrink: 0;
+ height: 2px;
+ border-radius: 2px;
+ background: ${cssVar.colorFillSecondary};
+ `,
+ dashActive: css`
+ background: ${cssVar.colorPrimary};
+ `,
+ item: css`
+ cursor: pointer;
+
+ padding-block: 6px;
+ padding-inline: 12px;
+ border-radius: 6px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ transition: background-color ${cssVar.motionDurationFast} ease;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ itemActive: css`
+ color: ${cssVar.colorPrimary};
+ `,
+ label: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 1;
+
+ font-size: 13px;
+ line-height: 1.4;
+ text-align: end;
+ text-overflow: ellipsis;
+ word-break: break-word;
+ `,
+ labelActive: css`
+ font-weight: 500;
+ color: ${cssVar.colorPrimary};
+ `,
+ list: css`
+ scrollbar-width: thin;
+
+ overflow-y: auto;
+
+ max-height: 60vh;
+ padding-block: 4px;
+ padding-inline: 4px;
+
+ &::-webkit-scrollbar {
+ width: 4px;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ border-radius: 2px;
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+}));
diff --git a/src/features/ChatMiniMap/types.ts b/src/features/ChatMiniMap/types.ts
index 0988cde6cc9..6d14353f684 100644
--- a/src/features/ChatMiniMap/types.ts
+++ b/src/features/ChatMiniMap/types.ts
@@ -1,7 +1,6 @@
export interface MinimapIndicator {
id: string;
preview: string;
- role: 'user' | 'assistant';
virtuosoIndex: number;
width: number;
}
@@ -11,8 +10,6 @@ export interface MinimapIndicatorProps {
id: string;
onJump: (virtuosoIndex: number) => void;
position: number;
- preview: string;
- role: 'user' | 'assistant';
virtuosoIndex: number;
width: number;
}
diff --git a/src/features/ChatMiniMap/useMinimapData.ts b/src/features/ChatMiniMap/useMinimapData.ts
index 52a3bbb4dba..873bb1d4b59 100644
--- a/src/features/ChatMiniMap/useMinimapData.ts
+++ b/src/features/ChatMiniMap/useMinimapData.ts
@@ -16,12 +16,11 @@ export const useMinimapData = () => {
const indicators = useMemo<MinimapIndicator[]>(() => {
return messages.reduce<MinimapIndicator[]>((acc, message, virtuosoIndex) => {
- if (message.role !== 'user' && message.role !== 'assistant') return acc;
+ if (message.role !== 'user') return acc;
acc.push({
id: message.id,
preview: getPreviewText(message.content),
- role: message.role,
virtuosoIndex,
width: getIndicatorWidth(message.content),
});
@@ -44,8 +43,18 @@ export const useMinimapData = () => {
log('> activeIndex', activeIndex);
log('> indicatorIndexMap', indicatorIndexMap);
- return indicatorIndexMap.get(activeIndex) ?? null;
- }, [activeIndex, indicatorIndexMap]);
+ const exact = indicatorIndexMap.get(activeIndex);
+ if (exact !== undefined) return exact;
+
+ // Viewport sits on a non-user message (typically an assistant reply).
+ // Highlight the most recent user message that started this turn.
+ let matched: number | null = null;
+ for (const [position, indicator] of indicators.entries()) {
+ if (indicator.virtuosoIndex <= activeIndex) matched = position;
+ else break;
+ }
+ return matched;
+ }, [activeIndex, indicatorIndexMap, indicators]);
const handleJump = useCallback(
(virtIndex: number) => {
@@ -54,59 +63,9 @@ export const useMinimapData = () => {
[scrollMethods],
);
- const handleStep = useCallback(
- (direction: 'prev' | 'next') => {
- if (!scrollMethods || indicators.length === 0) return;
-
- let targetPosition: number;
-
- if (activeIndicatorPosition !== null) {
- log('activeIndicatorPosition', activeIndicatorPosition);
- // We're on an indicator, move to prev/next
- const delta = direction === 'prev' ? -1 : 1;
- targetPosition = Math.min(
- Math.max(activeIndicatorPosition + delta, 0),
- Math.max(indicators.length - 1, 0),
- );
- } else if (activeIndex !== null) {
- // We're not on an indicator, find the nearest one in the direction
- if (direction === 'prev') {
- let matched = -1;
- for (let pos = indicators.length - 1; pos >= 0; pos -= 1) {
- if (indicators[pos].virtuosoIndex < activeIndex) {
- matched = pos;
- break;
- }
- }
- targetPosition = matched === -1 ? 0 : matched;
- } else {
- let matched = indicators.length - 1;
- for (const [pos, indicator] of indicators.entries()) {
- if (indicator.virtuosoIndex > activeIndex) {
- matched = pos;
- break;
- }
- }
- targetPosition = matched;
- }
- } else {
- // No active index, go to first/last
- targetPosition = direction === 'prev' ? 0 : indicators.length - 1;
- }
-
- const targetIndicator = indicators[targetPosition];
-
- if (!targetIndicator) return;
-
- scrollMethods.scrollToIndex(targetIndicator.virtuosoIndex, { align: 'start', smooth: true });
- },
- [activeIndex, activeIndicatorPosition, indicators, scrollMethods],
- );
-
return {
activeIndicatorPosition,
handleJump,
- handleStep,
indicators,
};
};
diff --git a/src/features/ChatMiniMap/utils.ts b/src/features/ChatMiniMap/utils.ts
index d7de5eedb88..39224bbc89d 100644
--- a/src/features/ChatMiniMap/utils.ts
+++ b/src/features/ChatMiniMap/utils.ts
@@ -1,14 +1,15 @@
import { markdownToTxt } from '@/utils/markdownToTxt';
-const MIN_WIDTH = 12;
-const MAX_WIDTH = 24;
-const MAX_CONTENT_LENGTH = 320;
+const MIN_WIDTH = 5;
+const MAX_WIDTH = 16;
+const MAX_LENGTH = 80;
export const getIndicatorWidth = (content: string | undefined): number => {
- if (!content) return MIN_WIDTH;
-
- const ratio = Math.min(content.length / MAX_CONTENT_LENGTH, 1);
+ const length = content?.length ?? 0;
+ // Smooth sqrt curve so very short messages render small and length grows
+ // naturally up to MAX_LENGTH — no piecewise jump.
+ const ratio = Math.min(Math.sqrt(length / MAX_LENGTH), 1);
return MIN_WIDTH + (MAX_WIDTH - MIN_WIDTH) * ratio;
};
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 1f747f388f9..79e3f2303f4 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -241,6 +241,7 @@ export default {
'Time To First Token (TTFT). This refers to the time interval from when you send a message to when the client receives the first Token.',
'messages.tokenDetails.title': 'Generation Details',
'messages.tokenDetails.total': 'Total Consumption',
+ 'minimap.emptyPreview': '(No text content)',
'minimap.jumpToMessage': 'Jump to message {{index}}',
'minimap.nextMessage': 'Next message',
'minimap.previousMessage': 'Previous message',
diff --git a/src/server/routers/lambda/thread.ts b/src/server/routers/lambda/thread.ts
index c0c9b5611e3..848decb42ce 100644
--- a/src/server/routers/lambda/thread.ts
+++ b/src/server/routers/lambda/thread.ts
@@ -1,3 +1,4 @@
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { MessageModel } from '@/database/models/message';
@@ -8,6 +9,29 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { type ThreadItem } from '@/types/topic/thread';
import { createThreadSchema } from '@/types/topic/thread';
+/**
+ * `ThreadModel.create` uses `onConflictDoNothing()` and returns undefined when
+ * the inserted id collides with an existing row. With server-generated 16-char
+ * nanoids this branch was effectively unreachable, but caller-provided ids
+ * (used by the CC subagent executor to allocate `threadId` synchronously
+ * before the create call resolves) can collide on retry or duplicate
+ * submission. Translating undefined into a CONFLICT error is required to
+ * avoid the downstream `messageModel.create({ threadId: undefined })` orphan
+ * write the original code allowed.
+ */
+const ensureThreadCreated = <T extends { id: string } | undefined>(
+ thread: T,
+ providedId: string | undefined,
+): NonNullable<T> => {
+ if (thread) return thread as NonNullable<T>;
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: providedId
+ ? `Thread id collision: ${providedId}. Regenerate the id and retry.`
+ : 'Thread create returned no row',
+ });
+};
+
const threadProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -21,16 +45,20 @@ const threadProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
export const threadRouter = router({
createThread: threadProcedure.input(createThreadSchema).mutation(async ({ input, ctx }) => {
- const thread = await ctx.threadModel.create({
- metadata: input.metadata,
- parentThreadId: input.parentThreadId,
- sourceMessageId: input.sourceMessageId,
- title: input.title,
- topicId: input.topicId,
- type: input.type,
- });
+ const thread = ensureThreadCreated(
+ await ctx.threadModel.create({
+ id: input.id,
+ metadata: input.metadata,
+ parentThreadId: input.parentThreadId,
+ sourceMessageId: input.sourceMessageId,
+ title: input.title,
+ topicId: input.topicId,
+ type: input.type,
+ }),
+ input.id,
+ );
- return thread?.id;
+ return thread.id;
}),
createThreadWithMessage: threadProcedure
.input(
@@ -39,18 +67,22 @@ export const threadRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- const thread = await ctx.threadModel.create({
- metadata: input.metadata,
- parentThreadId: input.parentThreadId,
- sourceMessageId: input.sourceMessageId,
- title: input.message.content.slice(0, 20),
- topicId: input.topicId,
- type: input.type,
- });
+ const thread = ensureThreadCreated(
+ await ctx.threadModel.create({
+ id: input.id,
+ metadata: input.metadata,
+ parentThreadId: input.parentThreadId,
+ sourceMessageId: input.sourceMessageId,
+ title: input.message.content.slice(0, 20),
+ topicId: input.topicId,
+ type: input.type,
+ }),
+ input.id,
+ );
- const message = await ctx.messageModel.create({ ...input.message, threadId: thread?.id });
+ const message = await ctx.messageModel.create({ ...input.message, threadId: thread.id });
- return { messageId: message?.id, threadId: thread?.id };
+ return { messageId: message?.id, threadId: thread.id };
}),
getThread: threadProcedure.query(async ({ ctx }): Promise<ThreadItem[]> => {
return ctx.threadModel.query() as any;