🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(verify): topic Goal tray above the composer (Labs) (#17375)
Arvin Xu5b186ceac7b1
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex f6610e68c74..f2cd59150a2 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -146,6 +146,74 @@ export const acceptanceRouter = router({return acceptance ?? null;}),+ /**+ * Persist a subject's standing acceptance checklist (the topic tray). Ensures+ * the aggregate exists, then writes the list into its `config.checklist` — so+ * the criteria live with the verify aggregate, not in client storage.+ */+ saveChecklist: acceptanceWriteProcedure+ .input(+ z.object({+ checklist: z.array(+ z.object({+ id: z.string(),+ method: z.string().optional(),+ name: z.string(),+ }),+ ),+ subjectId: z.string(),+ subjectType: subjectTypeSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const aggregate = await ctx.acceptanceService.ensureForSubject(+ input.subjectType,+ input.subjectId,+ );+ await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {+ config: { ...aggregate.config, checklist: input.checklist },+ });+ return { checklist: input.checklist, id: aggregate.id };+ } catch (error) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: error instanceof Error ? error.message : 'Acceptance subject not found',+ });+ }+ }),++ /**+ * Set (or update) a subject's acceptance goal — the one-sentence outcome the+ * conversation is delivering. Unlike `ensure`, this overwrites: the goal is a+ * user-editable field, so a later edit must stick.+ */+ saveGoal: acceptanceWriteProcedure+ .input(+ z.object({+ requirement: z.string().max(2000),+ subjectId: z.string(),+ subjectType: subjectTypeSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const aggregate = await ctx.acceptanceService.ensureForSubject(+ input.subjectType,+ input.subjectId,+ );+ await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {+ requirement: input.requirement,+ });+ return { id: aggregate.id, requirement: input.requirement };+ } catch (error) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: error instanceof Error ? error.message : 'Acceptance subject not found',+ });+ }+ }),+/*** One-shot payload for the acceptance decision workspace: the aggregate, its* subject header, the round ledger (each round's run + report), and thediff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex 121bd4f405e..2d867224132 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -13,8 +13,6 @@"features.claudeCodeSdk.title": "Claude Code SDK Runtime","features.fleet.desc": "Show the Fleet entry in the title bar — a side-by-side dashboard of all running tasks across your agents.","features.fleet.title": "Fleet View",- "features.foldFinishedTurn.desc": "Collapse the process (reasoning and tool calls) of finished agent turns under a \"Processed\" header once the final answer is visible. Click to expand the process.",- "features.foldFinishedTurn.title": "Fold Finished Turns","features.groupChat.desc": "Enable multi-agent group chat coordination.","features.groupChat.title": "Group Chat (Multi-Agent)","features.imessage.desc": "Connect agents to iMessage through the local LobeHub Desktop BlueBubbles bridge.",@@ -31,5 +29,7 @@"features.platformAgent.title": "Connect Agent","features.taskVerify.desc": "Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.","features.taskVerify.title": "Task Delivery Acceptance",+ "features.topicAcceptance.desc": "Author a delivery checklist for the current topic right above the composer, so the conversation is held to standards you can edit any time.",+ "features.topicAcceptance.title": "Topic Acceptance","title": "Labs"}diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex cb5ce04c05d..7f657ec6b5d 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -154,6 +154,30 @@"acceptance.subject.topic": "Topic","acceptance.surface.other": "Other","acceptance.titleFallback": "Delivery acceptance",+ "acceptance.tray.addCheck": "Add tracking item",+ "acceptance.tray.editModal.addTitle": "Add tracking item",+ "acceptance.tray.editModal.editTitle": "Edit tracking item",+ "acceptance.tray.editModal.methodLabel": "How to check (optional)",+ "acceptance.tray.editModal.methodPlaceholder": "e.g. it stays on topic and reads clearly",+ "acceptance.tray.editModal.nameLabel": "What to track",+ "acceptance.tray.editModal.namePlaceholder": "e.g. covers the key points",+ "acceptance.tray.editModal.remove": "Delete this item",+ "acceptance.tray.editModal.save": "Save",+ "acceptance.tray.goalArmed": "Goal on — your next message becomes this conversation’s goal",+ "acceptance.tray.goalLabel": "Goal",+ "acceptance.tray.goalModal.editTitle": "Edit goal",+ "acceptance.tray.goalModal.hint": "One sentence describing what a good result for this conversation looks like. Everything is tracked against it.",+ "acceptance.tray.goalModal.placeholder": "e.g. a clear 300-word intro to RAG a beginner can follow",+ "acceptance.tray.goalModal.save": "Save goal",+ "acceptance.tray.goalModal.setTitle": "Set the goal",+ "acceptance.tray.goalSection": "Goal",+ "acceptance.tray.menuSetGoal": "Set goal",+ "acceptance.tray.saveFailed.network": "You appear to be offline — the change wasn’t saved.",+ "acceptance.tray.saveFailed.server": "Couldn’t save the change. Please try again.",+ "acceptance.tray.section.method": "How to check",+ "acceptance.tray.section.methodEmpty": "No method described yet.",+ "acceptance.tray.trackCount": "· {{count}} tracked",+ "acceptance.tray.trackSection": "Tracking","acceptance.verdict.inProgress": "Acceptance in progress","acceptance.verdict.latestAt": "last verified {{time}}","acceptance.viewFullReport": "View full report",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex 9f5c334b4ab..b9cdd005b5e 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -13,8 +13,6 @@"features.claudeCodeSdk.title": "Claude Code SDK 运行时","features.fleet.desc": "在标题栏显示 Fleet 入口——把当前账号下所有运行中的任务并排展示的看板。","features.fleet.title": "Fleet 并排视图",- "features.foldFinishedTurn.desc": "当最终回答可见后,将已完成回合的过程(推理与工具调用)折叠进「已处理」标题;点击可展开过程。",- "features.foldFinishedTurn.title": "折叠已完成回合","features.groupChat.desc": "启用多代理协同群聊功能。","features.groupChat.title": "群聊(多代理)","features.imessage.desc": "通过本地 LobeHub 桌面 BlueBubbles 桥接器将代理连接到 iMessage。",@@ -31,5 +29,7 @@"features.platformAgent.title": "接入助理","features.taskVerify.desc": "在任务详情里增加「交付验收」模块:一句话描述验收要求,AI 自动生成可编辑的验收项。","features.taskVerify.title": "任务交付验收",+ "features.topicAcceptance.desc": "在输入框上方为当前话题编写一份交付验收清单,让对话对照你随时可编辑的标准来交付。",+ "features.topicAcceptance.title": "话题验收","title": "实验室"}diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 6b5a0b10b2d..34d041d5c99 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -154,6 +154,30 @@"acceptance.subject.topic": "话题","acceptance.surface.other": "其他","acceptance.titleFallback": "交付验收",+ "acceptance.tray.addCheck": "添加跟踪项",+ "acceptance.tray.editModal.addTitle": "添加跟踪项",+ "acceptance.tray.editModal.editTitle": "编辑跟踪项",+ "acceptance.tray.editModal.methodLabel": "怎么看(可选)",+ "acceptance.tray.editModal.methodPlaceholder": "例:紧扣主题、表达清晰",+ "acceptance.tray.editModal.nameLabel": "跟踪什么",+ "acceptance.tray.editModal.namePlaceholder": "例:覆盖了关键要点",+ "acceptance.tray.editModal.remove": "删除此项",+ "acceptance.tray.editModal.save": "保存",+ "acceptance.tray.goalArmed": "已设定目标 · 你的下一条消息将成为该对话的目标",+ "acceptance.tray.goalLabel": "目标",+ "acceptance.tray.goalModal.editTitle": "编辑目标",+ "acceptance.tray.goalModal.hint": "用一句话描述这次对话「做成什么样算好」。所有跟踪项都对照它来看。",+ "acceptance.tray.goalModal.placeholder": "例:写一篇 300 字、初学者能看懂的 RAG 介绍",+ "acceptance.tray.goalModal.save": "保存目标",+ "acceptance.tray.goalModal.setTitle": "设定目标",+ "acceptance.tray.goalSection": "目标",+ "acceptance.tray.menuSetGoal": "设定目标",+ "acceptance.tray.saveFailed.network": "网络似乎离线,改动未保存。",+ "acceptance.tray.saveFailed.server": "改动保存失败,请重试。",+ "acceptance.tray.section.method": "怎么看",+ "acceptance.tray.section.methodEmpty": "还没有描述怎么看。",+ "acceptance.tray.trackCount": "· {{count}} 项跟踪",+ "acceptance.tray.trackSection": "目标跟踪","acceptance.verdict.inProgress": "验收进行中","acceptance.verdict.latestAt": "最近验证 {{time}}","acceptance.viewFullReport": "查看完整报告",diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex c98b4a3b704..90c7b3a9636 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -20,9 +20,6 @@ export default {'features.fleet.desc':'Show the Fleet entry in the title bar — a side-by-side dashboard of all running tasks across your agents.','features.fleet.title': 'Fleet View',- 'features.foldFinishedTurn.desc':- 'Collapse the process (reasoning and tool calls) of finished agent turns under a "Processed" header once the final answer is visible. Click to expand the process.',- 'features.foldFinishedTurn.title': 'Fold Finished Turns','features.imessage.desc':'Connect agents to iMessage through the local LobeHub Desktop BlueBubbles bridge.','features.imessage.title': 'iMessage Channel',@@ -46,5 +43,8 @@ export default {'features.taskVerify.desc':'Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.','features.taskVerify.title': 'Task Delivery Acceptance',+ 'features.topicAcceptance.desc':+ 'Author a delivery checklist for the current topic right above the composer, so the conversation is held to standards you can edit any time.',+ 'features.topicAcceptance.title': 'Topic Acceptance','title': 'Labs',};diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 35e5939c76c..d079370a4e3 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -171,6 +171,32 @@ export default {'acceptance.subject.document': 'Document','acceptance.subject.task': 'Task','acceptance.subject.topic': 'Topic',+ 'acceptance.tray.addCheck': 'Add tracking item',+ 'acceptance.tray.editModal.addTitle': 'Add tracking item',+ 'acceptance.tray.editModal.editTitle': 'Edit tracking item',+ 'acceptance.tray.editModal.methodLabel': 'How to check (optional)',+ 'acceptance.tray.editModal.methodPlaceholder': 'e.g. it stays on topic and reads clearly',+ 'acceptance.tray.editModal.nameLabel': 'What to track',+ 'acceptance.tray.editModal.namePlaceholder': 'e.g. covers the key points',+ 'acceptance.tray.editModal.remove': 'Delete this item',+ 'acceptance.tray.editModal.save': 'Save',+ 'acceptance.tray.goalLabel': 'Goal',+ 'acceptance.tray.goalModal.editTitle': 'Edit goal',+ 'acceptance.tray.goalModal.hint':+ 'One sentence describing what a good result for this conversation looks like. Everything is tracked against it.',+ 'acceptance.tray.goalModal.placeholder':+ 'e.g. a clear 300-word intro to RAG a beginner can follow',+ 'acceptance.tray.goalModal.save': 'Save goal',+ 'acceptance.tray.goalModal.setTitle': 'Set the goal',+ 'acceptance.tray.goalSection': 'Goal',+ 'acceptance.tray.goalArmed': 'Goal on — your next message becomes this conversation’s goal',+ 'acceptance.tray.saveFailed.network': 'You appear to be offline — the change wasn’t saved.',+ 'acceptance.tray.saveFailed.server': 'Couldn’t save the change. Please try again.',+ 'acceptance.tray.menuSetGoal': 'Set goal',+ 'acceptance.tray.section.method': 'How to check',+ 'acceptance.tray.section.methodEmpty': 'No method described yet.',+ 'acceptance.tray.trackCount': '· {{count}} tracked',+ 'acceptance.tray.trackSection': 'Tracking','acceptance.surface.other': 'Other','acceptance.titleFallback': 'Delivery acceptance','acceptance.verdict.inProgress': 'Acceptance in progress',diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 981eb5b3296..212d3ad5da6 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -106,10 +106,6 @@ export const UserLabSchema = z.object({* enable the Fleet view (side-by-side running-task dashboard)*/enableFleet: z.boolean().optional(),- /**- * fold a finished agent turn's process under a "已处理" header when its final answer is visible- */- enableFoldFinishedTurn: z.boolean().optional(),/*** enable multi-agent group chat mode*/@@ -142,6 +138,11 @@ export const UserLabSchema = z.object({* enable the task delivery-acceptance (verify) config UI on the task detail*/enableTaskVerify: z.boolean().optional(),+ /**+ * enable the per-topic acceptance tray above the composer (author a topic's+ * delivery checklist inline)+ */+ enableTopicAcceptance: z.boolean().optional(),});export type UserLab = z.infer<typeof UserLabSchema>;diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 7a901892dbb..3297650dec8 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -91,7 +91,23 @@ export interface AcceptanceVisualRender {* a topic-level override, or a document acceptance rule, so it lives with the* generic aggregate rather than only in task types.*/+/**+ * One user-authored acceptance criterion in a subject's standing checklist+ * (e.g. the topic acceptance tray). Every item is judged by the verify agent;+ * `method` is the optional "how to check" note.+ */+export interface AcceptanceChecklistItem {+ id: string;+ method?: string;+ name: string;+}+export interface AcceptanceConfig {+ /**+ * The subject's standing, user-editable acceptance checklist (topic tray).+ * Persisted here so it lives with the verify aggregate, not in client storage.+ */+ checklist?: AcceptanceChecklistItem[];enabled?: boolean;maxIterations?: number;verifierAgentId?: string;diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsxindex 783480dc291..ee035043cad 100644--- a/src/features/ChatInput/ActionBar/Plus/index.tsx+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx@@ -18,6 +18,7 @@ import {PlusIcon,SearchCheck,Settings2Icon,+ TargetIcon,TypeIcon,} from 'lucide-react';import type { ReactNode } from 'react';@@ -36,6 +37,7 @@ import {chatConfigByIdSelectors,} from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';+import { useChatStore } from '@/store/chat';import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -45,8 +47,10 @@ import {useServerConfigStore,} from '@/store/serverConfig';import { useUserStore } from '@/store/user';-import { settingsSelectors } from '@/store/user/selectors';+import { labPreferSelectors, settingsSelectors } from '@/store/user/selectors';+import { useGoalArmStore } from '../../../Conversation/ChatInput/VerifyTray/goalArmStore';+import { openTopicGoalModal } from '../../../Conversation/ChatInput/VerifyTray/useTopicChecklist';import { useAgentId } from '../../hooks/useAgentId';import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';@@ -288,12 +292,20 @@ const PlusAction = memo(() => {const { t } = useTranslation('chat');const { t: tEditor } = useTranslation('editor');const { t: tSetting } = useTranslation('setting');+ const { t: tVerify } = useTranslation('verify');const isDark = useIsDark();const agentId = useAgentId();const { canConfigureResource } = useChatInputResourceAccess();const { updateAgentChatConfig } = useUpdateAgentConfig();const [dropdownOpen, setDropdownOpen] = useState(false);+ // Topic acceptance (lab): a "new acceptance item" entry in the "+" menu, so a+ // topic's checklist starts from here instead of an always-on strip above the+ // composer. Global stores only — Plus renders on surfaces without conversation+ // context.+ const enableTopicAcceptance = useUserStore(labPreferSelectors.enableTopicAcceptance);+ const activeTopicId = useChatStore((s) => s.activeTopicId);+const upload = useFileStore((s) => s.uploadChatFiles);const { enableKnowledgeBase } = useServerConfigStore(featureFlagsSelectors);const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);@@ -529,11 +541,35 @@ const PlusAction = memo(() => {),),} as ActionDropdownMenuItems[number],- { type: 'divider' },]: [];- const capabilityItems: ActionDropdownMenuItems = canConfigureResource+ // Agent Gateway sits below the formatting toolbar (grouped with advanced+ // params), gated on the resource-configuration permission.+ const gatewayItem: ActionDropdownMenuItems =+ canConfigureResource && enableGatewayMode+ ? [+ {+ checked: isGatewayModeEnabled,+ icon: Cloud,+ key: 'gateway-mode',+ label: (+ <PopoverLabel+ label={renderGatewayModeLabel()}+ popoverContent={gatewayModeInfo}+ // Clear the trailing toggle so the card sits to the right of the whole menu.+ sideOffset={64}+ />+ ),+ onCheckedChange: handleToggleGatewayMode,+ type: 'switch',+ } as ActionDropdownMenuItems[number],+ ]+ : [];++ // Memory / Web Search / Skills form one group (no dividers between them),+ // hidden entirely when the user can't configure resources.+ const coreItems: ActionDropdownMenuItems = canConfigureResource? [// Memory toggle — trailing switch; toggle by clicking the switch or the whole row{@@ -609,55 +645,37 @@ const PlusAction = memo(() => {type: 'switch',} as ActionDropdownMenuItems[number],]),- ...(enableGatewayMode- ? [- {- checked: isGatewayModeEnabled,- icon: Cloud,- key: 'gateway-mode',- label: (- <PopoverLabel- label={renderGatewayModeLabel()}- popoverContent={gatewayModeInfo}- // Clear the trailing toggle so the card sits to the right of the whole menu.- sideOffset={64}- />- ),- onCheckedChange: handleToggleGatewayMode,- type: 'switch',- } as ActionDropdownMenuItems[number],- ]- : []),- { type: 'divider' },- // Skills (with "Add Skills..." merged in) sits directly under the Web Search divider.+ // Skills (with "Add Skills..." merged in) stays in the same group....toolsItems,- // Formatting toolbar toggle — trailing switch; toggle by clicking the switch or the whole row- {- checked: Boolean(showTypoBar),- icon: TypeIcon,- key: 'typo',- label: tEditor('actions.typobar.title'),- onCheckedChange: (checked: boolean) => setShowTypoBar(checked),- type: 'switch',- },- // Advanced parameter settings — mirrors ParamsPanelToggle in the agent header.- {- icon: Settings2Icon,- key: 'params',- label: renderActive(tSetting('settingModel.params.title'), isParamsPanelActive),- onClick: handleToggleParams,- },]- : [- {- checked: Boolean(showTypoBar),- icon: TypeIcon,- key: 'typo',- label: tEditor('actions.typobar.title'),- onCheckedChange: (checked: boolean) => setShowTypoBar(checked),- type: 'switch',- },- ];+ : [];++ // Formatting toolbar is always available; Agent Gateway + advanced params+ // only when the user can configure resources.+ const formatItems: ActionDropdownMenuItems = [+ // Formatting toolbar toggle — trailing switch; toggle by clicking the switch or the whole row+ {+ checked: Boolean(showTypoBar),+ icon: TypeIcon,+ key: 'typo',+ label: tEditor('actions.typobar.title'),+ onCheckedChange: (checked: boolean) => setShowTypoBar(checked),+ type: 'switch',+ },+ // Agent Gateway directly below the formatting toolbar.+ ...gatewayItem,+ // Advanced parameter settings — only when resources can be configured.+ ...(canConfigureResource+ ? [+ {+ icon: Settings2Icon,+ key: 'params',+ label: renderActive(tSetting('settingModel.params.title'), isParamsPanelActive),+ onClick: handleToggleParams,+ } as ActionDropdownMenuItems[number],+ ]+ : []),+ ];// "Add Attachments..." merges file upload with the knowledge base (libraries / files).// When the knowledge base is disabled there is no submenu, so Upload stays a top-level entry.@@ -692,11 +710,45 @@ const PlusAction = memo(() => {]: uploadItems;- return [...attachmentsItems, ...capabilityItems];+ // Before a topic exists there is nothing to persist a goal onto, so the+ // entry *arms* the goal (the next message becomes it); once a topic exists+ // it opens the editor directly.+ const acceptanceItems: ActionDropdownMenuItems = enableTopicAcceptance+ ? [+ {+ icon: TargetIcon,+ key: 'set-topic-goal',+ label: tVerify('acceptance.tray.menuSetGoal'),+ onClick: () => {+ if (activeTopicId) {+ void openTopicGoalModal(activeTopicId);+ } else if (agentId) {+ useGoalArmStore.getState().arm(agentId);+ message.success(tVerify('acceptance.tray.goalArmed'));+ }+ },+ },+ ]+ : [];++ // Grouped with a single divider only between non-empty groups:+ // [attachments] | [memory · search · skills] | [set goal] | [formatting · gateway · params]+ const menuGroups: ActionDropdownMenuItems[] = [+ attachmentsItems,+ coreItems,+ acceptanceItems,+ formatItems,+ ];+ return menuGroups+ .filter((group) => group.length > 0)+ .flatMap((group, index) => (index === 0 ? group : [{ type: 'divider' as const }, ...group]));}, [- activeSearchOption,agentId,+ activeSearchOption,+ activeTopicId,canConfigureResource,+ enableTopicAcceptance,+ tVerify,canUploadImage,canUploadVideo,canUploadAudio,diff --git a/src/features/Conversation/ChatInput/VerifyTray/CheckItem.tsx b/src/features/Conversation/ChatInput/VerifyTray/CheckItem.tsxnew file mode 100644index 00000000000..7fb59f70b55--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/CheckItem.tsx@@ -0,0 +1,110 @@+'use client';++import { ActionIcon, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronDown, ChevronRight, CircleDashed, PencilIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { openCheckEditModal } from './EditModal';+import type { TrayCheck } from './types';++const styles = createStaticStyles(({ css }) => ({+ detail: css`+ padding-block: 2px 4px;+ padding-inline-start: 22px;+ `,+ head: css`+ cursor: pointer;+ user-select: none;+ `,+ method: css`+ color: ${cssVar.colorTextSecondary};+ `,+ row: css`+ padding-block: 6px;+ padding-inline: 14px;+ border-radius: ${cssVar.borderRadius};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:hover .verify-tray-row-edit {+ opacity: 1;+ }+ `,+ rowEdit: css`+ opacity: 0;+ transition: opacity 0.15s;+ `,+ secLabel: css`+ font-size: 10px;+ color: ${cssVar.colorTextQuaternary};+ text-transform: uppercase;+ letter-spacing: 0.04em;+ `,+}));++interface CheckItemProps {+ check: TrayCheck;+ onRemove: () => void;+ onUpdate: (patch: Partial<Omit<TrayCheck, 'id'>>) => void;+}++const CheckItem = memo<CheckItemProps>(({ check, onRemove, onUpdate }) => {+ const { t } = useTranslation('verify');+ const [open, setOpen] = useState(false);++ return (+ <Flexbox className={styles.row} gap={8}>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.head}+ gap={8}+ justify={'space-between'}+ onClick={() => setOpen(!open)}+ >+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>+ {/* Draft item has no verdict yet — a neutral glyph, not a false pass/fail. */}+ <Icon color={cssVar.colorTextQuaternary} icon={CircleDashed} size={14} />+ <Text ellipsis fontSize={13}>+ {check.name}+ </Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={4} style={{ flexShrink: 0 }}>+ <Tooltip title={t('acceptance.tray.editModal.editTitle')}>+ <ActionIcon+ className={cx('verify-tray-row-edit', styles.rowEdit)}+ icon={PencilIcon}+ size={'small'}+ onClick={(e) => {+ e.stopPropagation();+ openCheckEditModal({ initial: check, onRemove, onSubmit: onUpdate });+ }}+ />+ </Tooltip>+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={open ? ChevronDown : ChevronRight}+ size={14}+ />+ </Flexbox>+ </Flexbox>++ {open && (+ <Flexbox className={styles.detail} gap={5}>+ <Text className={styles.secLabel}>{t('acceptance.tray.section.method')}</Text>+ <Text className={styles.method} fontSize={12}>+ {check.method || t('acceptance.tray.section.methodEmpty')}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ );+});++CheckItem.displayName = 'VerifyTrayCheckItem';++export default CheckItem;diff --git a/src/features/Conversation/ChatInput/VerifyTray/EditModal.tsx b/src/features/Conversation/ChatInput/VerifyTray/EditModal.tsxnew file mode 100644index 00000000000..d8f168d670a--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/EditModal.tsx@@ -0,0 +1,109 @@+'use client';++import { Flexbox, Input, Text, TextArea } from '@lobehub/ui';+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';+import { t } from 'i18next';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { TrayCheck } from './types';++interface EditContentProps {+ /** Existing check to edit; undefined = authoring a new one. */+ initial?: TrayCheck;+ onRemove?: () => void;+ onSubmit: (value: { method: string; name: string }) => void | Promise<unknown>;+}++const EditContent = memo<EditContentProps>(({ initial, onRemove, onSubmit }) => {+ const { t: tv } = useTranslation('verify');+ const { close } = useModalContext();+ const [name, setName] = useState(initial?.name ?? '');+ const [method, setMethod] = useState(initial?.method ?? '');+ const [saving, setSaving] = useState(false);++ const handleSave = async () => {+ const trimmed = name.trim();+ if (!trimmed || saving) return;+ setSaving(true);+ try {+ // Only close once the write lands; a failed save keeps the modal open.+ await onSubmit({ method: method.trim(), name: trimmed });+ close();+ } catch {+ // The caller already rolled back the optimistic value and toasted.+ } finally {+ setSaving(false);+ }+ };++ return (+ <Flexbox gap={16}>+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'}>+ {tv('acceptance.tray.editModal.nameLabel')}+ </Text>+ <Input+ placeholder={tv('acceptance.tray.editModal.namePlaceholder')}+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </Flexbox>++ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'}>+ {tv('acceptance.tray.editModal.methodLabel')}+ </Text>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 2 }}+ placeholder={tv('acceptance.tray.editModal.methodPlaceholder')}+ value={method}+ onChange={(e) => setMethod(e.target.value)}+ />+ </Flexbox>++ <Flexbox horizontal align={'center'} justify={'space-between'}>+ {onRemove ? (+ <Button+ danger+ type={'text'}+ onClick={() => {+ onRemove();+ close();+ }}+ >+ {tv('acceptance.tray.editModal.remove')}+ </Button>+ ) : (+ <span />+ )}+ <Flexbox horizontal gap={8}>+ <Button disabled={saving} onClick={close}>+ {tv('acceptance.actions.cancel')}+ </Button>+ <Button+ disabled={!name.trim() || saving}+ loading={saving}+ type={'primary'}+ onClick={handleSave}+ >+ {tv('acceptance.tray.editModal.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+});++EditContent.displayName = 'VerifyTrayEditContent';++export const openCheckEditModal = (options: EditContentProps): ModalInstance =>+ createModal({+ content: <EditContent {...options} />,+ footer: null,+ maskClosable: true,+ title: options.initial+ ? t('acceptance.tray.editModal.editTitle', { ns: 'verify' })+ : t('acceptance.tray.editModal.addTitle', { ns: 'verify' }),+ width: 'min(90vw, 520px)',+ });diff --git a/src/features/Conversation/ChatInput/VerifyTray/GoalModal.tsx b/src/features/Conversation/ChatInput/VerifyTray/GoalModal.tsxnew file mode 100644index 00000000000..768cf14d194--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/GoalModal.tsx@@ -0,0 +1,75 @@+'use client';++import { Flexbox, Text, TextArea } from '@lobehub/ui';+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';+import { t } from 'i18next';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++interface GoalContentProps {+ initialGoal?: string;+ onSubmit: (goal: string) => void | Promise<unknown>;+}++const GoalContent = memo<GoalContentProps>(({ initialGoal, onSubmit }) => {+ const { t: tv } = useTranslation('verify');+ const { close } = useModalContext();+ const [goal, setGoal] = useState(initialGoal ?? '');+ const [saving, setSaving] = useState(false);++ const handleSave = async () => {+ const trimmed = goal.trim();+ if (!trimmed || saving) return;+ setSaving(true);+ try {+ // Only close once the write actually lands — a failed save (surfaced by+ // the caller) keeps the modal open so the edit isn't silently lost.+ await onSubmit(trimmed);+ close();+ } catch {+ // The caller already rolled back the optimistic value and toasted.+ } finally {+ setSaving(false);+ }+ };++ return (+ <Flexbox gap={16}>+ <Text fontSize={13} type={'secondary'}>+ {tv('acceptance.tray.goalModal.hint')}+ </Text>+ <TextArea+ autoSize={{ maxRows: 5, minRows: 3 }}+ placeholder={tv('acceptance.tray.goalModal.placeholder')}+ value={goal}+ onChange={(e) => setGoal(e.target.value)}+ />+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={saving} onClick={close}>+ {tv('acceptance.actions.cancel')}+ </Button>+ <Button+ disabled={!goal.trim() || saving}+ loading={saving}+ type={'primary'}+ onClick={handleSave}+ >+ {tv('acceptance.tray.goalModal.save')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++GoalContent.displayName = 'VerifyTrayGoalContent';++export const openGoalModal = (options: GoalContentProps): ModalInstance =>+ createModal({+ content: <GoalContent {...options} />,+ footer: null,+ maskClosable: true,+ title: options.initialGoal+ ? t('acceptance.tray.goalModal.editTitle', { ns: 'verify' })+ : t('acceptance.tray.goalModal.setTitle', { ns: 'verify' }),+ width: 'min(90vw, 520px)',+ });diff --git a/src/features/Conversation/ChatInput/VerifyTray/GoalTray.tsx b/src/features/Conversation/ChatInput/VerifyTray/GoalTray.tsxnew file mode 100644index 00000000000..8944bf505f6--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/GoalTray.tsx@@ -0,0 +1,205 @@+'use client';++import { ActionIcon, Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronDown, ChevronRight, PencilIcon, PlusIcon, TargetIcon } from 'lucide-react';+import { memo, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++import { useConversationStore } from '../../store';+import { pickArmedMessage } from './armedMessage';+import CheckItem from './CheckItem';+import { openCheckEditModal } from './EditModal';+import { useGoalArmStore } from './goalArmStore';+import { openGoalModal } from './GoalModal';+import { useTopicGoal } from './useTopicChecklist';++const styles = createStaticStyles(({ css }) => ({+ addRow: css`+ padding-block: 4px;+ padding-inline: 8px;+ `,+ container: css`+ border: 1px solid ${cssVar.colorFillSecondary};+ border-block-end: none;+ border-start-start-radius: 12px;+ border-start-end-radius: 12px;++ background: ${cssVar.colorBgElevated};+ `,+ containerTopAttached: css`+ border-start-start-radius: 0;+ border-start-end-radius: 0;+ `,+ goalRow: css`+ padding-block: 6px 8px;+ padding-inline: 12px;++ &:hover .verify-tray-goal-edit {+ opacity: 1;+ }+ `,+ goalText: css`+ color: ${cssVar.colorTextSecondary};+ `,+ head: css`+ cursor: pointer;+ user-select: none;+ padding-block: 6px;+ padding-inline: 12px;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ rowEdit: css`+ opacity: 0;+ transition: opacity 0.15s;+ `,+ secLabel: css`+ font-size: 10px;+ color: ${cssVar.colorTextQuaternary};+ text-transform: uppercase;+ letter-spacing: 0.04em;+ `,+ summary: css`+ overflow: hidden;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++interface GoalTrayProps {+ topAttached?: boolean;+}++/**+ * Topic Goal tray, floating just above the composer once a topic exists (behind+ * the `enableTopicAcceptance` lab). Before a topic is created the goal entry+ * lives in the composer "+" menu; the moment the conversation has a topic, the+ * goal earns a persistent home above the input — the "sent" state the user+ * asked for.+ *+ * When the user armed the goal from the "+" menu before sending, the first+ * message they send becomes the goal (the message IS the goal); otherwise the+ * goal is only ever set explicitly via the "+" menu / pencil. Tracking checks+ * live under it.+ */+const GoalTray = memo<GoalTrayProps>(({ topAttached }) => {+ const { t } = useTranslation('verify');+ const enabled = useUserStore(labPreferSelectors.enableTopicAcceptance);+ const topicId = useConversationStore((s) => s.context.topicId);+ const agentId = useConversationStore((s) => s.context.agentId);+ const displayMessages = useConversationStore((s) => s.displayMessages);+ const armedAt = useGoalArmStore((s) => (agentId ? s.armedAt[agentId] : undefined));+ const disarm = useGoalArmStore((s) => s.disarm);+ const { goal, checks, isLoading, setGoal, addCheck, updateCheck, removeCheck } = useTopicGoal(+ topicId ?? undefined,+ );+ const [open, setOpen] = useState(false);++ // The armed goal only applies to the topic it was armed in. Once a topic+ // becomes active while armed, adopt the message the user actually armed — the+ // first user message sent at or after the arm — as the goal. Older messages+ // carried over from the default conversation predate the arm, so they're+ // skipped (which also stops switching into a pre-existing topic from hijacking+ // the arm or clobbering its saved goal). Spend the arm either way, so it never+ // leaks to the next topic.+ useEffect(() => {+ if (!enabled || !agentId || armedAt === undefined || !topicId || isLoading) return;+ if (!goal) {+ const armedMessage = pickArmedMessage(displayMessages, armedAt);+ if (armedMessage?.content) void setGoal(armedMessage.content);+ }+ disarm(agentId);+ }, [enabled, agentId, armedAt, topicId, isLoading, goal, displayMessages, setGoal, disarm]);++ if (!enabled || !topicId || !goal) return null;++ const openAddCheck = () => openCheckEditModal({ onSubmit: (v) => addCheck(v) });+ const openEditGoal = () => openGoalModal({ initialGoal: goal, onSubmit: (v) => setGoal(v) });++ return (+ <Flexbox className={cx(styles.container, topAttached && styles.containerTopAttached)}>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.head}+ gap={8}+ justify={'space-between'}+ onClick={() => setOpen(!open)}+ >+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>+ <Icon color={cssVar.colorTextSecondary} icon={TargetIcon} size={14} />+ <Text strong fontSize={12} style={{ flexShrink: 0 }}>+ {t('acceptance.tray.goalLabel')}+ </Text>+ {/* The goal sentence rides inline only while collapsed; expanded, the+ "Goal" section below owns it, so showing it here too is redundant. */}+ {!open && <span className={styles.summary}>{goal}</span>}+ {checks.length > 0 && (+ <Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>+ {t('acceptance.tray.trackCount', { count: checks.length })}+ </Text>+ )}+ </Flexbox>+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={open ? ChevronDown : ChevronRight}+ size={14}+ />+ </Flexbox>++ {open && (+ <>+ <Flexbox className={styles.goalRow} gap={4}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text className={styles.secLabel}>{t('acceptance.tray.goalSection')}</Text>+ <Tooltip title={t('acceptance.tray.goalModal.editTitle')}>+ <ActionIcon+ className={cx('verify-tray-goal-edit', styles.rowEdit)}+ icon={PencilIcon}+ size={'small'}+ onClick={openEditGoal}+ />+ </Tooltip>+ </Flexbox>+ <Text className={styles.goalText} fontSize={13}>+ {goal}+ </Text>+ </Flexbox>++ {checks.length > 0 && (+ <Flexbox className={styles.goalRow} gap={2} style={{ paddingBlock: 0 }}>+ <Text className={styles.secLabel}>{t('acceptance.tray.trackSection')}</Text>+ </Flexbox>+ )}+ {checks.map((check) => (+ <CheckItem+ check={check}+ key={check.id}+ onRemove={() => removeCheck(check.id)}+ onUpdate={(patch) => updateCheck(check.id, patch)}+ />+ ))}+ <Flexbox horizontal className={styles.addRow}>+ <Button icon={PlusIcon} size={'small'} type={'text'} onClick={openAddCheck}>+ {t('acceptance.tray.addCheck')}+ </Button>+ </Flexbox>+ </>+ )}+ </Flexbox>+ );+});++GoalTray.displayName = 'GoalTray';++export default GoalTray;diff --git a/src/features/Conversation/ChatInput/VerifyTray/armedMessage.test.ts b/src/features/Conversation/ChatInput/VerifyTray/armedMessage.test.tsnew file mode 100644index 00000000000..2141f0471b4--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/armedMessage.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { pickArmedMessage } from './armedMessage';++const msg = (role: string, createdAt: number, content = `${role}@${createdAt}`) => ({+ content,+ createdAt,+ role,+});++describe('pickArmedMessage', () => {+ it('adopts the message sent after arming, not an older carried-over one', () => {+ // Regression: a goal armed at t=100 after the default conversation already+ // had a user message at t=10 must NOT skip to that older message.+ const messages = [msg('user', 10, 'carried over'), msg('user', 150, 'the armed one')];+ expect(pickArmedMessage(messages, 100)?.content).toBe('the armed one');+ });++ it('returns the message exactly at armedAt (inclusive)', () => {+ const messages = [msg('user', 100, 'exact')];+ expect(pickArmedMessage(messages, 100)?.content).toBe('exact');+ });++ it('ignores assistant/tool messages', () => {+ const messages = [msg('assistant', 120), msg('tool', 130), msg('user', 140, 'mine')];+ expect(pickArmedMessage(messages, 100)?.content).toBe('mine');+ });++ it('returns undefined when every message predates the arm (stale arm on a pre-existing topic)', () => {+ const messages = [msg('user', 10), msg('assistant', 20), msg('user', 30)];+ expect(pickArmedMessage(messages, 100)).toBeUndefined();+ });++ it('returns undefined for an empty conversation', () => {+ expect(pickArmedMessage([], 100)).toBeUndefined();+ });+});diff --git a/src/features/Conversation/ChatInput/VerifyTray/armedMessage.ts b/src/features/Conversation/ChatInput/VerifyTray/armedMessage.tsnew file mode 100644index 00000000000..625c1be2498--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/armedMessage.ts@@ -0,0 +1,22 @@+interface ArmedMessageCandidate {+ content: string;+ createdAt: number;+ role: string;+}++/**+ * The message a pre-topic goal arm actually meant: the first user message sent+ * at or after the arm.+ *+ * A conversation can already hold earlier user messages (e.g. the default/inbox+ * conversation) that get carried into the new topic. Those predate `armedAt`, so+ * picking the *oldest* user message would either adopt the wrong text or — when+ * its timestamp is before the arm — skip adoption entirely and lose the goal.+ * Selecting the first message at/after `armedAt` both preserves the armed+ * message and keeps a stale arm from hijacking a pre-existing topic (whose+ * messages all predate the arm → `undefined`).+ */+export const pickArmedMessage = <T extends ArmedMessageCandidate>(+ messages: T[],+ armedAt: number,+): T | undefined => messages.find((m) => m.role === 'user' && m.createdAt >= armedAt);diff --git a/src/features/Conversation/ChatInput/VerifyTray/goalArmStore.ts b/src/features/Conversation/ChatInput/VerifyTray/goalArmStore.tsnew file mode 100644index 00000000000..60ad6d62da0--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/goalArmStore.ts@@ -0,0 +1,37 @@+import { create } from 'zustand';++/**+ * Pre-topic "arm the goal" intent, keyed by agentId and stamped with the arm+ * time.+ *+ * Before a conversation has a topic there is nothing to persist a goal onto, so+ * the composer "+" menu instead *arms* the goal: the next message the user sends+ * (the one that creates the topic) becomes that topic's goal.+ *+ * The stamp scopes the intent to the topic it was armed in: the tray only adopts+ * a first message that post-dates the arm (so switching into a pre-existing topic+ * can't hijack the intent), and it spends the arm the moment any topic becomes+ * active — so a goal only ever applies to the current topic and a stray arm never+ * leaks to the next one.+ *+ * A tiny standalone store so the "+" menu (a different store scope than the tray)+ * and the tray share the intent without threading it through the big stores.+ */+interface GoalArmState {+ arm: (agentId: string) => void;+ /** agentId → arm timestamp (ms). Absent means not armed. */+ armedAt: Record<string, number>;+ disarm: (agentId: string) => void;+}++export const useGoalArmStore = create<GoalArmState>((set) => ({+ arm: (agentId) => set((s) => ({ armedAt: { ...s.armedAt, [agentId]: Date.now() } })),+ armedAt: {},+ disarm: (agentId) =>+ set((s) => {+ if (s.armedAt[agentId] === undefined) return s;+ const next = { ...s.armedAt };+ delete next[agentId];+ return { armedAt: next };+ }),+}));diff --git a/src/features/Conversation/ChatInput/VerifyTray/types.ts b/src/features/Conversation/ChatInput/VerifyTray/types.tsnew file mode 100644index 00000000000..d1089883810--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/types.ts@@ -0,0 +1,18 @@+/**+ * A single topic-scoped acceptance criterion authored in the tray.+ *+ * This is a client-side draft of the delivery contract for the active topic.+ * `method` is how the item is judged (stable across turns); the per-round+ * result is not part of the draft — it is produced by a real verify run and+ * hydrated separately once the backend topic-verify path lands.+ *+ * Every item is judged by the verify agent for now; a program/deterministic+ * mode is deferred until its authoring UX is designed.+ */+export interface TrayCheck {+ id: string;+ /** How the item is judged, in the user's words (optional). */+ method: string;+ /** The acceptance criterion itself. */+ name: string;+}diff --git a/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.ts b/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.tsnew file mode 100644index 00000000000..3e5368c0178--- /dev/null+++ b/src/features/Conversation/ChatInput/VerifyTray/useTopicChecklist.ts@@ -0,0 +1,168 @@+import { toast } from '@lobehub/ui/base-ui';+import { t } from 'i18next';+import { useCallback } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import { verifyKeys } from '@/libs/swr/keys';+// Workspace-aware mutate: applies the same `augmentKey` treatment+// useClientDataSWR uses on its keys, so a mutate here actually matches the+// tray's subscription (a raw `swr` mutate would miss the augmented key).+import { mutate as scopedMutate } from '@/libs/swr/mutate';+import { verifyService } from '@/services/verify';++import { openGoalModal } from './GoalModal';+import type { TrayCheck } from './types';++/**+ * A dropped/offline connection (`fetch` rejects with a TypeError, or the browser+ * reports itself offline) versus a request the server actively rejected — the+ * two call for different copy, so the user knows whether to retry or reconnect.+ */+const isNetworkError = (error: unknown): boolean => {+ if (typeof navigator !== 'undefined' && navigator.onLine === false) return true;+ const message = error instanceof Error ? error.message : String(error);+ return /fetch failed|failed to fetch|networkerror|load failed|err_(?:network|internet)/i.test(+ message,+ );+};++const genId = () => `chk_${Math.random().toString(36).slice(2, 10)}`;++/**+ * A topic's acceptance state: the one-sentence Goal (the outcome the+ * conversation is delivering, stored as `acceptance.requirement`) and the+ * tracking checks under it (`config.checklist`).+ */+interface TopicGoal {+ checks: TrayCheck[];+ goal: string;+}++const EMPTY: TopicGoal = { checks: [], goal: '' };++const swrKey = (topicId: string) =>+ verifyKeys.acceptanceBySubject('topic', topicId) as unknown as string;++const read = async (topicId: string): Promise<TopicGoal> => {+ const acceptance = await verifyService.getAcceptanceBySubject('topic', topicId);+ return {+ checks: (acceptance?.config?.checklist ?? []).map((c) => ({+ id: c.id,+ method: c.method ?? '',+ name: c.name,+ })),+ goal: acceptance?.requirement ?? '',+ };+};++// Optimistically publish `next` to the shared SWR key so every consumer (the+// tray + the "+" menu path) reflects it immediately, then run the write and+// revalidate. If the write fails (topic deleted mid-edit, offline, server+// error), roll the optimistic value back to the server truth and surface an+// error instead of leaving a phantom unsaved edit on screen; rethrow so the+// caller (e.g. the modal) can keep itself open rather than treating the edit as+// done.+const commit = async (topicId: string, next: TopicGoal, write: () => Promise<unknown>) => {+ await scopedMutate(swrKey(topicId), next, { revalidate: false });+ try {+ await write();+ } catch (error) {+ await scopedMutate(swrKey(topicId));+ toast.error(+ isNetworkError(error)+ ? t('acceptance.tray.saveFailed.network', { ns: 'verify' })+ : t('acceptance.tray.saveFailed.server', { ns: 'verify' }),+ );+ throw error;+ }+ await scopedMutate(swrKey(topicId));+};++const persistChecks = (topicId: string, goal: string, checks: TrayCheck[]) =>+ commit(topicId, { checks, goal }, () =>+ verifyService.saveAcceptanceChecklist(+ 'topic',+ topicId,+ checks.map((c) => ({ id: c.id, method: c.method || undefined, name: c.name })),+ ),+ );++const persistGoal = (topicId: string, goal: string, checks: TrayCheck[]) =>+ commit(topicId, { checks, goal }, () => verifyService.saveAcceptanceGoal('topic', topicId, goal));++/**+ * Set the topic's Goal without a mounted tray (used by the composer "+" →+ * "Set goal" entry). Reads the current state, writes the goal, and revalidates+ * the shared SWR key so the tray reflects it.+ */+export const setTopicGoal = async (topicId: string, goal: string) => {+ const current = await read(topicId);+ await persistGoal(topicId, goal, current.checks);+};++/**+ * Open the "set goal" modal for a topic from outside a mounted tray (the+ * composer "+" menu), prefilled with the current goal so an existing one is+ * edited rather than silently overwritten.+ */+export const openTopicGoalModal = async (topicId: string) => {+ const current = await read(topicId);+ openGoalModal({+ initialGoal: current.goal || undefined,+ onSubmit: (goal) => setTopicGoal(topicId, goal),+ });+};++/**+ * The topic's Goal + tracking checks, persisted on the verify aggregate — not+ * client storage. Reads via SWR; mutations write through the acceptance router+ * and revalidate.+ */+export const useTopicGoal = (topicId: string | undefined) => {+ const { data, isLoading } = useClientDataSWR(topicId ? swrKey(topicId) : null, () =>+ read(topicId!),+ );+ const { checks, goal } = data ?? EMPTY;++ const setGoal = useCallback(+ (next: string) => {+ if (!topicId) return;+ return persistGoal(topicId, next, checks);+ },+ [topicId, checks],+ );++ const addCheck = useCallback(+ (item: { method: string; name: string }) => {+ if (!topicId) return;+ return persistChecks(topicId, goal, [...checks, { ...item, id: genId() }]);+ },+ [topicId, goal, checks],+ );++ const updateCheck = useCallback(+ (id: string, patch: Partial<Omit<TrayCheck, 'id'>>) => {+ if (!topicId) return;+ return persistChecks(+ topicId,+ goal,+ checks.map((c) => (c.id === id ? { ...c, ...patch } : c)),+ );+ },+ [topicId, goal, checks],+ );++ const removeCheck = useCallback(+ (id: string) => {+ if (!topicId) return;+ return persistChecks(+ topicId,+ goal,+ checks.filter((c) => c.id !== id),+ );+ },+ [topicId, goal, checks],+ );++ return { addCheck, checks, goal, isLoading, removeCheck, setGoal, updateCheck };+};diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 88b46902200..6643c96d624 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -47,6 +47,7 @@ import {getConversationChatInputUiState,toChatInputMessages,} from './utils';+import GoalTray from './VerifyTray/GoalTray';/** Max recent messages to feed into auto-complete context (≈10 conversation turns) */const MAX_CONTEXT_MESSAGES = 25;@@ -442,6 +443,7 @@ const ChatInput = memo<ChatInputProps>({!disableQueue && hasQueuedMessages && <QueueTray />}<TodoProgress topAttached={!disableQueue && hasQueuedMessages} /><OpStatusTray topAttached={(!disableQueue && hasQueuedMessages) || hasTodos} />+ <GoalTray topAttached={(!disableQueue && hasQueuedMessages) || hasTodos} /></Flexbox><DesktopChatInputactionBarStyle={actionBarStyle}diff --git a/src/features/Conversation/Messages/AssistantGroup/index.tsx b/src/features/Conversation/Messages/AssistantGroup/index.tsxindex 2cefbc3e42f..fa25fc0f83f 100644--- a/src/features/Conversation/Messages/AssistantGroup/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/index.tsx@@ -18,11 +18,7 @@ import { useAgentGroupStore } from '@/store/agentGroup';import { agentGroupSelectors } from '@/store/agentGroup/selectors';import { useGlobalStore } from '@/store/global';import { useUserStore } from '@/store/user';-import {- labPreferSelectors,- userGeneralSettingsSelectors,- userProfileSelectors,-} from '@/store/user/selectors';+import { userGeneralSettingsSelectors, userProfileSelectors } from '@/store/user/selectors';import { ReactionDisplay } from '../../components/Reaction';import { useAgentMeta } from '../../hooks';@@ -147,7 +143,6 @@ const GroupMessage = memo<GroupMessageProps>(const interrupted = groupInterrupted || blockInterrupted;const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);- const enableProcessFold = useUserStore(labPreferSelectors.enableFoldFinishedTurn);const addReaction = useConversationStore((s) => s.addReaction);const removeReaction = useConversationStore((s) => s.removeReaction);const userId = useUserStore(userProfileSelectors.userId)!;@@ -250,12 +245,14 @@ const GroupMessage = memo<GroupMessageProps>(<Flexbox gap={4}>{children && children.length > 0 && (<Group+ enableProcessFoldblocks={children}content={lastAssistantMsg?.content}contentId={contentId}- defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}disableEditing={disableEditing}- enableProcessFold={enableProcessFold}+ // Folding a finished turn's process is the default behavior now+ // (graduated from Labs) — always on for the conversation.+ defaultWorkflowExpandLevel={defaultWorkflowExpandLevel}id={id}isLatestItem={isLatestItem}messageIndex={index}diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex e8c108c302a..eb30665098b 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -775,6 +775,14 @@ export const verifyKeys = {'verify:acceptanceBundle',acceptanceId,]),+ acceptanceBySubject: def(+ 'verify:acceptanceBySubject',+ (subjectType: string, subjectId: string) => [+ 'verify:acceptanceBySubject',+ subjectType,+ subjectId,+ ],+ ),acceptances: def('verify:acceptances', () => ['verify:acceptances']),criteria: def('verify:criteria', () => ['verify:criteria']),instruction: def('verify:instruction', (documentId: string) => [diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsxindex 30dc48a12cf..35aaafcc30a 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx@@ -3,14 +3,26 @@import { Icon } from '@lobehub/ui';import { cssVar } from 'antd-style';import dayjs from 'dayjs';-import { CalendarClockIcon, CheckIcon, ChevronRight, PlusIcon, TypeIcon } from 'lucide-react';+import {+ CalendarClockIcon,+ CheckIcon,+ ChevronRight,+ PlusIcon,+ TargetIcon,+ TypeIcon,+} from 'lucide-react';import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { message } from '@/components/AntdStaticMethods';import Action from '@/features/ChatInput/ActionBar/components/Action';import { type ActionDropdownMenuItems } from '@/features/ChatInput/ActionBar/components/ActionDropdown';import { useChatInputStore } from '@/features/ChatInput/store';import { useConversationStore } from '@/features/Conversation';+import { useGoalArmStore } from '@/features/Conversation/ChatInput/VerifyTray/goalArmStore';+import { openTopicGoalModal } from '@/features/Conversation/ChatInput/VerifyTray/useTopicChecklist';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { OFFSETS_IN_HOURS, resolveScheduleTime } from './scheduleTime';@@ -30,12 +42,16 @@ import { OFFSETS_IN_HOURS, resolveScheduleTime } from './scheduleTime';const HeteroPlus = memo(() => {const { t } = useTranslation('chat');const { t: tEditor } = useTranslation('editor');+ const { t: tVerify } = useTranslation('verify');const [open, setOpen] = useState(false);const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);const scheduledSendAt = useConversationStore((s) => s.scheduledSendAt);const setScheduledSendAt = useConversationStore((s) => s.setScheduledSendAt);+ const topicId = useConversationStore((s) => s.context.topicId);+ const agentId = useConversationStore((s) => s.context.agentId);+ const enableTopicAcceptance = useUserStore(labPreferSelectors.enableTopicAcceptance);const armSchedule = useCallback((hours: number) => {@@ -86,8 +102,40 @@ const HeteroPlus = memo(() => {onCheckedChange: (checked: boolean) => setShowTypoBar(checked),type: 'switch',},+ // Topic goal (lab): before a topic exists this *arms* the goal (the next+ // message becomes it); once a topic exists it opens the editor directly.+ ...(enableTopicAcceptance+ ? ([+ { type: 'divider' },+ {+ icon: TargetIcon,+ key: 'set-topic-goal',+ label: tVerify('acceptance.tray.menuSetGoal'),+ onClick: () => {+ setOpen(false);+ if (topicId) {+ void openTopicGoalModal(topicId);+ } else if (agentId) {+ useGoalArmStore.getState().arm(agentId);+ message.success(tVerify('acceptance.tray.goalArmed'));+ }+ },+ },+ ] as ActionDropdownMenuItems)+ : []),];- }, [t, tEditor, showTypoBar, setShowTypoBar, armSchedule, scheduledSendAt]);+ }, [+ t,+ tEditor,+ tVerify,+ showTypoBar,+ setShowTypoBar,+ armSchedule,+ scheduledSendAt,+ enableTopicAcceptance,+ agentId,+ topicId,+ ]);return (<Actiondiff --git a/src/routes/(main)/settings/advanced/index.test.tsx b/src/routes/(main)/settings/advanced/index.test.tsxindex c1f3eea051f..885a8580bd2 100644--- a/src/routes/(main)/settings/advanced/index.test.tsx+++ b/src/routes/(main)/settings/advanced/index.test.tsx@@ -142,4 +142,16 @@ describe('Advanced settings page', () => {expect(screen.queryByText('features.taskVerify.title')).toBeNull();});++ it('renders the topic acceptance (tray) lab toggle', () => {+ useUserStore.setState({+ isUserStateInit: true,+ setSettings: vi.fn(),+ updateLab: vi.fn(),+ });++ render(<Page />, { wrapper: createWrapper() });++ expect(screen.getByText('features.topicAcceptance.title')).toBeDefined();+ });});diff --git a/src/routes/(main)/settings/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsxindex c782ac2f525..ef6f33b2c78 100644--- a/src/routes/(main)/settings/advanced/index.tsx+++ b/src/routes/(main)/settings/advanced/index.tsx@@ -55,12 +55,12 @@ const Page = memo(() => {enableImessage,enableFleet,enableClaudeCodeSdk,- enableFoldFinishedTurn,enableMessageTextSelectionActions,enableOAuthApps,enableInAppBrowser,enableArtifactDeployment,enableBuiltinTerminal,+ enableTopicAcceptance,updateLab,] = useUserStore((s) => [preferenceSelectors.isPreferenceInit(s),@@ -70,12 +70,12 @@ const Page = memo(() => {labPreferSelectors.enableImessage(s),labPreferSelectors.enableFleet(s),labPreferSelectors.enableClaudeCodeSdk(s),- labPreferSelectors.enableFoldFinishedTurn(s),labPreferSelectors.enableMessageTextSelectionActions(s),labPreferSelectors.enableOAuthApps(s),labPreferSelectors.enableInAppBrowser(s),labPreferSelectors.enableArtifactDeployment(s),labPreferSelectors.enableBuiltinTerminal(s),+ labPreferSelectors.enableTopicAcceptance(s),s.updateLab,]);@@ -211,27 +211,27 @@ const Page = memo(() => {{children: (<Switch- checked={enableFoldFinishedTurn}+ checked={enableMessageTextSelectionActions}loading={!isPreferenceInit}- onChange={(checked) => updateLab({ enableFoldFinishedTurn: checked })}+ onChange={(checked) => updateLab({ enableMessageTextSelectionActions: checked })}/>),className: styles.labItem,- desc: tLabs('features.foldFinishedTurn.desc'),- label: tLabs('features.foldFinishedTurn.title'),+ desc: tLabs('features.messageTextSelectionActions.desc'),+ label: tLabs('features.messageTextSelectionActions.title'),minWidth: undefined,},{children: (<Switch- checked={enableMessageTextSelectionActions}+ checked={enableTopicAcceptance}loading={!isPreferenceInit}- onChange={(checked) => updateLab({ enableMessageTextSelectionActions: checked })}+ onChange={(checked) => updateLab({ enableTopicAcceptance: checked })}/>),className: styles.labItem,- desc: tLabs('features.messageTextSelectionActions.desc'),- label: tLabs('features.messageTextSelectionActions.title'),+ desc: tLabs('features.topicAcceptance.desc'),+ label: tLabs('features.topicAcceptance.title'),minWidth: undefined,},{diff --git a/src/services/verify.ts b/src/services/verify.tsindex b7ed6723f5a..098f8cc6c1a 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -1,6 +1,8 @@import type {+ AcceptanceChecklistItem,AcceptanceCheckReviewAction,AcceptanceReviewAnnotation,+ AcceptanceSubjectType,VerifierType,VerifyCheckItem,VerifyEvidence,@@ -141,6 +143,24 @@ export class VerifyService {getAcceptanceBundle = (id: string): Promise<AcceptanceBundle> =>lambdaClient.acceptance.getBundle.query({ id });+ /** The acceptance aggregate for a subject (topic/task/document), or null. */+ getAcceptanceBySubject = (subjectType: AcceptanceSubjectType, subjectId: string) =>+ lambdaClient.acceptance.getBySubject.query({ subjectId, subjectType });++ /** Persist a subject's standing acceptance checklist (topic tray). */+ saveAcceptanceChecklist = (+ subjectType: AcceptanceSubjectType,+ subjectId: string,+ checklist: AcceptanceChecklistItem[],+ ) => lambdaClient.acceptance.saveChecklist.mutate({ checklist, subjectId, subjectType });++ /** Set/update a subject's acceptance goal (the one-sentence outcome). */+ saveAcceptanceGoal = (+ subjectType: AcceptanceSubjectType,+ subjectId: string,+ requirement: string,+ ) => lambdaClient.acceptance.saveGoal.mutate({ requirement, subjectId, subjectType });+listAcceptances = (): Promise<AcceptanceListItem[]> => lambdaClient.acceptance.list.query();acceptDelivery = (id: string, comment?: string) =>diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex bfacb554b83..272e0a77eb5 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -15,8 +15,6 @@ export const labPreferSelectors = {s.preference.lab?.enableBuiltinTerminal ?? false,enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,enableFleet: (s: UserState): boolean => s.preference.lab?.enableFleet ?? false,- enableFoldFinishedTurn: (s: UserState): boolean =>- s.preference.lab?.enableFoldFinishedTurn ?? false,enableImessage: (s: UserState): boolean => s.preference.lab?.enableImessage ?? false,enableInAppBrowser: (s: UserState): boolean => s.preference.lab?.enableInAppBrowser ?? false,enableInputMarkdown: (s: UserState): boolean =>@@ -28,4 +26,6 @@ export const labPreferSelectors = {enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,enablePlatformAgent: (s: UserState): boolean => s.preference.lab?.enablePlatformAgent ?? false,enableTaskVerify: (s: UserState): boolean => s.preference.lab?.enableTaskVerify ?? false,+ enableTopicAcceptance: (s: UserState): boolean =>+ s.preference.lab?.enableTopicAcceptance ?? false,};