🤯 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(acceptance): the discussion, region notes and the reviewer's approval (#19348)
Arvin Xu45d944cc4c9d
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 5f56fd4174a..d8d01025d3e 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -79,6 +79,58 @@"acceptance.checks.rerunHint": "The same check ran in {{count}} rounds; the last round stands.","acceptance.checks.title": "Acceptance checks","acceptance.checks.viewTrace": "View verification run",+ "acceptance.comments.addReaction": "Add reaction",+ "acceptance.comments.approvalCount": "{{count}} reviewer(s) approved",+ "acceptance.comments.approve": "Approve this delivery",+ "acceptance.comments.approveAgain": "Approve this round",+ "acceptance.comments.approveDescription": "Your review opinion. It does not change the acceptance status — only the owner accepts the delivery.",+ "acceptance.comments.approveSummaryPlaceholder": "One-line summary (optional)",+ "acceptance.comments.approved": "Approved",+ "acceptance.comments.approvedAtRound": "Approved (round {{round}})",+ "acceptance.comments.approvedBy": "{{name}} approved this delivery",+ "acceptance.comments.approvedByAtRound": "{{name}} approved round {{round}}",+ "acceptance.comments.author.agent": "Agent",+ "acceptance.comments.author.deactivated": "Deactivated",+ "acceptance.comments.author.former": "Former member",+ "acceptance.comments.collapseThread": "Collapse",+ "acceptance.comments.commentEvidence": "Comment on a region",+ "acceptance.comments.commented": "commented {{time}}",+ "acceptance.comments.copyLink": "Copy link",+ "acceptance.comments.createFailed": "Failed to post the comment. Please try again.",+ "acceptance.comments.delete": "Delete",+ "acceptance.comments.deleteConfirm": "Delete this comment?",+ "acceptance.comments.deleteFailed": "Failed to delete the comment. Please try again.",+ "acceptance.comments.deleted": "This comment was deleted",+ "acceptance.comments.empty": "No discussion yet.",+ "acceptance.comments.evidenceFromRound": "Evidence from round {{round}} — replaced in a later round",+ "acceptance.comments.evidenceThisRound": "The evidence this check shows now",+ "acceptance.comments.historicalRegions": "{{count}} region note(s) on evidence a later round replaced",+ "acceptance.comments.linkCopied": "Link copied",+ "acceptance.comments.loadFailed": "Failed to load the discussion. Please refresh.",+ "acceptance.comments.moreActions": "More actions",+ "acceptance.comments.participants": "Participants",+ "acceptance.comments.placeholder": "Say something about this delivery…",+ "acceptance.comments.readOnly": "You can read the discussion; join the workspace to take part.",+ "acceptance.comments.region": "Region",+ "acceptance.comments.regionCount": "{{count}} region note(s)",+ "acceptance.comments.regionHint": "Drag a box on the image, then write your note.",+ "acceptance.comments.regionMissing": "Circle a region first.",+ "acceptance.comments.regionModalTitle": "Circle the spot you mean",+ "acceptance.comments.reopen": "Reopen",+ "acceptance.comments.reply": "Reply",+ "acceptance.comments.replyPlaceholder": "Reply…",+ "acceptance.comments.resolve": "Mark resolved",+ "acceptance.comments.resolvedSummary": "Resolved · {{name}} · {{count}} message(s)",+ "acceptance.comments.roundCompletedBy": "{{name}} completed round {{round}}",+ "acceptance.comments.roundContext": "Round {{round}}",+ "acceptance.comments.roundLanded": "Round {{round}} landed",+ "acceptance.comments.send": "Send",+ "acceptance.comments.title": "Discussion",+ "acceptance.comments.updateFailed": "Failed to update the comment. Please try again.",+ "acceptance.comments.withdraw": "Withdraw approval",+ "acceptance.comments.withdrawDescription": "You can withdraw or give this again at any time while the round is open — only where you land when the owner decides counts.",+ "acceptance.comments.youApproved": "You approved round {{round}}",+ "acceptance.comments.youApprovedNoRound": "You approved this delivery","acceptance.detail.suggestion": "Suggestion","acceptance.error.description": "Check your connection and try loading this acceptance again.","acceptance.error.title": "Unable to load acceptance",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex ebb5fba3c4b..e2cae820565 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -79,6 +79,58 @@"acceptance.checks.rerunHint": "同一检查项在 {{count}} 轮各验证一次,以最后一轮为准","acceptance.checks.title": "验收检查清单","acceptance.checks.viewTrace": "查看验证过程",+ "acceptance.comments.addReaction": "添加表情",+ "acceptance.comments.approvalCount": "{{count}} 位评审已接受",+ "acceptance.comments.approve": "表达接受交付",+ "acceptance.comments.approveAgain": "表达接受本轮",+ "acceptance.comments.approveDescription": "这是你的评审意见,不会改变验收状态;只有发起人能接受交付。",+ "acceptance.comments.approveSummaryPlaceholder": "一句话总结(可选)",+ "acceptance.comments.approved": "已接受",+ "acceptance.comments.approvedAtRound": "已接受(第 {{round}} 轮)",+ "acceptance.comments.approvedBy": "{{name}} 表达了接受",+ "acceptance.comments.approvedByAtRound": "{{name}} 接受了第 {{round}} 轮",+ "acceptance.comments.author.agent": "智能体",+ "acceptance.comments.author.deactivated": "已注销",+ "acceptance.comments.author.former": "已离开",+ "acceptance.comments.collapseThread": "收起",+ "acceptance.comments.commentEvidence": "圈选评论",+ "acceptance.comments.commented": "评论于 {{time}}",+ "acceptance.comments.copyLink": "复制链接",+ "acceptance.comments.createFailed": "评论发送失败,请重试。",+ "acceptance.comments.delete": "删除",+ "acceptance.comments.deleteConfirm": "删除这条评论?",+ "acceptance.comments.deleteFailed": "评论删除失败,请重试。",+ "acceptance.comments.deleted": "该评论已删除",+ "acceptance.comments.empty": "还没有讨论。",+ "acceptance.comments.evidenceFromRound": "第 {{round}} 轮的证据,后续轮次已替换",+ "acceptance.comments.evidenceThisRound": "该检查项当前展示的证据",+ "acceptance.comments.historicalRegions": "{{count}} 条圈选评论指向已被后续轮次替换的证据",+ "acceptance.comments.linkCopied": "链接已复制",+ "acceptance.comments.loadFailed": "讨论加载失败,请刷新重试。",+ "acceptance.comments.moreActions": "更多操作",+ "acceptance.comments.participants": "参与者",+ "acceptance.comments.placeholder": "对整次交付说点什么…",+ "acceptance.comments.readOnly": "你可以查看讨论,加入这个 workspace 后才能参与。",+ "acceptance.comments.region": "圈选",+ "acceptance.comments.regionCount": "{{count}} 条圈选",+ "acceptance.comments.regionHint": "在图上拖一个框,然后写下你的意见。",+ "acceptance.comments.regionMissing": "先在图上圈出一处。",+ "acceptance.comments.regionModalTitle": "在截图上圈出要说的位置",+ "acceptance.comments.reopen": "重新打开",+ "acceptance.comments.reply": "回复",+ "acceptance.comments.replyPlaceholder": "回复…",+ "acceptance.comments.resolve": "标记为已解决",+ "acceptance.comments.resolvedSummary": "已解决 · {{name}} · {{count}} 条",+ "acceptance.comments.roundCompletedBy": "{{name}} 已完成第 {{round}} 轮",+ "acceptance.comments.roundContext": "第 {{round}} 轮",+ "acceptance.comments.roundLanded": "第 {{round}} 轮已完成",+ "acceptance.comments.send": "发送",+ "acceptance.comments.title": "讨论",+ "acceptance.comments.updateFailed": "评论更新失败,请重试。",+ "acceptance.comments.withdraw": "撤回接受",+ "acceptance.comments.withdrawDescription": "本轮期间随时可以撤回或再次表达,最后停在哪个状态才算数。",+ "acceptance.comments.youApproved": "你已在第 {{round}} 轮表达接受",+ "acceptance.comments.youApprovedNoRound": "你已表达接受","acceptance.detail.suggestion": "建议","acceptance.error.description": "请检查网络连接后重试。","acceptance.error.title": "无法加载验收信息",diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 49b696cbe13..7f2820e8fa6 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -179,6 +179,62 @@ export default {'acceptance.detail.suggestion': 'Suggestion','acceptance.error.description': 'Check your connection and try loading this acceptance again.','acceptance.error.title': 'Unable to load acceptance',+ 'acceptance.comments.title': 'Discussion',+ 'acceptance.comments.moreActions': 'More actions',+ 'acceptance.comments.placeholder': 'Say something about this delivery…',+ 'acceptance.comments.replyPlaceholder': 'Reply…',+ 'acceptance.comments.send': 'Send',+ 'acceptance.comments.reply': 'Reply',+ 'acceptance.comments.addReaction': 'Add reaction',+ 'acceptance.comments.resolve': 'Mark resolved',+ 'acceptance.comments.reopen': 'Reopen',+ 'acceptance.comments.resolvedSummary': 'Resolved · {{name}} · {{count}} message(s)',+ 'acceptance.comments.collapseThread': 'Collapse',+ 'acceptance.comments.commented': 'commented {{time}}',+ 'acceptance.comments.copyLink': 'Copy link',+ 'acceptance.comments.linkCopied': 'Link copied',+ 'acceptance.comments.delete': 'Delete',+ 'acceptance.comments.deleteConfirm': 'Delete this comment?',+ 'acceptance.comments.deleted': 'This comment was deleted',+ 'acceptance.comments.evidenceFromRound':+ 'Evidence from round {{round}} — replaced in a later round',+ 'acceptance.comments.evidenceThisRound': 'The evidence this check shows now',+ 'acceptance.comments.roundLanded': 'Round {{round}} landed',+ 'acceptance.comments.roundCompletedBy': '{{name}} completed round {{round}}',+ 'acceptance.comments.approvedBy': '{{name}} approved this delivery',+ 'acceptance.comments.approvedByAtRound': '{{name}} approved round {{round}}',+ 'acceptance.comments.historicalRegions':+ '{{count}} region note(s) on evidence a later round replaced',+ 'acceptance.comments.empty': 'No discussion yet.',+ 'acceptance.comments.readOnly': 'You can read the discussion; join the workspace to take part.',+ 'acceptance.comments.region': 'Region',+ 'acceptance.comments.roundContext': 'Round {{round}}',+ 'acceptance.comments.commentEvidence': 'Comment on a region',+ 'acceptance.comments.regionModalTitle': 'Circle the spot you mean',+ 'acceptance.comments.regionHint': 'Drag a box on the image, then write your note.',+ 'acceptance.comments.regionMissing': 'Circle a region first.',+ 'acceptance.comments.regionCount': '{{count}} region note(s)',+ 'acceptance.comments.approve': 'Approve this delivery',+ 'acceptance.comments.approveDescription':+ 'Your review opinion. It does not change the acceptance status — only the owner accepts the delivery.',+ 'acceptance.comments.approveSummaryPlaceholder': 'One-line summary (optional)',+ 'acceptance.comments.withdraw': 'Withdraw approval',+ 'acceptance.comments.withdrawDescription':+ 'You can withdraw or give this again at any time while the round is open — only where you land when the owner decides counts.',+ 'acceptance.comments.approveAgain': 'Approve this round',+ 'acceptance.comments.approved': 'Approved',+ 'acceptance.comments.approvedAtRound': 'Approved (round {{round}})',+ 'acceptance.comments.youApproved': 'You approved round {{round}}',+ 'acceptance.comments.youApprovedNoRound': 'You approved this delivery',+ 'acceptance.comments.approvalCount': '{{count}} reviewer(s) approved',+ 'acceptance.comments.participants': 'Participants',+ 'acceptance.comments.author.agent': 'Agent',+ 'acceptance.comments.author.former': 'Former member',+ 'acceptance.comments.author.deactivated': 'Deactivated',+ 'acceptance.comments.loadFailed': 'Failed to load the discussion. Please refresh.',+ 'acceptance.comments.createFailed': 'Failed to post the comment. Please try again.',+ 'acceptance.comments.deleteFailed': 'Failed to delete the comment. Please try again.',+ 'acceptance.comments.updateFailed': 'Failed to update the comment. Please try again.','acceptance.evidence.empty':'No evidence artifacts were submitted for this check in this round — only the verifier’s recorded observation.','acceptance.evidence.audio': '{{count}} audio evidence item(s)',diff --git a/src/features/Acceptance/Viewer/AcceptanceOverview.tsx b/src/features/Acceptance/Viewer/AcceptanceOverview.tsxindex 74dfe98002a..6eee23c7a52 100644--- a/src/features/Acceptance/Viewer/AcceptanceOverview.tsx+++ b/src/features/Acceptance/Viewer/AcceptanceOverview.tsx@@ -3,10 +3,16 @@import { Flexbox } from '@lobehub/ui';import { createStaticStyles, cssVar, useResponsive } from 'antd-style';import { useState } from 'react';+import { useLocation } from 'react-router';import { useAcceptanceScope } from './AcceptanceScope';import AcceptanceCheckInventory from './Checks/AcceptanceCheckInventory';import AcceptanceCheckOwnerToolbar from './Checks/AcceptanceCheckOwnerToolbar';+import AcceptanceDiscussion from './Comments/AcceptanceDiscussion';+import { commentIdFromHash } from './Comments/anchor';+import { messageThreads } from './Comments/discussionTimeline';+import { useAcceptanceComments } from './Comments/hooks';+import ReviewerApprovalBar from './Comments/ReviewerApprovalBar';import AcceptanceOriginTopic from './Conversation/AcceptanceOriginTopic';import AcceptanceResources from './Evidence/AcceptanceResources';import { AcceptanceFlow } from './Flow/AcceptanceFlow';@@ -59,10 +65,14 @@ export const AcceptanceOverview = ({const { acceptanceId, embedded } = useAcceptanceScope();const { turn } = useAcceptanceTurn(embedded);const { data } = useAcceptanceBundle(acceptanceId);+ const { threads } = useAcceptanceComments(acceptanceId);const [requestedTab, setTab] = useState<AcceptanceTabKey>();+ // A link to one comment has to land on the tab that shows it. The reader can+ // still leave: their own tab choice, once made, outranks the fragment.+ const { hash } = useLocation();const flowCount = getFlowNodeCount(data?.flows);const tab = resolveAcceptanceTab(- requestedTab,+ requestedTab ?? (!embedded && commentIdFromHash(hash) ? 'discussion' : undefined),flowCount,Boolean(flowPlanPhase(data?.rounds.at(-1))),md,@@ -94,6 +104,7 @@ export const AcceptanceOverview = ({<AcceptanceTabsactive={tab}checkCount={checks.length}+ discussionCount={messageThreads(threads).length}flowCount={md ? flowCount : 0}resourceCount={resourceCount}onChange={setTab}@@ -108,7 +119,15 @@ export const AcceptanceOverview = ({paddingBlock={20}style={tab === 'flow' ? { maxWidth: 1500 } : undefined}>- {tab === 'flow' ? (+ {/* Deciding belongs where the evidence is. The discussion is a+ conversation; ending one there put the closing act under a thread+ that says nothing about whether the checks passed. Both faces of+ the act move together — the owner's decision bar and the+ reviewer's "fine by me" — or a reviewer would lose the affordance+ entirely. */}+ {tab === 'discussion' ? (+ <AcceptanceDiscussion />+ ) : tab === 'flow' ? (<><AcceptanceFlow /><AcceptanceDecision onDraftToComposer={onDraftToComposer} />@@ -116,6 +135,7 @@ export const AcceptanceOverview = ({) : tab === 'checks' ? (<><AcceptanceCheckInventory toolbar={<AcceptanceCheckOwnerToolbar />} />+ <ReviewerApprovalBar /><AcceptanceDecision onDraftToComposer={onDraftToComposer} /></>) : (diff --git a/src/features/Acceptance/Viewer/AcceptanceScope.tsx b/src/features/Acceptance/Viewer/AcceptanceScope.tsxindex 73ed6a38661..7122e371b40 100644--- a/src/features/Acceptance/Viewer/AcceptanceScope.tsx+++ b/src/features/Acceptance/Viewer/AcceptanceScope.tsx@@ -22,6 +22,9 @@ export const useAcceptanceScope = () => {return scope;};+/** For leaves that may also render outside the viewer (no scope → no collaboration UI). */+export const useOptionalAcceptanceScope = () => use(AcceptanceScopeContext);+export const AcceptanceScope = ({acceptanceId,children,diff --git a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx b/src/features/Acceptance/Viewer/Checks/CheckRow.tsxindex e05376f1de5..2197f910cbb 100644--- a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx+++ b/src/features/Acceptance/Viewer/Checks/CheckRow.tsx@@ -1,6 +1,5 @@'use client';-import type { AcceptanceReviewAnnotation } from '@lobechat/types';import { copyToClipboard, Flexbox, Icon, TextArea, Tooltip } from '@lobehub/ui';import { ActionIcon, Button, Tag, Text } from '@lobehub/ui/base-ui';import { cssVar, cx, useResponsive } from 'antd-style';@@ -16,6 +15,7 @@ import {FileText,Film,Images,+ MessageSquare,MessageSquareX,Repeat,Route,@@ -26,12 +26,22 @@ import { useTranslation } from 'react-i18next';import { hasRenderableEvidence, readVisualizationManifest } from '../../Report/visualization';import { VisualizationDeltaBadge, VisualizationRenderer } from '../../Report/VisualizationRenderer';import { checkDisplayTitle } from '../../utils';+import { useOptionalAcceptanceScope } from '../AcceptanceScope';+import { acceptanceAuthorColor } from '../Comments/authorColor';+import { commentAuthorName } from '../Comments/CommentCard';+import CommentThread from '../Comments/CommentThread';+import { openEvidenceCommentModal } from '../Comments/EvidenceCommentModal';+import { useAcceptanceComments } from '../Comments/hooks';+import ThreadEvidence from '../Comments/ThreadEvidence';+import { threadsForCheck } from '../Comments/threads';import { evidenceCounts, hasAnnotatableEvidence, isAnnotatable } from '../Evidence/evidence';import { EvidenceList } from '../Evidence/EvidenceList';+import type { EvidenceOverlayMap } from '../Evidence/overlay';import { openCheckRejectModal } from '../Review/CheckRejectModal';import type { CheckProposal } from '../Review/proposal';import { classifyProposalEdit } from '../Review/proposal';import ProposalCard from '../Review/ProposalCard';+import { useAcceptanceBundle } from '../useAcceptanceBundle';import {AcceptedNote,collectEvidenceById,@@ -124,10 +134,7 @@ export const AcceptanceCheckRow = memo<{// open — boxes with no visible explanation read as a defect of the evidence.const proposalOverlays = useMemo(() => {if (!proposalOpen || !check.prediction) return undefined;- const map = new Map<- string,- { comment?: string; label?: number; rect: AcceptanceReviewAnnotation['rect'] }[]- >();+ const map: EvidenceOverlayMap = new Map();(check.prediction.annotations ?? []).forEach((annotation, index) => {const bucket = map.get(annotation.evidenceId) ?? [];bucket.push({ comment: annotation.comment, label: index + 1, rect: annotation.rect });@@ -137,6 +144,75 @@ export const AcceptanceCheckRow = memo<{}, [proposalOpen, check.prediction]);const hasHistory = check.revisions > 1 || historyReviews.length > 0;+ // Collaboration: threads circled on this check's evidence. Only inside the+ // viewer — the row also renders in hosts with no acceptance scope.+ const scope = useOptionalAcceptanceScope();+ const { data: bundle } = useAcceptanceBundle(scope?.acceptanceId ?? '');+ const comments = useAcceptanceComments(scope?.acceptanceId);+ const checkThreads = useMemo(+ () => threadsForCheck(comments.threads, check.id),+ [comments.threads, check.id],+ );+ const commentActions = {+ onDelete: comments.remove,+ onReply: (rootId: string, content: string, attachments: { fileId: string }[]) =>+ comments.create({+ attachments,+ clientId: `${rootId}:${Date.now()}`,+ content,+ contextRunId: bundle?.rounds.at(-1)?.run.id,+ parentCommentId: rootId,+ }),+ onResolve: comments.setResolved,+ };+ // A region whose evidence a later round replaced: the box has nothing left+ // to sit on, so the thread renders under the evidence with its own copy of+ // the picture instead of disappearing.+ const showsNow = new Set(check.evidence.map((item) => item.id));+ const staleThreads = checkThreads.filter(+ (thread) => thread.root.evidenceId && !showsNow.has(thread.root.evidenceId),+ );+ // Each reviewer's regions carry their own colour, so two people circling+ // the same screenshot never read as one person's notes; the marker on the+ // box opens that thread in full — replies and all.+ const commentOverlays = useMemo(() => {+ const map: EvidenceOverlayMap = new Map(proposalOverlays ?? []);+ checkThreads.forEach((thread, index) => {+ const { author, authorUserId, evidenceId, rect, content, deletedAt } = thread.root;+ if (!evidenceId || !rect || deletedAt) return;+ const bucket = map.get(evidenceId) ?? [];+ bucket.push({+ authorName: commentAuthorName(author),+ color: acceptanceAuthorColor(authorUserId),+ comment: content,+ label: index + 1,+ panel: (+ <CommentThread canComment={comments.canComment} thread={thread} {...commentActions} />+ ),+ rect,+ resolved: Boolean(thread.root.resolvedAt),+ });+ map.set(evidenceId, bucket);+ });+ return map.size > 0 ? map : undefined;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [proposalOverlays, checkThreads, comments.canComment]);+ const canCommentEvidence =+ comments.canComment && Boolean(check.result) && hasAnnotatableEvidence(check);+ const openEvidenceComment = () =>+ openEvidenceCommentModal({+ evidence: check.evidence,+ onConfirm: async ({ content, evidenceId, rect }) => {+ await comments.create({+ anchor: { checkItemId: check.id, evidenceId, rect },+ clientId: `${check.id}:${Date.now()}`,+ content,+ contextRunId: bundle?.rounds.at(-1)?.run.id,+ });+ return true;+ },+ });+/*** @param fromProposal - when set, the modal opens prefilled with the* model's note and regions, and the submitted result is diffed against it@@ -409,6 +485,21 @@ export const AcceptanceCheckRow = memo<{</Tooltip>) : null,)}+ {checkThreads.length > 0 && (+ <Tooltip+ title={t('acceptance.comments.regionCount', { count: checkThreads.length })}+ >+ <Flexbox+ horizontal+ align={'center'}+ gap={3}+ style={{ color: cssVar.colorTextTertiary, fontSize: 11 }}+ >+ <Icon icon={MessageSquare} size={13} />+ {checkThreads.length}+ </Flexbox>+ </Tooltip>+ )}{/* The iteration mark stays compact — [↻ N]; the words (verified Nrounds · introduced in round X) live in its tooltip. Clickingjumps to the round the concern first appeared in. */}@@ -520,9 +611,64 @@ export const AcceptanceCheckRow = memo<{{visualization && <VisualizationRenderer manifest={visualization} />}<EvidenceListevidence={check.evidence}- overlays={proposalOverlays}+ overlays={commentOverlays}onReviewEvidence={canReview ? (id) => openReject(undefined, id) : undefined}/>+ {staleThreads.length > 0 && (+ <Flexbox className={styles.staleRegions} gap={10}>+ <Text fontSize={12} type={'secondary'}>+ {t('acceptance.comments.historicalRegions', { count: staleThreads.length })}+ </Text>+ {staleThreads.map((thread) => {+ const evidence = thread.root.evidenceId+ ? evidenceById.get(thread.root.evidenceId)+ : undefined;+ return (+ <Flexbox+ horizontal+ align={'flex-start'}+ gap={12}+ key={thread.root.id}+ wrap={'wrap'}+ >+ {evidence && (+ <ThreadEvidence+ stale+ comment={thread.root}+ evidence={evidence}+ roundIndex={+ check.timeline.find((entry) =>+ entry.evidence.some((item) => item.id === thread.root.evidenceId),+ )?.roundIndex+ }+ />+ )}+ <Flexbox flex={1} style={{ minWidth: 200 }}>+ <CommentThread+ canComment={comments.canComment}+ thread={thread}+ {...commentActions}+ />+ </Flexbox>+ </Flexbox>+ );+ })}+ </Flexbox>+ )}+ {canCommentEvidence && (+ <Button+ outdent+ icon={<Icon icon={MessageSquare} />}+ style={{ alignSelf: 'flex-start' }}+ type={'text'}+ onClick={(event) => {+ event.stopPropagation();+ openEvidenceComment();+ }}+ >+ {t('acceptance.comments.commentEvidence')}+ </Button>+ )}{check.state === 'not_executed' && (<Flexboxdiff --git a/src/features/Acceptance/Viewer/Checks/styles.ts b/src/features/Acceptance/Viewer/Checks/styles.tsindex 257a5e12dc5..b0e9bf1fce9 100644--- a/src/features/Acceptance/Viewer/Checks/styles.ts+++ b/src/features/Acceptance/Viewer/Checks/styles.ts@@ -1,6 +1,23 @@import { createStaticStyles, cssVar } from 'antd-style';export const styles = createStaticStyles(({ css }) => ({+ /**+ * Regions whose evidence a later round replaced. Kept quiet on purpose: it is+ * a footnote to the check, not a second checklist — full-strength cards here+ * competed with the evidence the reader actually came for.+ */+ staleRegions: css`+ margin-block-start: 4px;+ padding-block: 10px;+ padding-inline-start: 12px;+ border-inline-start: 2px solid ${cssVar.colorBorderSecondary};++ opacity: 0.75;++ &:hover {+ opacity: 1;+ }+ `,chip: css`padding-inline: 6px;border-radius: 4px;diff --git a/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx b/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsxnew file mode 100644index 00000000000..ae8ce90ba42--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx@@ -0,0 +1,279 @@+'use client';++import type { AcceptanceCommentItem } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { BadgeCheck, GitCommitHorizontal } from 'lucide-react';+import { nanoid } from 'nanoid';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useActivityTime } from '@/hooks/useActivityTime';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import { useAcceptanceScope } from '../AcceptanceScope';+import { useAcceptanceBundle } from '../useAcceptanceBundle';+import { commentAnchorId, useCommentAnchor } from './anchor';+import CommentCard, { commentAuthorName, CommentAvatar } from './CommentCard';+import CommentComposer from './CommentComposer';+import type { DiscussionEntry } from './discussionTimeline';+import { buildDiscussionTimeline } from './discussionTimeline';+import { useAcceptanceComments } from './hooks';+import { styles, TIMELINE_NODE } from './styles';++/** Enough room to start writing without the box dominating the column. */+const COMPOSER_MIN_HEIGHT = 80;++const local = createStaticStyles(({ css }) => ({+ empty: css`+ padding-block: 16px;+ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ `,+}));++/** A round landing or an approval — a dot on the rail and one line of text. */+const TimelineEvent = memo<{ at: Date; icon: typeof BadgeCheck; text: string }>(+ ({ at, icon, text }) => {+ const time = useActivityTime(at);+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.timelineEntry, styles.eventEntry)}+ gap={12}+ >+ <span className={styles.eventDot}>+ <Icon icon={icon} size={12} />+ </span>+ <Flexbox horizontal align={'center'} className={styles.event} gap={8} wrap={'wrap'}>+ <span>{text}</span>+ <span className={styles.meta} title={time.title}>+ {time.text}+ </span>+ </Flexbox>+ </Flexbox>+ );+ },+);++TimelineEvent.displayName = 'AcceptanceTimelineEvent';++/**+ * A round. With a note it IS the agent's turn: one entry whose header says+ * "<agent> completed round N" and whose body is what they wrote. The landing+ * and the author are the same sentence, so neither an event row above the note+ * nor a second author line is needed. Without a note it stays the plain event.+ */+const TimelineRound = memo<{+ anchored?: boolean;+ at: Date;+ onReact: (id: string, emoji: string, on: boolean) => Promise<void>;+ proposal?: AcceptanceCommentItem;+ reactable: boolean;+ roundIndex: number;+}>(({ anchored, at, onReact, proposal, reactable, roundIndex }) => {+ const { t } = useTranslation('verify');+ if (!proposal)+ return (+ <TimelineEvent+ at={at}+ icon={GitCommitHorizontal}+ text={t('acceptance.comments.roundLanded', { round: roundIndex })}+ />+ );+ return (+ <Flexbox+ horizontal+ align={'flex-start'}+ className={styles.timelineEntry}+ gap={12}+ id={commentAnchorId(proposal.id)}+ >+ <span className={styles.timelineNode}>+ <CommentAvatar comment={proposal} size={TIMELINE_NODE} />+ </span>+ <Flexbox className={cx(styles.box, anchored && styles.boxAnchored)}>+ <CommentCard+ anchored+ comment={proposal}+ reactable={reactable}+ nameOverride={t('acceptance.comments.roundCompletedBy', {+ name: commentAuthorName(proposal.author),+ round: roundIndex,+ })}+ onReact={onReact}+ />+ </Flexbox>+ </Flexbox>+ );+});++TimelineRound.displayName = 'AcceptanceTimelineRound';++/** One chat message: the author's face on the rail, the remark beside it. */+const TimelineMessage = memo<{+ anchored: boolean;+ comment: AcceptanceCommentItem;+ onDelete: (id: string) => Promise<void>;+ onReact: (id: string, emoji: string, on: boolean) => Promise<void>;+ reactable: boolean;+ /** Written by whoever is reading — GitHub paints their own turns blue. */+ self: boolean;+}>(({ anchored, comment, onDelete, onReact, reactable, self }) => (+ <Flexbox+ horizontal+ align={'flex-start'}+ className={styles.timelineEntry}+ gap={12}+ id={commentAnchorId(comment.id)}+ >+ <span className={styles.timelineNode}>+ <CommentAvatar comment={comment} size={TIMELINE_NODE} />+ </span>+ <Flexbox className={cx(styles.box, self && styles.boxSelf, anchored && styles.boxAnchored)}>+ <CommentCard+ anchored+ comment={comment}+ reactable={reactable}+ onDelete={onDelete}+ onReact={onReact}+ />+ </Flexbox>+ </Flexbox>+));++TimelineMessage.displayName = 'AcceptanceTimelineMessage';++/*+ * The rail runs inside the boxes rather than under the avatars, so nothing here+ * needs to sit above the line: the opaque boxes cover it, the event dots stand+ * on it, and the gaps between turns are where it shows.+ */++/**+ * The delivery's chat: one message per turn, strung on a rail with the rounds+ * that landed and the approvals people gave, and the composer at the end.+ *+ * Only chat lives here. A note circled on a screenshot reads next to that spot+ * and nowhere else, so it stays on the check that owns the evidence — which is+ * also why nothing here offers "reply" or "resolve": those belong to a note+ * about a place, not to a remark in a conversation.+ */+const AcceptanceDiscussion = memo(() => {+ const { t } = useTranslation('verify');+ const { acceptanceId, embedded } = useAcceptanceScope();+ const viewerId = useUserStore(userProfileSelectors.userId);+ const { data } = useAcceptanceBundle(acceptanceId);+ const { canComment, create, error, isLoading, items, react, remove, threads } =+ useAcceptanceComments(acceptanceId);++ const currentRunId = data?.rounds.at(-1)?.run.id;+ const anchoredId = useCommentAnchor(items, embedded);++ const timeline = useMemo(+ () =>+ buildDiscussionTimeline({+ approvals: items.filter((item) => item.kind === 'approval'),+ items,+ rounds: (data?.rounds ?? []).map(({ run }) => ({+ createdAt: run.createdAt,+ id: run.id,+ roundIndex: run.roundIndex,+ })),+ threads,+ }),+ [data?.rounds, items, threads],+ );++ if (isLoading && timeline.length === 0 && !canComment) return null;++ const renderEntry = (entry: DiscussionEntry) => {+ if (entry.kind === 'round')+ return (+ <TimelineRound+ anchored={Boolean(entry.proposal) && entry.proposal?.id === anchoredId}+ at={entry.at}+ key={`round-${entry.roundIndex}`}+ proposal={entry.proposal}+ reactable={canComment}+ roundIndex={entry.roundIndex}+ onReact={react}+ />+ );+ if (entry.kind === 'approval') {+ const who =+ entry.approval.contextRoundIndex === null+ ? t('acceptance.comments.approvedBy', {+ name: commentAuthorName(entry.approval.author),+ })+ : t('acceptance.comments.approvedByAtRound', {+ name: commentAuthorName(entry.approval.author),+ round: entry.approval.contextRoundIndex,+ });+ // The reviewer's optional one-line summary. Written into the same row and+ // read nowhere else, so it belongs on the line that announces it — a+ // field nobody can read back is worse than no field.+ const said = entry.approval.content.trim();+ return (+ <TimelineEvent+ at={entry.at}+ icon={BadgeCheck}+ key={entry.approval.id}+ text={said ? `${who} · ${said}` : who}+ />+ );+ }+ return (+ <TimelineMessage+ anchored={entry.comment.id === anchoredId}+ comment={entry.comment}+ key={entry.comment.id}+ reactable={canComment}+ self={Boolean(viewerId) && entry.comment.authorUserId === viewerId}+ onDelete={remove}+ onReact={react}+ />+ );+ };++ return (+ <Flexbox>+ {timeline.length === 0 && (+ <span className={local.empty}>{t('acceptance.comments.empty')}</span>+ )}+ {timeline.map((entry) => renderEntry(entry))}++ {/* Last, like GitHub's Conversation: you read the thread, then answer it. */}+ {canComment ? (+ <Flexbox className={cx(styles.timelineEntry, styles.nodelessEntry, styles.tailEntry)}>+ <Flexbox className={styles.composerBlock}>+ <CommentComposer+ minHeight={COMPOSER_MIN_HEIGHT}+ placeholder={t('acceptance.comments.placeholder')}+ onSubmit={(content, attachments) =>+ create({+ attachments,+ clientId: nanoid(),+ content,+ contextRunId: currentRunId,+ })+ }+ />+ </Flexbox>+ </Flexbox>+ ) : (+ <Text fontSize={13} type={'secondary'}>+ {/* A read that failed says nothing about permission. */}+ {error ? t('acceptance.comments.loadFailed') : t('acceptance.comments.readOnly')}+ </Text>+ )}+ </Flexbox>+ );+});++AcceptanceDiscussion.displayName = 'AcceptanceDiscussion';++export default AcceptanceDiscussion;diff --git a/src/features/Acceptance/Viewer/Comments/CommentCard.tsx b/src/features/Acceptance/Viewer/Comments/CommentCard.tsxnew file mode 100644index 00000000000..b3e1c80b79e--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/CommentCard.tsx@@ -0,0 +1,205 @@+'use client';++import type { AcceptanceCommentItem } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import type { DropdownItem } from '@lobehub/ui/base-ui';+import {+ ActionIcon,+ Avatar,+ confirmModal,+ DropdownMenu,+ Tag,+ Text,+ toast,+} from '@lobehub/ui/base-ui';+import { Link2, MoreHorizontal, Trash2 } from 'lucide-react';+import { memo, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActivityTime } from '@/hooks/useActivityTime';++import { AttachmentThumbs } from '../Evidence/attachments';+import { commentAnchorUrl } from './anchor';+import CommentReactions from './CommentReactions';+import { styles } from './styles';++export const commentAuthorName = (author: AcceptanceCommentItem['author']) =>+ author.fullName || author.username || '—';++/**+ * The author's face, plain. No ring: colour identifies the marks someone drew+ * on the evidence, and wrapping it around their avatar here said nothing while+ * making a quiet list look decorated.+ *+ * With no picture the fallback draws the name as text, and a two-character CJK+ * name wraps inside a small circle — so only the first character is handed over.+ */+export const CommentAvatar = memo<{ comment: AcceptanceCommentItem; size?: number }>(+ ({ comment, size = 20 }) => {+ const name = commentAuthorName(comment.author);+ return <Avatar avatar={comment.author.avatar || name.slice(0, 1)} size={size} />;+ },+);++CommentAvatar.displayName = 'AcceptanceCommentAvatar';++interface CommentCardProps {+ /** Present where the row is addressable — enables "copy link" in the menu. */+ anchored?: boolean;+ /** Rendered after the author line — anchor chip, round tag, resolved tag. */+ badges?: ReactNode;+ comment: AcceptanceCommentItem;+ /**+ * Replaces the author line for a row that is not a remark. A round's note+ * says "<agent> completed round N" — the landing and who did it in one line,+ * instead of an event row above a message that repeats the author.+ */+ nameOverride?: string;+ onDelete?: (id: string) => Promise<void>;+ /** Absent where reactions do not belong: a region note is a working thread. */+ onReact?: (id: string, emoji: string, on: boolean) => Promise<void>;+ /** True where the reader may write; the chips render for everyone else too. */+ reactable?: boolean;+ /**+ * `boxed` is the discussion message: a header strip over the body.+ * `plain` is the floating note: the same content with no frame of its own.+ */+ variant?: 'boxed' | 'plain';+}++/** One remark: who, when, what — and the author's own actions behind a menu. */+const CommentCard = memo<CommentCardProps>(+ ({+ anchored,+ badges,+ comment,+ nameOverride,+ onDelete,+ onReact,+ reactable,+ variant = 'boxed',+ }) => {+ const { t } = useTranslation('verify');+ const time = useActivityTime(comment.createdAt);+ const [deleting, setDeleting] = useState(false);+ const name = nameOverride ?? commentAuthorName(comment.author);++ const menuItems: DropdownItem[] = [+ ...(anchored+ ? [+ {+ icon: <Icon icon={Link2} />,+ key: 'copy-link',+ label: t('acceptance.comments.copyLink'),+ onClick: async () => {+ try {+ await navigator.clipboard.writeText(commentAnchorUrl(comment.id));+ toast.success(t('acceptance.comments.linkCopied'));+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.updateFailed'));+ }+ },+ } satisfies DropdownItem,+ ]+ : []),+ ...(comment.canDelete && onDelete+ ? [+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'delete',+ label: t('acceptance.comments.delete'),+ onClick: () =>+ confirmModal({+ content: t('acceptance.comments.deleteConfirm'),+ okButtonProps: { danger: true },+ okText: t('acceptance.comments.delete'),+ onOk: async () => {+ setDeleting(true);+ try {+ await onDelete(comment.id);+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.deleteFailed'));+ } finally {+ setDeleting(false);+ }+ },+ }),+ } satisfies DropdownItem,+ ]+ : []),+ ];++ return (+ <>+ <Flexbox+ horizontal+ align={'center'}+ className={variant === 'boxed' ? styles.boxHeader : undefined}+ gap={8}+ wrap={'wrap'}+ >+ {variant === 'plain' && <CommentAvatar comment={comment} size={18} />}+ <Text+ className={nameOverride ? styles.headline : styles.authorName}+ fontSize={13}+ weight={600}+ >+ {name}+ </Text>+ {comment.author.type === 'agent' && (+ <Tag size={'small'}>{t('acceptance.comments.author.agent')}</Tag>+ )}+ {comment.author.status !== 'active' && (+ <Tag size={'small'}>{t(`acceptance.comments.author.${comment.author.status}`)}</Tag>+ )}+ <span className={styles.meta} title={time.title}>+ {nameOverride ? time.text : t('acceptance.comments.commented', { time: time.text })}+ </span>+ {badges}+ {menuItems.length > 0 && (+ <div data-comment-actions className={styles.rowActions}>+ <DropdownMenu+ items={menuItems}+ placement={'bottomRight'}+ popupProps={{ style: { minWidth: 140 } }}+ >+ <ActionIcon+ icon={MoreHorizontal}+ loading={deleting}+ size={'small'}+ title={t('acceptance.comments.moreActions')}+ />+ </DropdownMenu>+ </div>+ )}+ </Flexbox>+ <div className={variant === 'boxed' ? styles.body : styles.panelBody}>+ {comment.deletedAt ? (+ <span className={styles.deleted}>{t('acceptance.comments.deleted')}</span>+ ) : (+ comment.content+ )}+ {/* Exhibits, under the words rather than inside them. */}+ {comment.attachments.length > 0 && (+ <div className={styles.attachments}>+ <AttachmentThumbs attachments={comment.attachments} />+ </div>+ )}+ {onReact && (+ <CommentReactions+ reactions={comment.reactions}+ onReact={reactable ? (emoji, on) => onReact(comment.id, emoji, on) : undefined}+ />+ )}+ </div>+ </>+ );+ },+);++CommentCard.displayName = 'AcceptanceCommentCard';++export default CommentCard;diff --git a/src/features/Acceptance/Viewer/Comments/CommentComposer.tsx b/src/features/Acceptance/Viewer/Comments/CommentComposer.tsxnew file mode 100644index 00000000000..2514e11c147--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/CommentComposer.tsx@@ -0,0 +1,140 @@+'use client';++import { Flexbox, TextArea } from '@lobehub/ui';+import { Button, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import type { CSSProperties } from 'react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import {+ AttachmentStrip,+ AttachmentUploadButton,+ useFeedbackAttachments,+} from '../Evidence/attachments';++/**+ * `autoSize` writes its own inline height onto the textarea, so a floor has to+ * reach the element itself — a `style` on the component lands on the wrapper.+ */+const styles = createStaticStyles(({ css }) => ({+ tall: css`+ & textarea {+ /* The control ships its own min-height; this floor has to outrank it. */+ min-height: var(--acceptance-composer-min-height) !important;+ }+ `,+}));++/** Room for a couple of screenshots without turning a remark into an album. */+const MAX_COMMENT_ATTACHMENTS = 4;++interface CommentComposerProps {+ autoFocus?: boolean;+ /** One-line reply box instead of the two-line root box. */+ compact?: boolean;+ /**+ * Floor for the writing area. The delivery-wide box gets a generous one: a+ * two-line field invites a two-word answer, and this is where the round's+ * real objection gets written.+ */+ minHeight?: number;+ onCancel?: () => void;+ /** Resolve when the comment is persisted; the box clears on success. */+ onSubmit: (content: string, attachments: { fileId: string }[]) => Promise<void>;+ placeholder: string;+ submitLabel?: string;+}++/**+ * A plain-text box with a send button and room for screenshots. Comments here+ * are short remarks between two people looking at the same evidence, and the+ * commonest one is "here is what I see instead" — so a picture is a first-class+ * part of the remark rather than something pasted into the prose. ⌘/Ctrl+Enter+ * sends.+ */+const CommentComposer = memo<CommentComposerProps>(+ ({ autoFocus, compact, minHeight, onCancel, onSubmit, placeholder, submitLabel }) => {+ const { t } = useTranslation('verify');+ const [value, setValue] = useState('');+ const [sending, setSending] = useState(false);+ const { attachments, fileIds, handlePaste, remove, uploadFiles, uploading } =+ useFeedbackAttachments(MAX_COMMENT_ATTACHMENTS);+ const trimmed = value.trim();+ // A screenshot on its own is a complete remark.+ const canSend = (trimmed.length > 0 || fileIds.length > 0) && !uploading;++ const submit = async () => {+ if (!canSend || sending) return;+ setSending(true);+ try {+ await onSubmit(+ trimmed,+ fileIds.map((fileId) => ({ fileId })),+ );+ setValue('');+ for (const id of fileIds) remove(id);+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.createFailed'));+ } finally {+ setSending(false);+ }+ };++ return (+ <Flexbox+ className={minHeight ? styles.tall : undefined}+ gap={8}+ style={+ minHeight+ ? ({ '--acceptance-composer-min-height': `${minHeight}px` } as CSSProperties)+ : undefined+ }+ >+ <TextArea+ autoFocus={autoFocus}+ autoSize={{ maxRows: 20, minRows: compact ? 1 : 2 }}+ placeholder={placeholder}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onPaste={handlePaste}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ void submit();+ }+ }}+ />+ <AttachmentStrip+ attachments={attachments}+ disabled={sending}+ uploading={uploading}+ onRemove={remove}+ />+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>+ <AttachmentUploadButton disabled={sending} onFiles={uploadFiles} />+ <Flexbox flex={1} />+ {onCancel && (+ <Button size={'small'} type={'text'} onClick={onCancel}>+ {t('cancel', { ns: 'common' })}+ </Button>+ )}+ <Button+ disabled={!canSend}+ loading={sending}+ size={'small'}+ type={'primary'}+ onClick={() => void submit()}+ >+ {submitLabel ?? t('acceptance.comments.send')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ },+);++CommentComposer.displayName = 'AcceptanceCommentComposer';++export default CommentComposer;diff --git a/src/features/Acceptance/Viewer/Comments/CommentReactions.tsx b/src/features/Acceptance/Viewer/Comments/CommentReactions.tsxnew file mode 100644index 00000000000..88e7590c128--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/CommentReactions.tsx@@ -0,0 +1,228 @@+'use client';++import data from '@emoji-mart/data';+import Picker from '@emoji-mart/react';+import type { AcceptanceCommentReaction } from '@lobechat/types';+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { Popover, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx, useTheme } from 'antd-style';+import { PlusIcon, SmilePlus } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useGlobalStore } from '@/store/global';+import { globalGeneralSelectors } from '@/store/global/selectors';++/** The ten GitHub offers, in GitHub's order — the shortcut covers nearly every click. */+const QUICK_REACTIONS = ['👍', '👎', '😄', '🎉', '😕', '❤️', '🚀', '👀', '🙏', '🔥'];++const styles = createStaticStyles(({ css }) => ({+ /** The reaction row closes the comment, so it hugs the body's bottom edge. */+ bar: css`+ padding-block-start: 10px;+ `,+ chip: css`+ cursor: pointer;++ display: inline-flex;+ gap: 5px;+ align-items: center;++ height: 24px;+ padding-block: 0;+ padding-inline: 8px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 999px;++ font-size: 13px;+ line-height: 1;++ background: ${cssVar.colorFillQuaternary};++ &:hover {+ border-color: ${cssVar.colorBorder};+ }+ `,+ /** Yours reads as pressed: same shape, the accent border and count. */+ chipMine: css`+ border-color: ${cssVar.colorInfoBorder};+ color: ${cssVar.colorInfoText};+ background: color-mix(in srgb, ${cssVar.colorInfo} 10%, transparent);+ `,+ count: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ emojiButton: css`+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 30px;+ height: 30px;+ border-radius: ${cssVar.borderRadius};++ font-size: 17px;++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+ moreButton: css`+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 30px;+ height: 30px;+ border-radius: ${cssVar.borderRadius};++ color: ${cssVar.colorTextTertiary};++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ /** The add button, quiet until the comment is hovered — GitHub's behaviour. */+ trigger: css`+ cursor: pointer;++ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 24px;+ height: 24px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 999px;++ color: ${cssVar.colorTextTertiary};++ opacity: 0;++ transition: opacity ${cssVar.motionDurationFast};++ &:hover,+ &[data-open] {+ color: ${cssVar.colorText};+ opacity: 1;+ }++ @media (hover: none) {+ opacity: 1;+ }+ `,+ triggerVisible: css`+ opacity: 1;+ `,+}));++interface CommentReactionsProps {+ /** Absent for a reader who may not write — the chips stay, the button goes. */+ onReact?: (emoji: string, on: boolean) => Promise<void>;+ reactions: AcceptanceCommentReaction[];+}++/**+ * Agreement without another message. One row of chips under the words, plus the+ * add button GitHub puts there: on a review page most replies are "yes, this+ * one" or "no", and spending a whole timeline entry on that buries the remarks+ * that actually say something.+ */+const CommentReactions = memo<CommentReactionsProps>(({ onReact, reactions }) => {+ const { t } = useTranslation('verify');+ const theme = useTheme();+ const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);+ const [open, setOpen] = useState(false);+ const [full, setFull] = useState(false);++ if (reactions.length === 0 && !onReact) return null;++ const fire = async (emoji: string, on: boolean) => {+ try {+ await onReact?.(emoji, on);+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.updateFailed'));+ }+ };++ const pick = (emoji: string) => {+ setOpen(false);+ setFull(false);+ void fire(emoji, true);+ };++ const picker = full ? (+ <Picker+ data={data}+ locale={locale?.split('-')[0] || 'en'}+ previewPosition={'none'}+ skinTonePosition={'none'}+ theme={theme.appearance === 'dark' ? 'dark' : 'light'}+ onEmojiSelect={(emoji: { native: string }) => pick(emoji.native)}+ />+ ) : (+ <Flexbox horizontal gap={2} style={{ padding: 4 }} wrap={'wrap'}>+ {QUICK_REACTIONS.map((emoji) => (+ <div className={styles.emojiButton} key={emoji} onClick={() => pick(emoji)}>+ {emoji}+ </div>+ ))}+ <div className={styles.moreButton} onClick={() => setFull(true)}>+ <Icon icon={PlusIcon} size={15} />+ </div>+ </Flexbox>+ );++ return (+ <Flexbox horizontal align={'center'} className={styles.bar} gap={6} wrap={'wrap'}>+ {reactions.map((reaction) => (+ <Tooltip+ key={reaction.emoji}+ title={reaction.authorNames.length > 0 ? reaction.authorNames.join('、') : reaction.emoji}+ >+ <span+ className={cx(styles.chip, reaction.mine && styles.chipMine)}+ style={onReact ? undefined : { cursor: 'default' }}+ onClick={onReact ? () => void fire(reaction.emoji, !reaction.mine) : undefined}+ >+ <span>{reaction.emoji}</span>+ <span className={styles.count}>{reaction.count}</span>+ </span>+ </Tooltip>+ ))}+ {onReact && (+ <Popover+ content={picker}+ open={open}+ placement={'topLeft'}+ styles={{ content: { padding: 0 } }}+ trigger={'click'}+ onOpenChange={(visible) => {+ setOpen(visible);+ if (!visible) setFull(false);+ }}+ >+ <span+ data-comment-reaction-add+ className={cx(styles.trigger, open && styles.triggerVisible)}+ title={t('acceptance.comments.addReaction')}+ {...(open ? { 'data-open': '' } : {})}+ >+ <Icon icon={SmilePlus} size={13} />+ </span>+ </Popover>+ )}+ </Flexbox>+ );+});++CommentReactions.displayName = 'AcceptanceCommentReactions';++export default CommentReactions;diff --git a/src/features/Acceptance/Viewer/Comments/CommentThread.tsx b/src/features/Acceptance/Viewer/Comments/CommentThread.tsxnew file mode 100644index 00000000000..a405f749091--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/CommentThread.tsx@@ -0,0 +1,133 @@+'use client';++import type { AcceptanceCommentThread } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Tag, toast } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import { CheckCircle2 } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import CommentCard, { commentAuthorName } from './CommentCard';+import CommentComposer from './CommentComposer';+import { styles } from './styles';++interface CommentThreadProps {+ canComment: boolean;+ onDelete: (id: string) => Promise<void>;+ onReply: (rootId: string, content: string, attachments: { fileId: string }[]) => Promise<void>;+ onResolve: (rootId: string, resolved: boolean) => Promise<void>;+ thread: AcceptanceCommentThread;+}++/**+ * A region note and its answers, as the floating pin shows them: the remark,+ * whoever replied, and the two things you can do about it. Frameless on+ * purpose — the panel it lives in is already a surface.+ *+ * Once it is settled it folds to a single muted line. A handled concern is+ * closed business: it should be findable, not loud, which is why nothing here+ * carries a success colour any more.+ */+const CommentThread = memo<CommentThreadProps>(+ ({ canComment, onDelete, onReply, onResolve, thread }) => {+ const { t } = useTranslation('verify');+ const [replying, setReplying] = useState(false);+ const [resolving, setResolving] = useState(false);+ const [openOverride, setOpenOverride] = useState<boolean>();+ const { root, replies } = thread;+ const resolved = Boolean(root.resolvedAt);+ // Reopening a note should show it again without the reader asking twice,+ // so the override only holds while the resolved state stays put.+ const open = openOverride ?? !resolved;++ const toggleResolved = async () => {+ setResolving(true);+ try {+ await onResolve(root.id, !resolved);+ setOpenOverride(undefined);+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.updateFailed'));+ } finally {+ setResolving(false);+ }+ };++ if (!open)+ return (+ <button+ className={styles.resolvedSummary}+ type={'button'}+ onClick={() => setOpenOverride(true)}+ >+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon icon={CheckCircle2} size={13} />+ <span>+ {t('acceptance.comments.resolvedSummary', {+ count: replies.length + 1,+ name: commentAuthorName(root.author),+ })}+ </span>+ </Flexbox>+ </button>+ );++ const badges = root.contextRoundIndex !== null && (+ <Tag size={'small'}>+ {t('acceptance.comments.roundContext', { round: root.contextRoundIndex })}+ </Tag>+ );++ return (+ <Flexbox className={cx(resolved && styles.resolvedThread)}>+ <CommentCard badges={badges} comment={root} variant={'plain'} onDelete={onDelete} />+ {replies.map((reply) => (+ <div className={styles.panelReply} key={reply.id}>+ <CommentCard comment={reply} variant={'plain'} onDelete={onDelete} />+ </div>+ ))}+ {canComment &&+ (replying ? (+ <Flexbox className={styles.panelActions}>+ <CommentComposer+ autoFocus+ compact+ placeholder={t('acceptance.comments.replyPlaceholder')}+ submitLabel={t('acceptance.comments.reply')}+ onCancel={() => setReplying(false)}+ onSubmit={async (content, attachments) => {+ await onReply(root.id, content, attachments);+ setReplying(false);+ }}+ />+ </Flexbox>+ ) : (+ <Flexbox horizontal className={styles.panelActions} gap={2}>+ <Button outdent size={'small'} type={'text'} onClick={() => setReplying(true)}>+ {t('acceptance.comments.reply')}+ </Button>+ <Button+ outdent+ loading={resolving}+ size={'small'}+ type={'text'}+ onClick={() => void toggleResolved()}+ >+ {resolved ? t('acceptance.comments.reopen') : t('acceptance.comments.resolve')}+ </Button>+ {resolved && (+ <Button outdent size={'small'} type={'text'} onClick={() => setOpenOverride(false)}>+ {t('acceptance.comments.collapseThread')}+ </Button>+ )}+ </Flexbox>+ ))}+ </Flexbox>+ );+ },+);++CommentThread.displayName = 'AcceptanceCommentThread';++export default CommentThread;diff --git a/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx b/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsxnew file mode 100644index 00000000000..b9e14662a02--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx@@ -0,0 +1,171 @@+'use client';++import type { AcceptanceReviewAnnotation } from '@lobechat/types';+import { Flexbox, TextArea } from '@lobehub/ui';+import { Button, createModal, Text, toast, useModalContext } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { t } from 'i18next';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { AcceptanceEvidence } from '../Checks/types';+import { AnnotationCanvas } from '../Evidence/Annotation';+import { isAnnotatable } from '../Evidence/evidence';++const styles = createStaticStyles(({ css }) => ({+ hint: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ stage: css`+ overflow: auto;++ max-height: min(60vh, 640px);+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 8px;++ background: ${cssVar.colorFillQuaternary};+ `,+ thumb: css`+ cursor: pointer;++ overflow: hidden;++ width: 64px;+ height: 44px;+ border: 2px solid transparent;+ border-radius: 6px;++ background: ${cssVar.colorFillTertiary};++ img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ `,+ thumbActive: css`+ border-color: ${cssVar.colorPrimary};+ `,+}));++export interface EvidenceCommentValue {+ content: string;+ evidenceId: string;+ rect: AcceptanceReviewAnnotation['rect'];+}++interface EvidenceCommentModalProps {+ evidence: AcceptanceEvidence[];+ initialEvidenceId?: string;+ /** Persist the comment; resolve true to close, false to stay open. */+ onConfirm: (value: EvidenceCommentValue) => Promise<boolean>;+}++/**+ * Circle one spot on one screenshot and say what is wrong with it. One region+ * per comment on purpose: a thread is about a place, and two places are two+ * threads.+ */+const EvidenceCommentContent = memo<EvidenceCommentModalProps>(+ ({ evidence, initialEvidenceId, onConfirm }) => {+ const { t } = useTranslation('verify');+ const { close } = useModalContext();+ const images = evidence.filter(isAnnotatable);+ const [activeId, setActiveId] = useState(initialEvidenceId ?? images[0]?.id);+ const [rect, setRect] = useState<AcceptanceReviewAnnotation['rect'] | null>(null);+ const [content, setContent] = useState('');+ const [submitting, setSubmitting] = useState(false);+ const active = images.find((item) => item.id === activeId) ?? images[0];+ const trimmed = content.trim();++ const submit = async () => {+ if (!active || !rect || !trimmed || submitting) return;+ setSubmitting(true);+ try {+ const done = await onConfirm({ content: trimmed, evidenceId: active.id, rect });+ if (done) close();+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.createFailed'));+ } finally {+ setSubmitting(false);+ }+ };++ if (!active) return null;++ return (+ <Flexbox gap={12} padding={16}>+ <span className={styles.hint}>{t('acceptance.comments.regionHint')}</span>+ {images.length > 1 && (+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ {images.map((item) => (+ <div+ aria-pressed={item.id === active.id}+ className={cx(styles.thumb, item.id === active.id && styles.thumbActive)}+ key={item.id}+ role={'button'}+ onClick={() => {+ setActiveId(item.id);+ setRect(null);+ }}+ >+ <img alt={item.description ?? item.type} src={item.fileUrl!} />+ </div>+ ))}+ </Flexbox>+ )}+ <div className={styles.stage}>+ <AnnotationCanvas+ annotations={rect ? [{ comment: '', rect }] : []}+ src={active.fileUrl!}+ onDraw={setRect}+ onRemove={() => setRect(null)}+ onUpdate={(_index, next) => setRect(next)}+ />+ </div>+ <TextArea+ autoFocus+ autoSize={{ maxRows: 6, minRows: 2 }}+ placeholder={t('acceptance.comments.placeholder')}+ value={content}+ onChange={(event) => setContent(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ void submit();+ }+ }}+ />+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>+ {!rect && (+ <Text fontSize={12} type={'secondary'}>+ {t('acceptance.comments.regionMissing')}+ </Text>+ )}+ <Button+ disabled={!rect || !trimmed}+ loading={submitting}+ type={'primary'}+ onClick={() => void submit()}+ >+ {t('acceptance.comments.send')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+ },+);++EvidenceCommentContent.displayName = 'AcceptanceEvidenceCommentContent';++export const openEvidenceCommentModal = (options: EvidenceCommentModalProps) =>+ createModal({+ content: <EvidenceCommentContent {...options} />,+ footer: null,+ maskClosable: true,+ styles: { content: { padding: 0 } },+ title: t('acceptance.comments.regionModalTitle', { ns: 'verify' }),+ width: 'min(880px, 92vw)',+ });diff --git a/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx b/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsxnew file mode 100644index 00000000000..c4f8ea3d658--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/ReviewerApprovalBar.tsx@@ -0,0 +1,139 @@+'use client';++import { Flexbox, Icon, TextArea } from '@lobehub/ui';+import { Button, Text, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { BadgeCheck } from 'lucide-react';+import { nanoid } from 'nanoid';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAcceptanceScope } from '../AcceptanceScope';+import { useAcceptanceBundle } from '../useAcceptanceBundle';+import { canReviewAcceptance } from '../visibility';+import { useAcceptanceComments } from './hooks';++const styles = createStaticStyles(({ css }) => ({+ card: css`+ padding-block: 14px;+ padding-inline: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 12px;++ background: ${cssVar.colorBgContainer};+ `,+ description: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+}));++/**+ * The reviewer's counterpart of the decision bar. A teammate who can comment+ * but cannot close the acceptance says "fine by me" here; it lands as an+ * approval row the owner reads, and the acceptance status stays untouched.+ *+ * An approval is never final while the round is open: review is a moving+ * opinion, so it can be withdrawn and given again at any point. Only the state+ * standing when the owner decides matters, and the newest row is that state.+ */+const ReviewerApprovalBar = memo(() => {+ const { t } = useTranslation('verify');+ const { acceptanceId } = useAcceptanceScope();+ const { data } = useAcceptanceBundle(acceptanceId);+ const { canComment, create, items, remove } = useAcceptanceComments(acceptanceId);+ const [summary, setSummary] = useState('');+ const [pending, setPending] = useState(false);++ if (!data || !canComment || canReviewAcceptance(data)) return null;+ if (data.acceptance.status === 'accepted' || data.acceptance.status === 'closed') return null;++ // Nothing has been delivered yet, so there is nothing to approve. Allowing it+ // would pin the approval to no round at all, and an unpinned approval reads+ // as approving every round that ever arrives — the reviewer would never be+ // asked to look at the evidence.+ const currentRound = data.rounds.at(-1)?.run;+ if (!currentRound) return null;++ // `canDelete` is only ever true on the caller's own live rows, so it doubles+ // as "mine" without a user store lookup.+ const mine = [...items].reverse().find((item) => item.kind === 'approval' && item.canDelete);+ const approvedCurrentRound = mine?.contextRoundIndex === currentRound.roundIndex;++ const run = async (action: () => Promise<unknown>) => {+ setPending(true);+ try {+ await action();+ setSummary('');+ } catch (cause) {+ console.error('[acceptance:comments]', cause);+ toast.error(t('acceptance.comments.createFailed'));+ } finally {+ setPending(false);+ }+ };++ const approve = () =>+ run(() =>+ create({+ clientId: nanoid(),+ content: summary.trim(),+ contextRunId: currentRound.id,+ kind: 'approval',+ }),+ );++ return (+ <Flexbox className={styles.card} gap={10}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon+ color={approvedCurrentRound ? cssVar.colorSuccess : undefined}+ icon={BadgeCheck}+ size={18}+ />+ <Text weight={600}>+ {mine+ ? mine.contextRoundIndex === null+ ? t('acceptance.comments.youApprovedNoRound')+ : t('acceptance.comments.youApproved', { round: mine.contextRoundIndex })+ : t('acceptance.comments.approve')}+ </Text>+ </Flexbox>+ <span className={styles.description}>+ {approvedCurrentRound+ ? t('acceptance.comments.withdrawDescription')+ : t('acceptance.comments.approveDescription')}+ </span>+ {approvedCurrentRound ? (+ <Button+ loading={pending}+ style={{ alignSelf: 'flex-end' }}+ onClick={() => void run(() => remove(mine!.id))}+ >+ {t('acceptance.comments.withdraw')}+ </Button>+ ) : (+ <Flexbox gap={8}>+ <TextArea+ autoSize={{ maxRows: 4, minRows: 1 }}+ placeholder={t('acceptance.comments.approveSummaryPlaceholder')}+ value={summary}+ onChange={(event) => setSummary(event.target.value)}+ />+ <Button+ loading={pending}+ style={{ alignSelf: 'flex-end' }}+ type={'primary'}+ onClick={() => void approve()}+ >+ {mine ? t('acceptance.comments.approveAgain') : t('acceptance.comments.approve')}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ );+});++ReviewerApprovalBar.displayName = 'AcceptanceReviewerApprovalBar';++export default ReviewerApprovalBar;diff --git a/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx b/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsxnew file mode 100644index 00000000000..11305b293dd--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx@@ -0,0 +1,71 @@+'use client';++import type { AcceptanceCommentItem } from '@lobechat/types';+import { Flexbox } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { AcceptanceEvidence } from '../Checks/types';+import { AnnotatedImage } from '../Evidence/Annotation';+import { acceptanceAuthorColor } from './authorColor';++const THUMBNAIL_WIDTH = 220;++const styles = createStaticStyles(({ css }) => ({+ caption: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ wrapper: css`+ align-self: flex-start;+ `,+}));++interface ThreadEvidenceProps {+ comment: AcceptanceCommentItem;+ evidence: AcceptanceEvidence;+ /** The round this evidence was produced in; absent when it is unknown. */+ roundIndex?: number;+ /** True once a newer round replaced what the check shows today. */+ stale: boolean;+}++/**+ * The picture the remark was written against, kept with the remark.+ *+ * A newer round swaps the evidence the check row displays, and the thread's+ * region belongs to the old image — so without this the note survives with+ * nothing to look at, and "第 3 轮那块没覆盖" becomes unreadable the moment+ * round 4 lands. The thumbnail is the thread's own copy of that moment.+ */+const ThreadEvidence = memo<ThreadEvidenceProps>(({ comment, evidence, roundIndex, stale }) => {+ const { t } = useTranslation('verify');+ if (!evidence.fileUrl || !comment.rect) return null;++ return (+ <Flexbox className={styles.wrapper} gap={4}>+ <AnnotatedImage+ annotations={[{ color: acceptanceAuthorColor(comment.authorUserId), rect: comment.rect }]}+ imageStyle={{ width: THUMBNAIL_WIDTH }}+ showComments={false}+ src={evidence.fileUrl}+ />+ <span className={styles.caption}>+ {stale && roundIndex !== undefined+ ? t('acceptance.comments.evidenceFromRound', { round: roundIndex })+ : t('acceptance.comments.evidenceThisRound')}+ </span>+ {evidence.description && (+ <Text ellipsis fontSize={12} style={{ maxWidth: THUMBNAIL_WIDTH }} type={'secondary'}>+ {evidence.description}+ </Text>+ )}+ </Flexbox>+ );+});++ThreadEvidence.displayName = 'AcceptanceThreadEvidence';++export default ThreadEvidence;diff --git a/src/features/Acceptance/Viewer/Comments/anchor.test.ts b/src/features/Acceptance/Viewer/Comments/anchor.test.tsnew file mode 100644index 00000000000..dea1a007015--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/anchor.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest';++import { commentAnchorId, commentIdFromHash } from './anchor';++describe('comment anchors', () => {+ it('round-trips a comment id through the fragment', () => {+ const id = '9f1c2d3e-0000-4000-8000-000000000001';+ expect(commentIdFromHash(`#${commentAnchorId(id)}`)).toBe(id);+ });++ it('ignores fragments that address something else', () => {+ expect(commentIdFromHash('')).toBeUndefined();+ expect(commentIdFromHash('#')).toBeUndefined();+ // The page carries other fragments; only its own prefix may be claimed.+ expect(commentIdFromHash('#check-c2')).toBeUndefined();+ // A bare prefix names no comment.+ expect(commentIdFromHash('#comment-')).toBeUndefined();+ });+});diff --git a/src/features/Acceptance/Viewer/Comments/anchor.ts b/src/features/Acceptance/Viewer/Comments/anchor.tsnew file mode 100644index 00000000000..3a4fac90a72--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/anchor.ts@@ -0,0 +1,52 @@+import { useEffect, useRef } from 'react';+import { useLocation } from 'react-router';++/**+ * A comment is addressable, the way a pull-request comment is: its id lives in+ * the URL fragment, so a link pasted into chat opens the acceptance already+ * scrolled to the remark it is about. The fragment is used rather than a query+ * parameter so it never collides with the round and filter params the page+ * already carries, and so the browser keeps it across in-page navigation.+ */+const PREFIX = 'comment-';++export const commentAnchorId = (commentId: string) => `${PREFIX}${commentId}`;++/** The comment a fragment addresses, or undefined for any other fragment. */+export const commentIdFromHash = (hash: string): string | undefined => {+ const value = hash.replace(/^#/, '');+ return value.startsWith(PREFIX) ? value.slice(PREFIX.length) || undefined : undefined;+};++/** The link to hand someone else — this page, this comment. */+export const commentAnchorUrl = (commentId: string) => {+ if (typeof window === 'undefined') return '';+ const { origin, pathname, search } = window.location;+ return `${origin}${pathname}${search}#${commentAnchorId(commentId)}`;+};++/**+ * Which comment the URL points at, and a one-shot scroll to it.+ *+ * The scroll waits for the comment to exist: the list is fetched, so on a cold+ * open the element is not in the document when the fragment is first read.+ * `ready` is whatever the caller knows changes when the list arrives.+ *+ * Embedded viewers (a portal beside a conversation) share the page's fragment+ * with whatever else is mounted, so they never claim it.+ */+export const useCommentAnchor = (ready: unknown, embedded = false) => {+ const { hash } = useLocation();+ const anchoredId = embedded ? undefined : commentIdFromHash(hash);+ const scrolledTo = useRef<string | undefined>(undefined);++ useEffect(() => {+ if (!anchoredId || scrolledTo.current === anchoredId) return;+ const element = document.getElementById(commentAnchorId(anchoredId));+ if (!element) return;+ scrolledTo.current = anchoredId;+ element.scrollIntoView({ behavior: 'smooth', block: 'center' });+ }, [anchoredId, ready]);++ return anchoredId;+};diff --git a/src/features/Acceptance/Viewer/Comments/authorColor.test.ts b/src/features/Acceptance/Viewer/Comments/authorColor.test.tsnew file mode 100644index 00000000000..d58d7e27071--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/authorColor.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { ACCEPTANCE_AUTHOR_COLORS, acceptanceAuthorColor } from './authorColor';++describe('acceptanceAuthorColor', () => {+ it('is stable for one author and independent of call order', () => {+ const first = acceptanceAuthorColor('user_agent_testing_002');+ acceptanceAuthorColor('someone-else');+ expect(acceptanceAuthorColor('user_agent_testing_002')).toBe(first);+ });++ it('separates the authors of a two-person review', () => {+ expect(acceptanceAuthorColor('user_agent_testing_001')).not.toBe(+ acceptanceAuthorColor('user_agent_testing_002'),+ );+ });++ it('always answers with a palette colour, including for a deleted account', () => {+ for (const id of ['a', 'user_1', '文一', null, undefined, '']) {+ expect(ACCEPTANCE_AUTHOR_COLORS).toContain(acceptanceAuthorColor(id));+ }+ });++ it('draws from the theme palette, never a hard-coded hex', () => {+ for (const color of ACCEPTANCE_AUTHOR_COLORS) expect(color).toMatch(/^var\(--/);+ });++ it('leaves the verdict colours to verdicts', () => {+ const { cssVar } = require('antd-style');+ for (const semantic of [cssVar.volcano, cssVar.green, cssVar.colorError, cssVar.colorSuccess]) {+ expect(ACCEPTANCE_AUTHOR_COLORS).not.toContain(semantic);+ }+ });+});diff --git a/src/features/Acceptance/Viewer/Comments/authorColor.ts b/src/features/Acceptance/Viewer/Comments/authorColor.tsnew file mode 100644index 00000000000..9ace54d3cad--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/authorColor.ts@@ -0,0 +1,33 @@+import { cssVar } from 'antd-style';++/**+ * Marks drawn on evidence need to say WHO drew them at a glance: two reviewers+ * circling the same screenshot in one colour read as one person's notes. Each+ * author gets a stable hue from the design system's preset scale, so the box on+ * the image, the ring on their avatar and the marker badge always agree.+ *+ * Theme tokens rather than raw hexes, so the marks follow light/dark like every+ * other surface. The semantic hues are deliberately absent: `volcano` is+ * `colorError` and `green` is `colorSuccess`, and a person's box wearing either+ * would read as a verdict on the evidence rather than as an author.+ */+export const ACCEPTANCE_AUTHOR_COLORS = [+ cssVar.geekblue,+ cssVar.magenta,+ cssVar.gold,+ cssVar.cyan,+ cssVar.purple,+ cssVar.lime,+ cssVar.orange,+ cssVar.blue,+] as const;++/** Deterministic, order-independent: the same author keeps their colour across rounds and reloads. */+export const acceptanceAuthorColor = (authorUserId?: string | null): string => {+ if (!authorUserId) return ACCEPTANCE_AUTHOR_COLORS[0];+ let hash = 0;+ for (let index = 0; index < authorUserId.length; index++) {+ hash = (hash * 31 + authorUserId.codePointAt(index)!) >>> 0;+ }+ return ACCEPTANCE_AUTHOR_COLORS[hash % ACCEPTANCE_AUTHOR_COLORS.length];+};diff --git a/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.ts b/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.tsnew file mode 100644index 00000000000..7490891e642--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.ts@@ -0,0 +1,174 @@+import type { AcceptanceCommentItem, AcceptanceCommentThread } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildDiscussionTimeline, messageThreads, regionThreads } from './discussionTimeline';++let seq = 0;+const item = (overrides: Partial<AcceptanceCommentItem> = {}): AcceptanceCommentItem => {+ seq += 1;+ return {+ acceptanceId: 'acc',+ anchorType: 'acceptance',+ attachments: [],+ author: {+ avatar: null,+ fullName: 'u',+ id: 'u1',+ status: 'active',+ type: 'user',+ username: 'u',+ },+ authorAgentId: null,+ authorUserId: 'u1',+ canDelete: false,+ checkItemId: null,+ clientId: `c${seq}`,+ content: `m${seq}`,+ contextRoundIndex: null,+ contextRunId: null,+ createdAt: new Date(2026, 8, 9, 10, seq),+ deletedAt: null,+ editorData: null,+ evidenceId: null,+ id: `id${seq}`,+ kind: 'comment',+ parentCommentId: null,+ reactions: [],+ rect: null,+ resolvedAt: null,+ resolvedByUserId: null,+ updatedAt: new Date(2026, 8, 9, 10, seq),+ ...overrides,+ };+};+const thread = (+ root: AcceptanceCommentItem,+ replies: AcceptanceCommentItem[] = [],+): AcceptanceCommentThread => ({ replies, root });++describe('round notes', () => {+ it("folds a round's proposal into that round's entry instead of listing it", () => {+ const proposal = item({+ contextRunId: 'run-1',+ id: 'proposal-1',+ kind: 'proposal',+ });+ const remark = item({ id: 'remark-1' });++ const entries = buildDiscussionTimeline({+ approvals: [],+ items: [proposal, remark],+ rounds: [{ createdAt: new Date(2026, 8, 9, 9), id: 'run-1', roundIndex: 1 }],+ threads: [+ { replies: [], root: proposal },+ { replies: [], root: remark },+ ],+ });++ const round = entries.find((entry) => entry.kind === 'round');+ expect(round?.kind === 'round' && round.proposal?.id).toBe('proposal-1');+ // The note is the round's, so it never doubles as a message of its own.+ expect(+ entries.filter((entry) => entry.kind === 'message').map((entry) => entry.comment.id),+ ).toEqual(['remark-1']);+ });++ it('leaves a round with no note as a plain event', () => {+ const entries = buildDiscussionTimeline({+ approvals: [],+ items: [],+ rounds: [{ createdAt: new Date(2026, 8, 9, 9), id: 'run-1', roundIndex: 1 }],+ threads: [],+ });+ const round = entries.find((entry) => entry.kind === 'round');+ expect(round?.kind === 'round' && round.proposal).toBeUndefined();+ });+});++describe('discussion split', () => {+ it('keeps delivery-wide remarks and leaves circled regions to the checks', () => {+ const message = thread(item());+ const region = thread(item({ anchorType: 'evidence', checkItemId: 'c2', evidenceId: 'ev1' }));++ expect(messageThreads([message, region])).toEqual([message]);+ expect(regionThreads([message, region])).toEqual([region]);+ });+});++describe('buildDiscussionTimeline', () => {+ it('interleaves messages, rounds and approvals oldest first', () => {+ const early = thread(item({ createdAt: new Date(2026, 8, 9, 10, 0) }));+ const late = thread(item({ createdAt: new Date(2026, 8, 9, 12, 0) }));+ const approval = item({+ createdAt: new Date(2026, 8, 9, 11, 30),+ kind: 'approval',+ });++ const timeline = buildDiscussionTimeline({+ approvals: [approval],+ rounds: [+ { createdAt: new Date(2026, 8, 9, 11, 0), roundIndex: 2 },+ { createdAt: new Date(2026, 8, 9, 9, 0), roundIndex: 1 },+ ],+ threads: [late, early],+ });++ expect(timeline.map((entry) => entry.kind)).toEqual([+ 'round',+ 'message',+ 'round',+ 'approval',+ 'message',+ ]);+ });++ it('flattens replies to a delivery-wide remark into their own messages', () => {+ const root = item({ createdAt: new Date(2026, 8, 9, 10, 0) });+ const reply = item({+ createdAt: new Date(2026, 8, 9, 10, 30),+ parentCommentId: root.id,+ });++ const timeline = buildDiscussionTimeline({+ approvals: [],+ rounds: [],+ threads: [thread(root, [reply])],+ });++ expect(timeline).toHaveLength(2);+ expect(timeline.map((entry) => (entry.kind === 'message' ? entry.comment.id : ''))).toEqual([+ root.id,+ reply.id,+ ]);+ });++ it('leaves the answers to a circled region out of the chat', () => {+ const root = item({ anchorType: 'evidence', evidenceId: 'ev1' });+ const reply = item({ parentCommentId: root.id });+ const timeline = buildDiscussionTimeline({+ approvals: [],+ rounds: [],+ threads: [thread(root, [reply])],+ });+ expect(timeline).toEqual([]);+ });++ it('drops rounds with no index and withdrawn approvals', () => {+ const timeline = buildDiscussionTimeline({+ approvals: [item({ deletedAt: new Date(), kind: 'approval' })],+ rounds: [+ { createdAt: new Date(2026, 8, 9, 9, 0), roundIndex: null },+ { createdAt: null, roundIndex: 3 },+ ],+ threads: [],+ });++ expect(timeline).toEqual([]);+ });++ it('never lists a circled region as a message', () => {+ const region = thread(item({ anchorType: 'evidence', evidenceId: 'ev1' }));+ const timeline = buildDiscussionTimeline({ approvals: [], rounds: [], threads: [region] });+ expect(timeline).toEqual([]);+ });+});diff --git a/src/features/Acceptance/Viewer/Comments/discussionTimeline.ts b/src/features/Acceptance/Viewer/Comments/discussionTimeline.tsnew file mode 100644index 00000000000..8d318ecfcea--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/discussionTimeline.ts@@ -0,0 +1,91 @@+import type { AcceptanceCommentItem, AcceptanceCommentThread } from '@lobechat/types';++/**+ * The discussion is a conversation, not a filing cabinet: it carries messages+ * about the delivery as a whole, strung together with the events that happened+ * between them (a round landing, a reviewer approving).+ *+ * Comments circled on a screenshot are deliberately NOT here — a region note+ * only means anything next to the pixels it points at, so it lives on the check+ * that owns that evidence.+ */+export type DiscussionEntry =+ | { at: Date; comment: AcceptanceCommentItem; kind: 'message' }+ | {+ at: Date;+ kind: 'round';+ /** The round's own note, signed by the agent that produced it. */+ proposal?: AcceptanceCommentItem;+ roundIndex: number;+ runId?: string;+ }+ | { approval: AcceptanceCommentItem; at: Date; kind: 'approval' };++/**+ * Threads that belong in the discussion stream: plain, delivery-wide remarks.+ * A proposal is not one of them — it is the round's own note and renders as+ * part of that round, so listing it here too would say the same thing twice.+ */+export const messageThreads = (threads: AcceptanceCommentThread[]) =>+ threads.filter(+ (thread) => thread.root.anchorType === 'acceptance' && thread.root.kind !== 'proposal',+ );++/** Threads circled on evidence, which belong on the check rows instead. */+export const regionThreads = (threads: AcceptanceCommentThread[]) =>+ threads.filter((thread) => thread.root.anchorType === 'evidence');++interface BuildInput {+ approvals: AcceptanceCommentItem[];+ /** Every comment of the acceptance — proposals are read straight off it. */+ items?: AcceptanceCommentItem[];+ rounds: { createdAt: Date | string | null; id?: string; roundIndex: number | null }[];+ threads: AcceptanceCommentThread[];+}++/**+ * One chronological stream, oldest first — the order the delivery actually+ * happened in, which is what makes "he asked, then round 4 landed, then she+ * approved" readable at all.+ */+export const buildDiscussionTimeline = ({+ approvals,+ items = [],+ rounds,+ threads,+}: BuildInput): DiscussionEntry[] => {+ const entries: DiscussionEntry[] = [];++ // One note per round; a later one wins, which is what a re-ingest of the+ // same round means.+ const proposalByRun = new Map<string, AcceptanceCommentItem>();+ for (const item of items) {+ if (item.kind !== 'proposal' || !item.contextRunId || item.deletedAt) continue;+ proposalByRun.set(item.contextRunId, item);+ }++ // Flattened: the discussion is a chat, so a reply to a delivery-wide remark+ // is just the next message. Threading is for regions, where a note and its+ // answers are about one spot on one picture.+ for (const thread of messageThreads(threads))+ for (const comment of [thread.root, ...thread.replies])+ entries.push({ at: new Date(comment.createdAt), comment, kind: 'message' });++ for (const round of rounds) {+ if (round.roundIndex === null || !round.createdAt) continue;+ entries.push({+ at: new Date(round.createdAt),+ kind: 'round',+ proposal: round.id ? proposalByRun.get(round.id) : undefined,+ roundIndex: round.roundIndex,+ runId: round.id,+ });+ }++ for (const approval of approvals) {+ if (approval.deletedAt) continue;+ entries.push({ approval, at: new Date(approval.createdAt), kind: 'approval' });+ }++ return entries.sort((a, b) => a.at.getTime() - b.at.getTime());+};diff --git a/src/features/Acceptance/Viewer/Comments/hooks.ts b/src/features/Acceptance/Viewer/Comments/hooks.tsnew file mode 100644index 00000000000..fba6a4a6b3f--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/hooks.ts@@ -0,0 +1,98 @@+import type { AcceptanceCommentList, CreateAcceptanceCommentInput } from '@lobechat/types';+import { useCallback, useMemo } from 'react';++import { useClientDataSWR } from '@/libs/swr';+import { acceptanceCommentKeys } from '@/libs/swr/keys';+import { acceptanceCommentService } from '@/services/acceptanceComment';++import {+ groupCommentThreads,+ listParticipants,+ summarizeApprovals,+ toggleReaction,+} from './threads';++const EMPTY: AcceptanceCommentList = { canComment: false, items: [] };++/**+ * The whole discussion of one acceptance, read once and shared by every+ * consumer on the page through the SWR key. Mutations revalidate the list;+ * the bundle itself never changes because of a comment.+ */+export const useAcceptanceComments = (acceptanceId: string | undefined) => {+ const swr = useClientDataSWR<AcceptanceCommentList>(+ acceptanceId ? acceptanceCommentKeys.list(acceptanceId) : null,+ () => acceptanceCommentService.list(acceptanceId!),+ { revalidateOnFocus: true },+ );+ const data = swr.data ?? EMPTY;+ const { mutate } = swr;++ const threads = useMemo(() => groupCommentThreads(data.items), [data.items]);+ const approvals = useMemo(() => summarizeApprovals(data.items), [data.items]);+ const participants = useMemo(() => listParticipants(data.items), [data.items]);++ const create = useCallback(+ async (input: Omit<CreateAcceptanceCommentInput, 'acceptanceId'>) => {+ if (!acceptanceId) return;+ await acceptanceCommentService.create({ ...input, acceptanceId });+ await mutate();+ },+ [acceptanceId, mutate],+ );+ const remove = useCallback(+ async (id: string) => {+ await acceptanceCommentService.delete(id);+ await mutate();+ },+ [mutate],+ );+ /**+ * Optimistic on purpose: a chip that waits for a round trip before it fills+ * in makes the click feel broken, and the write is a single idempotent row.+ */+ const react = useCallback(+ async (id: string, emoji: string, on: boolean) => {+ if (!acceptanceId) return;+ await mutate(+ async () => {+ await acceptanceCommentService.react(id, emoji, on);+ // Read back rather than trusting the guess: the count also moves when+ // someone else reacts, and the names behind it are only known here.+ return acceptanceCommentService.list(acceptanceId);+ },+ {+ optimisticData: (current) => toggleReaction(current ?? EMPTY, id, emoji, on),+ revalidate: false,+ },+ );+ },+ [acceptanceId, mutate],+ );+ const setResolved = useCallback(+ async (id: string, resolved: boolean) => {+ await acceptanceCommentService.setResolved(id, resolved);+ await mutate();+ },+ [mutate],+ );++ return {+ approvals,+ canComment: data.canComment,+ /**+ * A failed read is not a permission answer. Without this the page falls+ * back to `canComment: false` and tells the owner to join the workspace,+ * which is both wrong and unactionable.+ */+ error: swr.error as Error | undefined,+ create,+ isLoading: swr.isLoading,+ items: data.items,+ participants,+ react,+ remove,+ setResolved,+ threads,+ };+};diff --git a/src/features/Acceptance/Viewer/Comments/styles.ts b/src/features/Acceptance/Viewer/Comments/styles.tsnew file mode 100644index 00000000000..800c386a233--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/styles.ts@@ -0,0 +1,282 @@+import { createStaticStyles, cssVar } from 'antd-style';++/**+ * Two comment surfaces, deliberately different.+ *+ * The discussion follows GitHub's Conversation: a rail down the left, the+ * author's avatar beside it, and the remark in a bordered box. Header names who+ * spoke and when; body carries the words. No colour anywhere — an author's+ * colour belongs on the marks they drew, not around their face.+ *+ * A region note is a Figma-style pin: no frame at all, just an elevated surface+ * floating beside the screenshot.+ */+export const TIMELINE_NODE = 32;+const NODE_GUTTER = 12;+const EVENT_DOT = 20;+/**+ * GitHub does not run the rail through the avatars. It runs it just inside the+ * content column's left edge, where the opaque comment boxes cover it and only+ * the gaps between turns show a line; the avatar hangs off to its left.+ * Measured off the reference: 19px in from the box.+ */+const RAIL = TIMELINE_NODE + NODE_GUTTER + 19;++/**+ * The accent, diluted well past the reference. A blue box line reads much+ * heavier than the same blue on GitHub's does, because everything around it+ * here is a near-black surface with a near-black border.+ */+const SELF_BORDER = `color-mix(in srgb, ${cssVar.colorInfoBorder} 45%, transparent)`;++export const styles = createStaticStyles(({ css }) => ({+ body: css`+ /* A one-line remark in a header-topped box read as a sliver; GitHub's+ comment bodies always have room to breathe under the author line. */+ min-height: 80px;+ padding-block: 12px;+ padding-inline: 14px;++ font-size: 14px;+ line-height: 1.7;+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ `,+ /** A discussion message: header strip, then the words. */+ box: css`+ /* Positioned so it paints after the entry's rail pseudo-element. Without+ it the line ran straight over the box and clipped the first glyph of+ every line that crossed x = RAIL. */+ position: relative;++ flex: 1;++ min-width: 0;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorBgContainer};+ `,+ /**+ * Your own turn, the way GitHub marks it: the box line picks up the accent+ * blue and the header strip takes a matching tint. In a two-person review you+ * scan for what the other side said, and that only works if your own remarks+ * are identifiable without reading the names.+ *+ * A line and nothing else. Every fill this box ever had — the header strip,+ * then the accent tint on top of it — read as decoration once the rest of the+ * discussion had none.+ */+ boxSelf: css`+ border-color: ${SELF_BORDER};+ `,+ /**+ * The author line, over the words. No fill and no divider: a strip of tinted+ * surface with a rule under it framed every remark like a table row. The+ * padding stays, so the line still reads as its own band.+ */+ boxHeader: css`+ padding-block: 8px;+ padding-inline: 14px;+ border-start-start-radius: ${cssVar.borderRadius};+ border-start-end-radius: ${cssVar.borderRadius};+ `,+ /**+ * The comment the URL points at. An outline rather than a fill: the box's own+ * line already carries meaning (yours vs theirs), and the discussion has no+ * fills left to compete with.+ */+ boxAnchored: css`+ outline: 2px solid ${cssVar.colorInfoBorder};+ outline-offset: 2px;+ `,+ /** Attachments sit under the words with a gap, never woven into them. */+ attachments: css`+ padding-block-start: 10px;+ `,+ /** The composer, wrapped so it reads as one block rather than a loose field. */+ composerBlock: css`+ /* Same reason as the message box: it has to cover the rail, not sit under it. */+ position: relative;++ padding: 12px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorBgContainer};+ `,+ deleted: css`+ font-style: italic;+ color: ${cssVar.colorTextTertiary};+ `,+ /** A round landing or an approval: a dot on the rail and one line of text. */+ event: css`+ padding-block: 2px;+ font-size: 13px;+ color: ${cssVar.colorTextSecondary};+ `,+ /**+ * Opaque on purpose: a translucent fill let the rail show straight through+ * the dot, which read as a smudge rather than as a node on the line.+ */+ eventDot: css`+ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: ${EVENT_DOT}px;+ height: ${EVENT_DOT}px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 50%;++ color: ${cssVar.colorTextTertiary};++ background: ${cssVar.colorBgElevated};+ `,+ meta: css`+ flex: none;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ panelBody: css`+ padding-block-start: 6px;++ font-size: 13px;+ line-height: 1.65;+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ `,+ /**+ * The actions close the note, so they hug its bottom edge. Sitting a full+ * panel padding above it left a band of empty surface under them that read+ * as a rendering mistake.+ */+ panelActions: css`+ margin-block-end: -4px;+ padding-block-start: 10px;+ `,+ panelReply: css`+ padding-block-start: 10px;+ `,+ /**+ * A settled note is closed business. It folds down to one quiet line and,+ * opened again, stays muted — a handled concern should never draw the eye+ * harder than an open one, which a green badge did.+ */+ resolvedSummary: css`+ cursor: pointer;++ width: 100%;+ padding: 0;+ border: none;++ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ text-align: start;++ background: none;++ &:hover {+ color: ${cssVar.colorTextSecondary};+ }+ `,+ resolvedThread: css`+ color: ${cssVar.colorTextTertiary};+ `,+ /**+ * A name is never a wrap point. In the narrow floating note the header ran+ * out of room and broke a two-character name down the middle of the circle.+ */+ authorName: css`+ overflow: hidden;+ flex: none;++ max-width: 180px;++ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ /**+ * A headline is a sentence, not a name: it may wrap, and it must never be+ * cut at the name cap — "Acceptance Builder 已完成…" says nothing.+ */+ headline: css`+ min-width: 0;+ `,+ /** Pushed to the end of its line, so the header above may wrap freely. */+ rowActions: css`+ flex: none;+ margin-inline-start: auto;+ opacity: 0;+ transition: opacity ${cssVar.motionDurationFast};++ @media (hover: none) {+ opacity: 1;+ }+ `,+ /** Entries with no node of their own still line up with the boxes above. */+ nodelessEntry: css`+ padding-inline-start: ${TIMELINE_NODE + NODE_GUTTER}px;+ `,+ /** An event has no avatar; its dot takes the rail's place on the line. */+ eventEntry: css`+ padding-inline-start: ${RAIL - EVENT_DOT / 2}px;+ `,+ /**+ * The stream's last turn. Without this the rail stopped at the composer's top+ * edge and the box hung off the end of the line instead of closing it.+ */+ tailEntry: css`+ /* Outranks the last-of-type truncation, which would otherwise stop the+ line 10px in and leave the composer hanging off the end. */+ &&&::before {+ inset-block: 0;+ height: auto;+ }+ `,+ /**+ * The continuous line behind the nodes. Drawn on the entry rather than the+ * list so the last entry can stop it, and inset to the node's centre.+ */+ timelineEntry: css`+ position: relative;+ padding-block-end: 14px;++ &::before {+ content: '';++ position: absolute;+ inset-block: 0;+ inset-inline-start: ${RAIL - 1}px;++ width: 2px;++ background: ${cssVar.colorBorderSecondary};+ }++ &:hover [data-comment-actions],+ &:hover [data-comment-reaction-add] {+ opacity: 1;+ }++ &:first-of-type::before {+ inset-block-start: ${EVENT_DOT / 2}px;+ }++ &:last-of-type::before {+ inset-block-end: auto;+ height: ${EVENT_DOT / 2}px;+ }+ `,+ /** The author's column, left of the rail — GitHub keeps the face off the line. */+ timelineNode: css`+ display: flex;+ flex: none;+ justify-content: center;++ width: ${TIMELINE_NODE}px;++ line-height: 0;+ `,+}));diff --git a/src/features/Acceptance/Viewer/Comments/threads.test.ts b/src/features/Acceptance/Viewer/Comments/threads.test.tsnew file mode 100644index 00000000000..989f7b4933c--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/threads.test.ts@@ -0,0 +1,107 @@+import type { AcceptanceCommentItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ groupCommentThreads,+ listParticipants,+ summarizeApprovals,+ threadsForCheck,+ threadsForEvidence,+} from './threads';++const author = (id: string): AcceptanceCommentItem['author'] => ({+ avatar: null,+ fullName: id,+ id,+ status: 'active',+ type: 'user',+ username: id,+});++let seq = 0;+const item = (overrides: Partial<AcceptanceCommentItem> = {}): AcceptanceCommentItem => {+ seq += 1;+ const authorId = overrides.authorUserId ?? 'u1';+ return {+ acceptanceId: 'acc',+ anchorType: 'acceptance',+ attachments: [],+ author: author(authorId),+ authorAgentId: null,+ authorUserId: authorId,+ canDelete: false,+ checkItemId: null,+ clientId: `c${seq}`,+ content: `content ${seq}`,+ contextRoundIndex: null,+ contextRunId: null,+ createdAt: new Date(2026, 8, 9, 10, seq),+ deletedAt: null,+ editorData: null,+ evidenceId: null,+ id: `id${seq}`,+ kind: 'comment',+ parentCommentId: null,+ reactions: [],+ rect: null,+ resolvedAt: null,+ resolvedByUserId: null,+ updatedAt: new Date(2026, 8, 9, 10, seq),+ ...overrides,+ };+};++describe('groupCommentThreads', () => {+ it('nests replies under their root and keeps approvals out of the discussion', () => {+ const root = item();+ const reply = item({ parentCommentId: root.id });+ const approval = item({ kind: 'approval' });+ const orphan = item({ parentCommentId: 'missing' });++ const threads = groupCommentThreads([root, reply, approval, orphan]);+ expect(threads).toHaveLength(1);+ expect(threads[0].root.id).toBe(root.id);+ expect(threads[0].replies.map((r) => r.id)).toEqual([reply.id]);+ });++ it('filters threads by evidence and by check', () => {+ const onImage = item({ anchorType: 'evidence', checkItemId: 'c2', evidenceId: 'ev1' });+ const onOther = item({ anchorType: 'evidence', checkItemId: 'c2', evidenceId: 'ev2' });+ const global = item();+ const threads = groupCommentThreads([onImage, onOther, global]);++ expect(threadsForEvidence(threads, 'ev1').map((t) => t.root.id)).toEqual([onImage.id]);+ expect(threadsForCheck(threads, 'c2').map((t) => t.root.id)).toEqual([onImage.id, onOther.id]);+ });+});++describe('summarizeApprovals', () => {+ it('keeps one entry per reviewer at their newest approval', () => {+ const early = item({ authorUserId: 'wenyi', contextRoundIndex: 2, kind: 'approval' });+ const late = item({ authorUserId: 'wenyi', contextRoundIndex: 4, kind: 'approval' });+ const other = item({ authorUserId: 'liansheng', contextRoundIndex: 4, kind: 'approval' });+ const deleted = item({+ authorUserId: 'gone',+ deletedAt: new Date(),+ kind: 'approval',+ });++ const summary = summarizeApprovals([early, late, other, deleted, item()]);+ expect(summary.map((s) => [s.authorUserId, s.contextRoundIndex])).toEqual([+ ['wenyi', 4],+ ['liansheng', 4],+ ]);+ });+});++describe('listParticipants', () => {+ it('lists each live author once in first-seen order', () => {+ const rows = [+ item({ authorUserId: 'b' }),+ item({ authorUserId: 'a' }),+ item({ authorUserId: 'b', kind: 'approval' }),+ item({ authorUserId: 'c', deletedAt: new Date() }),+ ];+ expect(listParticipants(rows).map((p) => p.userId)).toEqual(['b', 'a']);+ });+});diff --git a/src/features/Acceptance/Viewer/Comments/threads.ts b/src/features/Acceptance/Viewer/Comments/threads.tsnew file mode 100644index 00000000000..661aa23176b--- /dev/null+++ b/src/features/Acceptance/Viewer/Comments/threads.ts@@ -0,0 +1,105 @@+import type {+ AcceptanceApprovalSummary,+ AcceptanceCommentItem,+ AcceptanceCommentList,+ AcceptanceCommentThread,+} from '@lobechat/types';++/**+ * Group a flat, oldest-first comment list into threads. A reply whose root is+ * missing (never expected — the server keeps threads inside one acceptance) is+ * dropped rather than rendered orphaned. Approvals are not discussion and are+ * left out; read them with {@link summarizeApprovals}.+ */+export const groupCommentThreads = (items: AcceptanceCommentItem[]): AcceptanceCommentThread[] => {+ const threads = new Map<string, AcceptanceCommentThread>();+ for (const item of items) {+ if (item.parentCommentId) continue;+ if (item.kind === 'approval') continue;+ threads.set(item.id, { replies: [], root: item });+ }+ for (const item of items) {+ if (!item.parentCommentId) continue;+ threads.get(item.parentCommentId)?.replies.push(item);+ }+ return [...threads.values()];+};++/** Threads circled on one evidence image, in posting order. */+export const threadsForEvidence = (threads: AcceptanceCommentThread[], evidenceId: string) =>+ threads.filter((thread) => thread.root.evidenceId === evidenceId);++/** Threads hanging on one union check (any of its evidence images). */+export const threadsForCheck = (threads: AcceptanceCommentThread[], checkItemId: string) =>+ threads.filter((thread) => thread.root.checkItemId === checkItemId);++/**+ * Each reviewer's standing opinion: their NEWEST approval row. Someone who+ * approved round 2 and again round 4 shows once, at round 4.+ */+export const summarizeApprovals = (items: AcceptanceCommentItem[]): AcceptanceApprovalSummary[] => {+ const latest = new Map<string, AcceptanceApprovalSummary>();+ for (const item of items) {+ if (item.kind !== 'approval' || !item.authorUserId || item.deletedAt) continue;+ latest.set(item.authorUserId, {+ author: item.author,+ authorUserId: item.authorUserId,+ contextRoundIndex: item.contextRoundIndex,+ createdAt: item.createdAt,+ });+ }+ return [...latest.values()];+};++/** Live participants: everyone who wrote a surviving row, in first-seen order. */+export const listParticipants = (items: AcceptanceCommentItem[]) => {+ const seen = new Map<string, AcceptanceCommentItem['author']>();+ for (const item of items) {+ if (!item.authorUserId || item.deletedAt || seen.has(item.authorUserId)) continue;+ seen.set(item.authorUserId, item.author);+ }+ return [...seen.entries()].map(([userId, author]) => ({ author, userId }));+};++/**+ * The list as it will look once the server has taken the click, so the chip can+ * fill in immediately. `mine` is the only thing the caller knows for certain,+ * which is why the count moves by exactly one and the name list is left alone —+ * a wrong name for 300ms is worse than a late one.+ */+export const toggleReaction = (+ list: AcceptanceCommentList,+ commentId: string,+ emoji: string,+ on: boolean,+): AcceptanceCommentList => ({+ ...list,+ items: list.items.map((item) => {+ if (item.id !== commentId) return item;+ const existing = item.reactions.find((reaction) => reaction.emoji === emoji);+ if (on) {+ if (existing?.mine) return item;+ return {+ ...item,+ reactions: existing+ ? item.reactions.map((reaction) =>+ reaction.emoji === emoji+ ? { ...reaction, count: reaction.count + 1, mine: true }+ : reaction,+ )+ : [...item.reactions, { authorNames: [], count: 1, emoji, mine: true }],+ };+ }+ if (!existing?.mine) return item;+ return {+ ...item,+ reactions: item.reactions.flatMap((reaction) =>+ reaction.emoji === emoji+ ? reaction.count <= 1+ ? []+ : [{ ...reaction, count: reaction.count - 1, mine: false }]+ : [reaction],+ ),+ };+ }),+});diff --git a/src/features/Acceptance/Viewer/Evidence/Annotation.tsx b/src/features/Acceptance/Viewer/Evidence/Annotation.tsxindex 273dcb7409b..92b6f25a5ca 100644--- a/src/features/Acceptance/Viewer/Evidence/Annotation.tsx+++ b/src/features/Acceptance/Viewer/Evidence/Annotation.tsx@@ -7,6 +7,7 @@ import { createStaticStyles, cssVar } from 'antd-style';import { Trash2 } from 'lucide-react';import { memo } from 'react';+import type { EvidenceOverlay } from './overlay';import { useAnnotationGesture } from './useAnnotationGesture';/**@@ -36,7 +37,7 @@ const styles = createStaticStyles(({ css }) => ({font-size: 11px;font-weight: 600;line-height: 1;- color: #fff;+ color: ${cssVar.colorTextLightSolid};background: ${cssVar.colorError};`,@@ -60,7 +61,7 @@ const styles = createStaticStyles(({ css }) => ({border: none;border-radius: 50%;- color: #fff;+ color: ${cssVar.colorTextLightSolid};background: ${cssVar.colorError};@@ -106,7 +107,7 @@ const styles = createStaticStyles(({ css }) => ({position: absolute;border: 2px solid ${cssVar.colorError};border-radius: 4px;- box-shadow: 0 0 0 1px rgb(0 0 0 / 25%);+ box-shadow: 0 0 0 1px ${cssVar.colorFillSecondary};`,resizeHandle: css`cursor: nwse-resize;@@ -139,12 +140,12 @@ const rectStyle = (rect: Rect) => ({interface AnnotatedImageProps {/**- * `label` overrides the badge number. Regions belonging to one review may be- * spread across several images, and per-image numbering would restart at 1 on- * each — so a list that references "区域 2" elsewhere could point at two- * different boxes. Pass an explicit label to keep one sequence across images.+ * Each region carries the colour of whoever drew it — see+ * {@link EvidenceOverlay}. `label` overrides the badge number: regions+ * belonging to one review may be spread across several images, and per-image+ * numbering would restart at 1 on each.*/- annotations: { comment?: string; label?: number; rect: Rect }[];+ annotations: EvidenceOverlay[];imageStyle?: React.CSSProperties;/** Render the per-region notes under the image. Off when a caller already lists them. */showComments?: boolean;@@ -163,8 +164,22 @@ export const AnnotatedImage = memo<AnnotatedImageProps>(<div className={styles.frame}><img alt={''} className={styles.image} src={src} style={imageStyle} />{annotations.map((annotation, index) => (- <div className={styles.rect} key={index} style={rectStyle(annotation.rect)}>- {numbered && <span className={styles.badge}>{annotation.label ?? index + 1}</span>}+ <div+ className={styles.rect}+ key={index}+ style={{+ ...rectStyle(annotation.rect),+ borderColor: annotation.color ?? cssVar.colorError,+ }}+ >+ {numbered && (+ <span+ className={styles.badge}+ style={{ background: annotation.color ?? cssVar.colorError }}+ >+ {annotation.label ?? index + 1}+ </span>+ )}</div>))}</div>@@ -175,6 +190,7 @@ export const AnnotatedImage = memo<AnnotatedImageProps>(annotation.comment && (<Text fontSize={12} key={index} type={'secondary'}>{numbered ? `${annotation.label ?? index + 1}. ` : ''}+ {annotation.authorName ? `${annotation.authorName}: ` : ''}{annotation.comment}</Text>),diff --git a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsxindex e89d5409176..2a3ea5e0d74 100644--- a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx+++ b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx@@ -1,6 +1,5 @@'use client';-import type { AcceptanceReviewAnnotation } from '@lobechat/types';import { Flexbox, Image } from '@lobehub/ui';import { useResponsive } from 'antd-style';import { memo } from 'react';@@ -22,6 +21,7 @@ import type { AcceptanceEvidence } from '../Checks/types';import { AnnotatedImage } from '../Evidence/Annotation';import { ScreenshotTiles } from '../Evidence/ScreenshotTiles';import { IMAGE_EVIDENCE, imageRatio, isVisual } from './evidence';+import type { EvidenceOverlayMap } from './overlay';import { styles } from './styles';/** Flat media for a comparison side — the card frames it, so no own border/radius. */@@ -64,14 +64,11 @@ export const EvidenceList = memo<{onReviewEvidence?: (id: string) => void;/*** Regions to draw over an evidence image, keyed by evidence id. Used by the- * AI proposal: rather than the card rendering its own copy of the screenshot- * (which showed the same image twice in one row), the boxes land on the image- * that is already here.+ * AI proposal and by reviewers' circled comments: rather than the card+ * rendering its own copy of the screenshot (which showed the same image twice+ * in one row), the boxes land on the image that is already here.*/- overlays?: Map<- string,- { comment?: string; label?: number; rect: AcceptanceReviewAnnotation['rect'] }[]- >;+ overlays?: EvidenceOverlayMap;}>(({ evidence, overlays, onReviewEvidence }) => {const { md = true } = useResponsive();const sorted = [...evidence].sort((a, b) => (isVisual(b) ? 1 : 0) - (isVisual(a) ? 1 : 0));diff --git a/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx b/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsxindex 9907321ce86..494a3d56a57 100644--- a/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx+++ b/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx@@ -1,10 +1,12 @@'use client';-import type { AcceptanceReviewAnnotation } from '@lobechat/types';-import { Flexbox, Image } from '@lobehub/ui';+import { Flexbox, Icon, Image } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Check, MessageSquare } from 'lucide-react';import { memo, type ReactNode, useState } from 'react';+import type { EvidenceOverlay } from './overlay';import {annotationInSlice,isPortraitScreenshot,@@ -13,8 +15,6 @@ import {screenshotTileWidth,} from './screenshotSlices';-type Rect = AcceptanceReviewAnnotation['rect'];-const styles = createStaticStyles(({ css }) => ({badge: css`position: absolute;@@ -32,9 +32,7 @@ const styles = createStaticStyles(({ css }) => ({font-size: 11px;font-weight: 600;line-height: 1;- color: #fff;-- background: ${cssVar.colorError};+ color: ${cssVar.colorTextLightSolid};`,frame: css`position: relative;@@ -50,21 +48,197 @@ const styles = createStaticStyles(({ css }) => ({border: none;border-radius: 0;`,+ /**+ * The clickable note slot, pinned to the region's OUTER right edge: the box+ * marks where the concern is, this marker is how you read it. Kept on the+ * right so it never covers the numbered badge on the opposite corner.+ */+ marker: css`+ pointer-events: auto;+ cursor: pointer;++ position: absolute;+ inset-block-start: -10px;+ inset-inline-end: -10px;++ display: inline-flex;+ gap: 2px;+ align-items: center;+ justify-content: center;++ padding-block: 2px;+ padding-inline: 5px;+ border: none;+ border-radius: 999px;++ font-size: 10px;+ font-weight: 600;+ line-height: 1;+ color: ${cssVar.colorTextLightSolid};++ box-shadow: ${cssVar.boxShadowTertiary};++ &:hover {+ filter: brightness(1.12);+ }+ `,+ markerActive: css`+ outline: 2px solid ${cssVar.colorTextLightSolid};+ `,+ /**+ * The opened note FLOATS rather than taking a column of its own: reserving+ * layout for it shoved the evidence narrower the moment anyone opened a note,+ * and closing it snapped the image back.+ *+ * Where it floats depends on the room beside the reading column. Given a wide+ * enough window it sits in the margin, clear of the screenshot — the note is+ * about the picture, so covering the picture with it is the one thing it must+ * not do. Below that it falls back to hugging the image's right edge, which+ * still beats pushing the evidence around.+ */+ note: css`+ position: absolute;+ z-index: 5;+ inset-inline-end: 12px;++ width: min(280px, 76%);+ padding: 12px;++ /* No frame: an elevated surface is the whole affordance, the way Figma's+ comments read. A 1px box around content that already sits in a box is+ what made the earlier rounds look like wireframes. */+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgElevated};+ box-shadow: ${cssVar.boxShadowSecondary};++ /* 920px reading column + 240px note + gaps — the point where the margin+ can hold the note without the page growing a horizontal scrollbar. */+ @media (width >= 1440px) {+ inset-inline: calc(100% + 12px) auto;+ width: 240px;+ }+ `,+ noteFallbackHead: css`+ padding-block-end: 4px;+ `,+ /**+ * The collapsed pin: while a note is shut there has to be something in the+ * margin saying it exists, or the only way to find a remark is to hunt for+ * the marker on the box it points at.+ */+ pin: css`+ cursor: pointer;++ position: absolute;+ z-index: 4;+ inset-inline-end: -14px;++ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 24px;+ height: 24px;+ border: none;+ border-radius: 50% 50% 50% 2px;++ color: ${cssVar.colorTextLightSolid};++ box-shadow: ${cssVar.boxShadowTertiary};++ &:hover {+ filter: brightness(1.12);+ }++ @media (width >= 1440px) {+ inset-inline: calc(100% + 12px) auto;+ }+ `,+ /** Positioning context for the floating note; the frame itself clips. */+ stage: css`+ position: relative;+ `,+ noteBody: css`+ font-size: 13px;+ line-height: 1.6;+ overflow-wrap: anywhere;+ white-space: pre-wrap;+ `,rect: css`pointer-events: none;position: absolute;border: 2px solid ${cssVar.colorError};- border-radius: 4px;+ border-radius: ${cssVar.borderRadiusXS};- box-shadow: 0 0 0 1px rgb(0 0 0 / 25%);+ box-shadow: 0 0 0 1px ${cssVar.colorFillSecondary};+ `,+ swatch: css`+ flex: none;+ width: 8px;+ height: 8px;+ border-radius: 50%;`,}));+interface OverlayRectProps {+ annotation: EvidenceOverlay;+ /** Index within the whole image, so the marker and the note agree. */+ index: number;+ numbered: boolean;+ onToggle: (index: number) => void;+ opened: boolean;+ /** Region geometry for THIS tile — a sliced screenshot clips it per tile. */+ rect: EvidenceOverlay['rect'];+}++const OverlayRect = memo<OverlayRectProps>(+ ({ annotation, index, numbered, onToggle, opened, rect }) => {+ // A settled region keeps its place but drops its author's colour: an+ // answered note should not compete with an open one for attention.+ const color = annotation.resolved+ ? cssVar.colorTextQuaternary+ : (annotation.color ?? cssVar.colorError);+ const label = annotation.label ?? index + 1;+ return (+ <div+ className={styles.rect}+ style={{+ borderColor: color,+ height: `${rect.height * 100}%`,+ left: `${rect.x * 100}%`,+ top: `${rect.y * 100}%`,+ width: `${rect.width * 100}%`,+ }}+ >+ {numbered && (+ <span className={styles.badge} style={{ background: color }}>+ {label}+ </span>+ )}+ {annotation.comment && (+ <button+ className={cx(styles.marker, opened && styles.markerActive)}+ style={{ background: color }}+ title={annotation.authorName}+ type={'button'}+ onClick={() => onToggle(index)}+ >+ <Icon icon={annotation.resolved ? Check : MessageSquare} size={10} />+ </button>+ )}+ </div>+ );+ },+);++OverlayRect.displayName = 'AcceptanceOverlayRect';+interface ScreenshotTilesProps {alt: string;- annotations?: { comment?: string; label?: number; rect: Rect }[];+ annotations?: EvidenceOverlay[];caption?: ReactNode;fileHeight?: number | null;fileWidth?: number | null;@@ -78,10 +252,14 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(const [natural, setNatural] = useState(fileWidth && fileHeight ? { height: fileHeight, width: fileWidth } : undefined,);+ const [openedNote, setOpenedNote] = useState<number>();const slices = natural ? screenshotSlices(natural.width, natural.height) : undefined;const numbered =(annotations?.length ?? 0) > 1 || annotations?.some((item) => item.label !== undefined);+ const toggleNote = (index: number) =>+ setOpenedNote((current) => (current === index ? undefined : index));+ const opened = openedNote === undefined ? undefined : annotations?.[openedNote];const rememberSize = (event: { currentTarget: HTMLImageElement }) => {if (natural) return;@@ -91,9 +269,60 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(});};+ // Pinned near the region it belongs to, but never so low that the panel+ // hangs off the bottom of the image.+ const note = opened && (+ <div+ className={styles.note}+ style={{ insetBlockStart: `${Math.min(Math.max(opened.rect.y, 0), 0.62) * 100}%` }}+ >+ {opened.panel ?? (+ <Flexbox gap={4}>+ <Flexbox horizontal align={'center'} className={styles.noteFallbackHead} gap={6}>+ <span+ className={styles.swatch}+ style={{ background: opened.color ?? cssVar.colorError }}+ />+ <Text fontSize={12} type={'secondary'}>+ {numbered ? `${opened.label ?? openedNote! + 1} · ` : ''}+ {opened.authorName}+ </Text>+ </Flexbox>+ <div className={styles.noteBody}>{opened.comment}</div>+ </Flexbox>+ )}+ </div>+ );++ const pins =+ openedNote === undefined &&+ annotations?.map((annotation, index) =>+ annotation.comment ? (+ <button+ className={styles.pin}+ key={index}+ title={annotation.authorName}+ type={'button'}+ style={{+ background: annotation.resolved+ ? cssVar.colorTextQuaternary+ : (annotation.color ?? cssVar.colorError),+ insetBlockStart: `${Math.min(Math.max(annotation.rect.y, 0), 0.86) * 100}%`,+ }}+ onClick={() => toggleNote(index)}+ >+ <Icon icon={annotation.resolved ? Check : MessageSquare} size={12} />+ </button>+ ) : null,+ );+const shell = (width: string | number, body: ReactNode) => (<Flexbox gap={4} style={{ maxWidth: '100%', width }}>- {body}+ <div className={styles.stage}>+ {body}+ {pins}+ {note}+ </div>{caption}</Flexbox>);@@ -127,7 +356,7 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(?.map((annotation, index) => {const rect = annotationInSlice(annotation.rect, slice, natural.height);if (!rect) return;- return { ...annotation, index, rect };+ return { annotation, index, rect };}).filter((item) => item !== undefined);@@ -160,23 +389,16 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(wrapper: { height: '100%', width: '100%' },}}/>- {local?.map((annotation) => (- <div- className={styles.rect}- key={annotation.index}- style={{- height: `${annotation.rect.height * 100}%`,- left: `${annotation.rect.x * 100}%`,- top: `${annotation.rect.y * 100}%`,- width: `${annotation.rect.width * 100}%`,- }}- >- {numbered && (- <span className={styles.badge}>- {annotation.label ?? annotation.index + 1}- </span>- )}- </div>+ {local?.map((item) => (+ <OverlayRect+ annotation={item.annotation}+ index={item.index}+ key={item.index}+ numbered={Boolean(numbered)}+ opened={openedNote === item.index}+ rect={item.rect}+ onToggle={toggleNote}+ />))}</div>);@@ -209,18 +431,15 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(width={'100%'}/>{annotations?.map((annotation, index) => (- <div- className={styles.rect}+ <OverlayRect+ annotation={annotation}+ index={index}key={index}- style={{- height: `${annotation.rect.height * 100}%`,- left: `${annotation.rect.x * 100}%`,- top: `${annotation.rect.y * 100}%`,- width: `${annotation.rect.width * 100}%`,- }}- >- {numbered && <span className={styles.badge}>{annotation.label ?? index + 1}</span>}- </div>+ numbered={Boolean(numbered)}+ opened={openedNote === index}+ rect={annotation.rect}+ onToggle={toggleNote}+ />))}</div>,);diff --git a/src/features/Acceptance/Viewer/Evidence/overlay.ts b/src/features/Acceptance/Viewer/Evidence/overlay.tsnew file mode 100644index 00000000000..18cbe6be209--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/overlay.ts@@ -0,0 +1,33 @@+import type { AcceptanceReviewAnnotation } from '@lobechat/types';+import type { ReactNode } from 'react';++/**+ * A region drawn over an evidence image by someone other than the renderer:+ * a model proposal, or a reviewer's circled comment.+ *+ * `color` and `authorName` are what make several people's marks on one+ * screenshot tellable apart; `comment` is what the marker reveals when clicked.+ */+export interface EvidenceOverlay {+ /** Rendered next to the note when the marker is opened. */+ authorName?: string;+ /** Author colour — border, badge and marker share it. Falls back to the error red. */+ color?: string;+ comment?: string;+ /**+ * Overrides the badge number. Regions belonging to one review may be spread+ * across several images, and per-image numbering would restart at 1 on each.+ */+ label?: number;+ /**+ * What the floating note shows when the marker is opened. A caller that owns+ * a whole discussion thread passes it here; without one the note falls back+ * to `authorName` plus `comment`.+ */+ panel?: ReactNode;+ rect: AcceptanceReviewAnnotation['rect'];+ /** A handled thread reads as settled rather than an open concern. */+ resolved?: boolean;+}++export type EvidenceOverlayMap = Map<string, EvidenceOverlay[]>;diff --git a/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts b/src/features/Acceptance/Viewer/Flow/flowNavigation.test.tsindex a36f2a06353..f6ee00fd2c7 100644--- a/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts+++ b/src/features/Acceptance/Viewer/Flow/flowNavigation.test.ts@@ -10,6 +10,11 @@ describe('acceptance flow navigation', () => {expect(resolveAcceptanceTab('flow', 2)).toBe('flow');expect(resolveAcceptanceTab('resources', 0)).toBe('resources');});+ it('opens the discussion only when asked, never as the landing tab', () => {+ expect(resolveAcceptanceTab('discussion', 0)).toBe('discussion');+ expect(resolveAcceptanceTab('discussion', 3, true, false)).toBe('discussion');+ expect(resolveAcceptanceTab(undefined, 0)).toBe('checks');+ });});const makeFlows = () =>diff --git a/src/features/Acceptance/Viewer/Flow/flowNavigation.ts b/src/features/Acceptance/Viewer/Flow/flowNavigation.tsindex 0d10f9e0549..3b767c60cef 100644--- a/src/features/Acceptance/Viewer/Flow/flowNavigation.ts+++ b/src/features/Acceptance/Viewer/Flow/flowNavigation.ts@@ -13,6 +13,11 @@ export const getFlowNodeCount = (flows: Bundle['flows'] = []) =>0,);+/**+ * Which face to show. Discussion leads the tab strip but is never the landing+ * tab: an acceptance opens on what has to be judged, not on a thread that is+ * usually still empty.+ */export const resolveAcceptanceTab = (tab: AcceptanceTabKey | undefined,nodeCount: number,diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceTabs.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceTabs.tsxindex 5102e33bcc2..2701e8af1f1 100644--- a/src/features/Acceptance/Viewer/Header/AcceptanceTabs.tsx+++ b/src/features/Acceptance/Viewer/Header/AcceptanceTabs.tsx@@ -3,10 +3,10 @@import { Flexbox, Icon } from '@lobehub/ui';import { Tabs, Tag } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';-import { ListChecks, Paperclip, Route } from 'lucide-react';+import { ListChecks, MessagesSquare, Paperclip, Route } from 'lucide-react';import { useTranslation } from 'react-i18next';-export type AcceptanceTabKey = 'checks' | 'resources' | 'flow';+export type AcceptanceTabKey = 'checks' | 'discussion' | 'resources' | 'flow';const styles = createStaticStyles(({ css }) => ({// The square variant underlines its whole list; the band below already draws@@ -21,25 +21,38 @@ const styles = createStaticStyles(({ css }) => ({interface AcceptanceTabsProps {active: AcceptanceTabKey;checkCount: number;+ /** Open discussion threads on this delivery. */+ discussionCount: number;flowCount?: number;onChange: (key: AcceptanceTabKey) => void;resourceCount: number;}/**- * The delivery's two faces: the checks a person judges, and the artefacts the- * rounds produced. They close the identity band; the active tab's underline is- * the boundary between "what this delivery is" and "what you are looking at".+ * The delivery's faces: the conversation about it, the checks a person judges,+ * and the artefacts the rounds produced. They close the identity band; the+ * active tab's underline is the boundary between "what this delivery is" and+ * "what you are looking at".+ *+ * Discussion leads, as GitHub's Conversation does — it is the delivery's+ * shared thread, and it was unfindable while it sat below the checklist.*/const AcceptanceTabs = ({active,checkCount,+ discussionCount,flowCount = 0,onChange,resourceCount,}: AcceptanceTabsProps) => {const { t } = useTranslation('verify');const tabs = [+ {+ count: discussionCount,+ icon: MessagesSquare,+ key: 'discussion' as const,+ label: t('acceptance.comments.title'),+ },{count: checkCount,icon: ListChecks,diff --git a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsxindex b00b11eda36..19f7986ead6 100644--- a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx+++ b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx@@ -15,6 +15,7 @@ import { verifyService } from '@/services/verify';import { useAcceptanceScope } from '../AcceptanceScope';import { checkFilterState, isException } from '../Checks/checkState';import { buildRepairPrompt } from '../Checks/checkWork';+import { useAcceptanceComments } from '../Comments/hooks';import { flowPlanPhase } from '../Plan/planReview';import { acceptanceCheckPath } from '../routes';import { useAcceptanceBundle } from '../useAcceptanceBundle';@@ -38,6 +39,7 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {const { turn, setTurn } = useAcceptanceTurn(embedded);const [pending, setPending] = useState(false);const [feedbackOpen, setFeedbackOpen] = useState(false);+ const { approvals } = useAcceptanceComments(acceptanceId);if (!data || !canReviewAcceptance(data) || data.acceptance.status === 'closed') return null;if (flowPlanPhase(data.rounds.at(-1))) return null;@@ -116,6 +118,19 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {},}[barState];+ // Teammates' approvals ride along the state line: they are opinions the+ // decider reads, never the decision itself. Only this round's count — an+ // approval given to round 1 says nothing about round 2, and the reviewer's+ // own card already asks them to look again, so counting it here would tell+ // the decider the opposite of what the reviewer is being shown.+ const approvalText = (() => {+ const roundIndex = currentRound?.run.roundIndex;+ if (roundIndex === undefined) return undefined;+ const count = approvals.filter((approval) => approval.contextRoundIndex === roundIndex).length;+ return count > 0 ? t('acceptance.comments.approvalCount', { count }) : undefined;+ })();+ const subTextWithApprovals = [barTexts.subText, approvalText].filter(Boolean).join(' · ');+const currentRoundIndex = currentRound?.run.roundIndex ?? 0;const groupFeedbackEntries = rounds.flatMap((round) =>(round.run.decisionDetail?.groupFeedback ?? []).map((entry) => ({@@ -183,7 +198,7 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {rerunPending={false}state={barState}statusText={barTexts.statusText}- subText={barTexts.subText}+ subText={subTextWithApprovals || undefined}totalCount={reviewTotal}onOpenFeedback={() => setFeedbackOpen(true)}onAccept={() =>diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 1f6436dc20e..88ec1397dce 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -176,6 +176,14 @@ export const topicCommentKeys = {]),};+// ---- acceptance comment -------------------------------------------------+export const acceptanceCommentKeys = {+ list: def('acceptanceComment:list', (acceptanceId: string) => [+ 'acceptanceComment:list',+ acceptanceId,+ ]),+};+// ---- document comment ---------------------------------------------------export const documentCommentKeys = {detail: def('documentComment:detail', (workspaceId: string | null, commentId: string) => [@@ -1482,6 +1490,7 @@ export const swrKeys = {tool: toolKeys,topic: topicKeys,topicComment: topicCommentKeys,+ acceptanceComment: acceptanceCommentKeys,documentComment: documentCommentKeys,documentLike: documentLikeKeys,topicAction: topicActionKeys,diff --git a/src/services/acceptanceComment.ts b/src/services/acceptanceComment.tsnew file mode 100644index 00000000000..cd296cd8962--- /dev/null+++ b/src/services/acceptanceComment.ts@@ -0,0 +1,21 @@+import type { AcceptanceCommentList, CreateAcceptanceCommentInput } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++class AcceptanceCommentService {+ create = (input: CreateAcceptanceCommentInput) =>+ lambdaClient.acceptanceComment.create.mutate(input);++ delete = (id: string) => lambdaClient.acceptanceComment.delete.mutate({ id });++ list = (acceptanceId: string): Promise<AcceptanceCommentList> =>+ lambdaClient.acceptanceComment.list.query({ acceptanceId });++ react = (id: string, emoji: string, on: boolean) =>+ lambdaClient.acceptanceComment.react.mutate({ emoji, id, on });++ setResolved = (id: string, resolved: boolean) =>+ lambdaClient.acceptanceComment.setResolved.mutate({ id, resolved });+}++export const acceptanceCommentService = new AcceptanceCommentService();