Skip to content

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

✨ feat(acceptance): add independent video frame comments (#21328)

Bryancbd4d80712ec
diff --git a/apps/cli/src/commands/acceptance/commentFeedback.ts b/apps/cli/src/commands/acceptance/commentFeedback.ts
index 4ed77ab4597..c6e4a4afd5e 100644
--- a/apps/cli/src/commands/acceptance/commentFeedback.ts
+++ b/apps/cli/src/commands/acceptance/commentFeedback.ts
@@ -26,7 +26,12 @@ export const collectCommentFeedback = (
const check = root.checkItemId ? checksById.get(root.checkItemId) : undefined;
const annotation =
root.evidenceId && root.rect
- ? { comment: item.content, evidenceId: root.evidenceId, rect: root.rect }
+ ? {
+ comment: item.content,
+ evidenceId: root.evidenceId,
+ rect: root.rect,
+ ...(root.time ? { time: root.time } : {}),
+ }
: undefined;
const page = root.source
? {
diff --git a/apps/cli/src/commands/acceptance/index.feedback.test.ts b/apps/cli/src/commands/acceptance/index.feedback.test.ts
index 3fd8de66077..4b2754ce73a 100644
--- a/apps/cli/src/commands/acceptance/index.feedback.test.ts
+++ b/apps/cli/src/commands/acceptance/index.feedback.test.ts
@@ -365,3 +365,17 @@ it('records where the delivery is deployed for preview review', async () => {
url: 'https://pr-12.example.com/',
});
});
+
+it('includes video time for the root and its replies in actionable feedback', async () => {
+ listComments.mockResolvedValue({
+ items: [
+ comment('video-root', { time: { start: 1.25 } }),
+ comment('video-reply', { parentCommentId: 'video-root', evidenceId: null, rect: null }),
+ ],
+ });
+ const result = await feedback('--json');
+ const video = result.entries.filter((item: { kind: string }) => item.kind === 'comment');
+ expect(video).toHaveLength(2);
+ expect(video[0].annotations[0].time).toEqual({ start: 1.25 });
+ expect(video[1].annotations[0].time).toEqual({ start: 1.25 });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts b/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts
index faeb431da17..a995cad4acb 100644
--- a/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts
@@ -3,12 +3,15 @@ import { randomUUID } from 'node:crypto';
import { type LobeChatDatabase } from '@lobechat/database';
import {
+ acceptanceComments,
acceptances,
verifyCheckResults,
+ verifyCriteria,
verifyEvidence,
verifyRuns,
} from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { acceptanceCommentRouter } from '../acceptanceComment';
@@ -146,4 +149,266 @@ describe('acceptanceCommentRouter create reference scoping', () => {
expect(data).toMatchObject({ contextRoundIndex: 1, evidenceId: ownEvidenceId });
});
+ it.each(['screenshot', 'video'] as const)(
+ 'keeps the viewing round when commenting on inherited %s evidence',
+ async (type) => {
+ await serverDB
+ .update(verifyEvidence)
+ .set({ type })
+ .where(eq(verifyEvidence.id, ownEvidenceId));
+ const [viewingRun] = await serverDB
+ .insert(verifyRuns)
+ .values({
+ acceptanceId,
+ roundIndex: 2,
+ userId: ownerId,
+ })
+ .returning();
+ const { data } = await caller(ownerId).create({
+ acceptanceId,
+ anchor: {
+ checkItemId: 'c1',
+ evidenceId: ownEvidenceId,
+ rect,
+ ...(type === 'video' ? { time: { start: 1.25 } } : {}),
+ },
+ clientId: randomUUID(),
+ content: 'comment on inherited evidence while viewing round two',
+ contextRunId: viewingRun.id,
+ });
+ expect(data).toMatchObject({ contextRoundIndex: 2, evidenceId: ownEvidenceId });
+ const [stored] = await serverDB
+ .select()
+ .from(acceptanceComments)
+ .where(eq(acceptanceComments.id, data.id));
+ expect(stored.contextRunId).toBe(viewingRun.id);
+ expect(stored.evidenceId).toBe(ownEvidenceId);
+ },
+ );
+
+ it('rejects a foreign viewing round even when the evidence belongs to this acceptance', async () => {
+ await expect(
+ caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: ownEvidenceId, rect },
+ clientId: randomUUID(),
+ content: 'foreign round with local evidence',
+ contextRunId: foreignRunId,
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it.each(['screenshot', 'gif', 'video'] as const)(
+ 'keeps flow occurrence identity for %s comments, including inherited evidence',
+ async (type) => {
+ const [asset] = await serverDB
+ .insert(verifyCriteria)
+ .values({ title: 'Shared criterion', verifierType: 'agent', userId: ownerId })
+ .returning();
+ const assetId = asset.id;
+ const occurrenceId = 'node:branch';
+ const otherOccurrenceId = 'node:other-branch';
+ await serverDB
+ .update(verifyRuns)
+ .set({
+ plan: [occurrenceId, otherOccurrenceId].map((id, index) => ({
+ id,
+ index,
+ title: 'Shared flow criterion',
+ onFail: 'manual' as const,
+ verifierType: 'agent' as const,
+ verifierConfig: {},
+ required: true,
+ sourceCriterionId: assetId,
+ sourceFlowNode: { flowId: 'flow', nodeId: 'node', incomingEdgeId: id },
+ })),
+ })
+ .where(eq(verifyRuns.id, ownRunId));
+ const [evidence] = await serverDB
+ .select()
+ .from(verifyEvidence)
+ .where(eq(verifyEvidence.id, ownEvidenceId));
+ await serverDB
+ .update(verifyCheckResults)
+ .set({ checkItemId: occurrenceId, sourceCriterionId: assetId })
+ .where(eq(verifyCheckResults.id, evidence.checkResultId));
+ await serverDB
+ .update(verifyEvidence)
+ .set({ type })
+ .where(eq(verifyEvidence.id, ownEvidenceId));
+ // The viewing round need not contain the original flow plan.
+ const [viewingRun] = await serverDB
+ .insert(verifyRuns)
+ .values({ acceptanceId, roundIndex: 2, userId: ownerId })
+ .returning();
+ const input = {
+ acceptanceId,
+ anchor: {
+ checkItemId: occurrenceId,
+ evidenceId: ownEvidenceId,
+ rect,
+ ...(type === 'video' ? { time: { start: 1.25 } } : {}),
+ },
+ clientId: randomUUID(),
+ content: 'Feedback on this flow occurrence',
+ contextRunId: viewingRun.id,
+ };
+ const { data } = await caller(ownerId).create(input);
+ expect(data).toMatchObject({
+ checkItemId: occurrenceId,
+ contextRoundIndex: 2,
+ evidenceId: ownEvidenceId,
+ });
+ const [stored] = await serverDB
+ .select()
+ .from(acceptanceComments)
+ .where(eq(acceptanceComments.id, data.id));
+ expect(stored).toMatchObject({ checkItemId: occurrenceId, contextRunId: viewingRun.id });
+ for (const checkItemId of [assetId, otherOccurrenceId]) {
+ await expect(
+ caller(ownerId).create({
+ ...input,
+ anchor: { ...input.anchor, checkItemId },
+ clientId: randomUUID(),
+ }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Evidence belongs to another check',
+ });
+ }
+ },
+ );
+
+ it('uses the criterion identity for non-flow evidence', async () => {
+ const [criterion] = await serverDB
+ .insert(verifyCriteria)
+ .values({ title: 'Ordinary criterion', verifierType: 'agent', userId: ownerId })
+ .returning();
+ const criterionId = criterion.id;
+ await serverDB
+ .update(verifyRuns)
+ .set({
+ plan: [
+ {
+ id: 'c1',
+ index: 0,
+ title: 'Ordinary check',
+ onFail: 'manual',
+ verifierType: 'agent',
+ verifierConfig: {},
+ required: true,
+ sourceCriterionId: criterionId,
+ },
+ ],
+ })
+ .where(eq(verifyRuns.id, ownRunId));
+ await serverDB
+ .update(verifyCheckResults)
+ .set({ sourceCriterionId: criterionId })
+ .where(eq(verifyCheckResults.verifyRunId, ownRunId));
+ const { data } = await caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: criterionId, evidenceId: ownEvidenceId, rect },
+ clientId: randomUUID(),
+ content: 'Ordinary criterion feedback',
+ });
+ expect(data.checkItemId).toBe(criterionId);
+ await expect(
+ caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: ownEvidenceId, rect },
+ clientId: randomUUID(),
+ content: 'Wrong physical ID',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('round-trips a video frame and keeps repeated sends idempotent', async () => {
+ await serverDB
+ .update(verifyEvidence)
+ .set({ type: 'video' })
+ .where(eq(verifyEvidence.id, ownEvidenceId));
+ const input = {
+ acceptanceId,
+ anchor: {
+ checkItemId: 'c1',
+ evidenceId: ownEvidenceId,
+ rect,
+ time: { start: 1.25 },
+ },
+ clientId: `video-${randomUUID()}`,
+ content: 'this part needs explanation',
+ contextRunId: ownRunId,
+ };
+ const first = await caller(ownerId).create(input);
+ const retry = await caller(ownerId).create(input);
+ expect(first.data.time).toEqual({ start: 1.25 });
+ const [stored] = await serverDB
+ .select()
+ .from(acceptanceComments)
+ .where(eq(acceptanceComments.id, first.data.id));
+ expect(stored.metadata).toEqual({
+ evidenceAnchor: { time: { start: 1.25 } },
+ });
+ expect(retry.data.id).toBe(first.data.id);
+ const list = await caller(ownerId).list({ acceptanceId });
+ expect(list.items.find((item) => item.id === first.data.id)?.time).toEqual(input.anchor.time);
+ const [run] = await serverDB.select().from(verifyRuns).where(eq(verifyRuns.id, ownRunId));
+ expect(run.userDecision).toBeNull();
+ });
+
+ it.each([undefined, { start: -1 }, { start: 'bad' }])(
+ 'does not expose invalid time from malformed metadata: %j',
+ async (time) => {
+ const { data } = await caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: ownEvidenceId, rect },
+ clientId: randomUUID(),
+ content: 'original image comment',
+ });
+ expect(data.time).toBeNull();
+ // Seed malformed stored JSON directly rather
+ // than weakening the new metadata contract to admit these values.
+ await serverDB
+ .update(acceptanceComments)
+ .set({ metadata: sql`${JSON.stringify({ evidenceAnchor: { time } })}::jsonb` })
+ .where(eq(acceptanceComments.id, data.id));
+ const list = await caller(ownerId).list({ acceptanceId });
+ expect(list.items.find((item) => item.id === data.id)).toMatchObject({
+ time: null,
+ rect,
+ content: 'original image comment',
+ });
+ },
+ );
+
+ it('rejects a video time on an image and a mismatched check', async () => {
+ const input = {
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: ownEvidenceId, rect, time: { start: 1 } },
+ clientId: randomUUID(),
+ content: 'bad anchor',
+ };
+ await expect(caller(ownerId).create(input)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ await expect(
+ caller(ownerId).create({
+ ...input,
+ anchor: { ...input.anchor, checkItemId: 'c2', time: undefined },
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it.each([{ start: -1 }, { start: NaN }, { start: Infinity }])(
+ 'rejects invalid time %j',
+ async (time) => {
+ await expect(
+ caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: ownEvidenceId, rect, time },
+ clientId: randomUUID(),
+ content: 'invalid',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ },
+ );
});
diff --git a/apps/server/src/routers/lambda/acceptanceComment.ts b/apps/server/src/routers/lambda/acceptanceComment.ts
index 06ba43413e6..9e6ea18fadb 100644
--- a/apps/server/src/routers/lambda/acceptanceComment.ts
+++ b/apps/server/src/routers/lambda/acceptanceComment.ts
@@ -5,7 +5,7 @@ import type {
AcceptanceCommentList,
AcceptanceCommentReaction,
} from '@lobechat/types';
-import { reviewAnchorSchema } from '@lobechat/types';
+import { acceptanceCommentTimeSchema, reviewAnchorSchema } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { and, eq, inArray, isNull } from 'drizzle-orm';
import { z } from 'zod';
@@ -50,6 +50,7 @@ const createSchema = z
checkItemId: z.string().min(1).max(255),
evidenceId: z.string().uuid(),
rect: rectSchema,
+ time: acceptanceCommentTimeSchema.optional(),
})
.optional(),
attachments: z
@@ -269,6 +270,12 @@ const enrich = async (
return rest;
};
+ const timeOf = (row: AcceptanceCommentRow) => {
+ if (row.anchorType !== 'evidence') return null;
+ const parsed = acceptanceCommentTimeSchema.safeParse(row.metadata?.evidenceAnchor?.time);
+ return parsed.success ? parsed.data : null;
+ };
+
return rows
.filter((row) => row.kind !== 'reaction')
.map((row) => ({
@@ -299,6 +306,7 @@ const enrich = async (
parentCommentId: row.parentCommentId,
reactions: [...(reactionsByComment.get(row.id)?.values() ?? [])],
rect: row.anchorRect,
+ time: timeOf(row),
resolvedAt: row.resolvedAt,
resolvedByUserId: row.resolvedByUserId,
source: sourceOf(row),
@@ -365,7 +373,10 @@ const assertAuthorAgentUsable = async (
const assertReferencesBelongToAcceptance = async (
db: LobeChatDatabase,
acceptanceId: string,
- refs: { evidenceId?: string; runId?: string },
+ refs: {
+ anchor?: { evidenceId: string; checkItemId: string; time?: { start: number } };
+ runId?: string;
+ },
) => {
if (refs.runId) {
const [run] = await db
@@ -376,15 +387,46 @@ const assertReferencesBelongToAcceptance = async (
if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Round not found' });
}
- if (refs.evidenceId) {
+ if (refs.anchor) {
const [evidence] = await db
- .select({ id: verifyEvidence.id })
+ .select({
+ id: verifyEvidence.id,
+ type: verifyEvidence.type,
+ checkItemId: verifyCheckResults.checkItemId,
+ sourceCriterionId: verifyCheckResults.sourceCriterionId,
+ runId: verifyRuns.id,
+ plan: verifyRuns.plan,
+ })
.from(verifyEvidence)
.innerJoin(verifyCheckResults, eq(verifyCheckResults.id, verifyEvidence.checkResultId))
.innerJoin(verifyRuns, eq(verifyRuns.id, verifyCheckResults.verifyRunId))
- .where(and(eq(verifyEvidence.id, refs.evidenceId), eq(verifyRuns.acceptanceId, acceptanceId)))
+ .where(
+ and(
+ eq(verifyEvidence.id, refs.anchor.evidenceId),
+ eq(verifyRuns.acceptanceId, acceptanceId),
+ ),
+ )
.limit(1);
if (!evidence) throw new TRPCError({ code: 'NOT_FOUND', message: 'Evidence not found' });
+ // Use the producing round's snapshot, even when the viewer is in a later round.
+ // Flow occurrences may share a criterion but remain distinct checks in the union.
+ const item = evidence.plan?.find((item) => item.id === evidence.checkItemId);
+ const checkId = item?.sourceFlowNode
+ ? item.id
+ : (item?.sourceCriterionId ?? evidence.sourceCriterionId ?? evidence.checkItemId);
+ if (checkId !== refs.anchor.checkItemId)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Evidence belongs to another check' });
+ if (!['screenshot', 'gif', 'video'].includes(evidence.type))
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'This evidence cannot carry a media anchor',
+ });
+ if (Boolean(refs.anchor.time) !== (evidence.type === 'video'))
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Video anchors require a time; images have no time',
+ });
+ return evidence.runId;
}
};
@@ -420,10 +462,14 @@ export const acceptanceCommentRouter = router({
{ userId: ctx.userId, workspaceId: access.memberOfWorkspaceId },
input.authorAgentId,
);
- await assertReferencesBelongToAcceptance(ctx.serverDB, access.acceptance.id, {
- evidenceId: input.anchor?.evidenceId,
- runId: input.contextRunId,
- });
+ const evidenceRunId = await assertReferencesBelongToAcceptance(
+ ctx.serverDB,
+ access.acceptance.id,
+ {
+ anchor: input.anchor,
+ runId: input.contextRunId,
+ },
+ );
try {
const { comment } = await ctx.acceptanceCommentModel.create({
@@ -434,7 +480,8 @@ export const acceptanceCommentRouter = router({
authorUserId: ctx.userId,
clientId: input.clientId,
content: input.content,
- contextRunId: input.contextRunId,
+ // Inherited evidence keeps its producing run; the comment belongs to the viewing run.
+ contextRunId: input.contextRunId ?? evidenceRunId,
editorData: input.editorData as never,
kind: input.kind,
parentCommentId: input.parentCommentId,
diff --git a/apps/workbench/src/entry.tsx b/apps/workbench/src/entry.tsx
index 16c0fc8ae14..bef20166cea 100644
--- a/apps/workbench/src/entry.tsx
+++ b/apps/workbench/src/entry.tsx
@@ -1,3 +1,4 @@
+import '@/styles/stylex.css';
import '@/spa/initialize';
import { RouterProvider } from 'react-router/dom';
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index bddd3c0a185..baf005a7de4 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -102,7 +102,7 @@
"acceptance.comments.checkRejectedRegions": "{{count}} marked region(s)",
"acceptance.comments.collapseThread": "Collapse",
"acceptance.comments.commentEvidence": "Comment on a region",
- "acceptance.comments.commentThisEvidence": "Comment on this screenshot",
+ "acceptance.comments.commentMedia": "Comment on this evidence",
"acceptance.comments.commented": "commented {{time}}",
"acceptance.comments.copyLink": "Copy link",
"acceptance.comments.copyLinkHint": "{{time}} · click to copy this comment’s link",
@@ -111,9 +111,23 @@
"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.draftEmptyTitle": "Circle what you mean",
+ "acceptance.comments.draftNeedsRegion": "Circle an area to start a comment",
+ "acceptance.comments.draftNeedsText": "Comment {{index}} needs text",
+ "acceptance.comments.draftNumber": "Comment {{index}}",
+ "acceptance.comments.draftPlaceholder": "Write a comment about this area…",
+ "acceptance.comments.draftRemove": "Remove comment {{index}}",
+ "acceptance.comments.draftRemoved": "Comment {{index}} removed",
+ "acceptance.comments.draftSaved": "Drafts are saved on this device",
+ "acceptance.comments.draftsTitle": "New comments",
+ "acceptance.comments.draftsUnsent": "{{count}} comment(s) not sent. Your text is kept — send again.",
"acceptance.comments.empty": "No discussion yet.",
+ "acceptance.comments.evidenceDrafts": "{{count}} unsent",
"acceptance.comments.evidenceFromRound": "Evidence from round {{round}} — replaced in a later round",
+ "acceptance.comments.evidenceModalTitle": "Comment on evidence",
+ "acceptance.comments.evidenceNumber": "Evidence {{index}}",
"acceptance.comments.evidenceThisRound": "Current evidence for this check",
+ "acceptance.comments.evidenceUnavailable": "This evidence is no longer available.",
"acceptance.comments.historicalRegions": "{{count}} region note(s) on evidence replaced by a later round",
"acceptance.comments.linkCopied": "Link copied",
"acceptance.comments.loadFailed": "Failed to load the discussion. Please refresh.",
@@ -141,12 +155,19 @@
"acceptance.comments.roundRejected": "Round {{round}} delivery sent back",
"acceptance.comments.sectionMessages": "{{count}} message(s)",
"acceptance.comments.send": "Send",
+ "acceptance.comments.sendCount": "Send {{count}} comments",
"acceptance.comments.signIn": "Sign in",
"acceptance.comments.signInDescription": "Sign in to comment, reply, and mark up screenshots.",
"acceptance.comments.signInTitle": "Join the discussion",
"acceptance.comments.signUp": "Sign up",
"acceptance.comments.title": "Discussion",
+ "acceptance.comments.undo": "Undo",
"acceptance.comments.updateFailed": "Failed to update the comment. Please try again.",
+ "acceptance.comments.video.emptyBody": "Pause on any frame and drag over the video. Each area you circle becomes its own comment, so you can mark several moments before sending.",
+ "acceptance.comments.video.hintPaused": "Drag to circle an area · frame {{frame}}",
+ "acceptance.comments.video.hintPlaying": "Press to pause, then drag to circle",
+ "acceptance.comments.video.listTitle": "{{count}} comment(s) on this video",
+ "acceptance.comments.video.showFrame": "Show the frame at {{time}}",
"acceptance.comments.withdraw": "Withdraw approval",
"acceptance.comments.withdrawDescription": "You can withdraw or re-approve any time while the round is open. Only your status when the owner decides counts.",
"acceptance.comments.youApproved": "You approved round {{round}}",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 54eb724f1b8..1aa6398fe8a 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -102,7 +102,7 @@
"acceptance.comments.checkRejectedRegions": "圈注了 {{count}} 处",
"acceptance.comments.collapseThread": "收起",
"acceptance.comments.commentEvidence": "圈选评论",
- "acceptance.comments.commentThisEvidence": "评论这张截图",
+ "acceptance.comments.commentMedia": "评论此证据",
"acceptance.comments.commented": "评论于 {{time}}",
"acceptance.comments.copyLink": "复制链接",
"acceptance.comments.copyLinkHint": "{{time}} · 点一下复制这条评论的链接",
@@ -111,9 +111,23 @@
"acceptance.comments.deleteConfirm": "删除这条评论?",
"acceptance.comments.deleteFailed": "评论删除失败,请重试。",
"acceptance.comments.deleted": "该评论已删除",
+ "acceptance.comments.draftEmptyTitle": "圈出你想说的地方",
+ "acceptance.comments.draftNeedsRegion": "先圈出一个区域,再写评论",
+ "acceptance.comments.draftNeedsText": "评论 {{index}} 还没有内容",
+ "acceptance.comments.draftNumber": "评论 {{index}}",
+ "acceptance.comments.draftPlaceholder": "写下对这块区域的评论…",
+ "acceptance.comments.draftRemove": "删除评论 {{index}}",
+ "acceptance.comments.draftRemoved": "已删除评论 {{index}}",
+ "acceptance.comments.draftSaved": "草稿已保存在此设备",
+ "acceptance.comments.draftsTitle": "新评论",
+ "acceptance.comments.draftsUnsent": "{{count}} 条评论未发送,内容已保留,请重新发送。",
"acceptance.comments.empty": "还没有讨论。",
+ "acceptance.comments.evidenceDrafts": "{{count}} 条未发送",
"acceptance.comments.evidenceFromRound": "第 {{round}} 轮的证据,后续轮次已替换",
+ "acceptance.comments.evidenceModalTitle": "评论证据",
+ "acceptance.comments.evidenceNumber": "证据 {{index}}",
"acceptance.comments.evidenceThisRound": "该检查项当前展示的证据",
+ "acceptance.comments.evidenceUnavailable": "该证据已不可用。",
"acceptance.comments.historicalRegions": "{{count}} 条圈选评论指向已被后续轮次替换的证据",
"acceptance.comments.linkCopied": "链接已复制",
"acceptance.comments.loadFailed": "讨论加载失败,请刷新重试。",
@@ -141,12 +155,19 @@
"acceptance.comments.roundRejected": "第 {{round}} 轮交付被打回",
"acceptance.comments.sectionMessages": "{{count}} 条消息",
"acceptance.comments.send": "发送",
+ "acceptance.comments.sendCount": "发送 {{count}} 条评论",
"acceptance.comments.signIn": "登录",
"acceptance.comments.signInDescription": "登录后就能在这里评论、回复、在截图上圈出问题。",
"acceptance.comments.signInTitle": "加入这次讨论",
"acceptance.comments.signUp": "注册",
"acceptance.comments.title": "讨论",
+ "acceptance.comments.undo": "撤销",
"acceptance.comments.updateFailed": "评论更新失败,请重试。",
+ "acceptance.comments.video.emptyBody": "在任意画面暂停,然后在视频上拖出一个框。每个框都是一条独立评论,可以标好多个时间点后一起发送。",
+ "acceptance.comments.video.hintPaused": "拖动圈出区域 · 第 {{frame}} 帧",
+ "acceptance.comments.video.hintPlaying": "按下画面暂停,拖动即可圈选",
+ "acceptance.comments.video.listTitle": "本视频有 {{count}} 条评论",
+ "acceptance.comments.video.showFrame": "查看 {{time}} 的画面",
"acceptance.comments.withdraw": "撤回接受",
"acceptance.comments.withdrawDescription": "本轮期间随时可以撤回或再次表达,最后停在哪个状态才算数。",
"acceptance.comments.youApproved": "你已在第 {{round}} 轮表达接受",
diff --git a/packages/database/src/models/__tests__/acceptanceComment.test.ts b/packages/database/src/models/__tests__/acceptanceComment.test.ts
index 38037f2bfc5..d559d7a592d 100644
--- a/packages/database/src/models/__tests__/acceptanceComment.test.ts
+++ b/packages/database/src/models/__tests__/acceptanceComment.test.ts
@@ -68,6 +68,33 @@ const rect = { height: 0.2, width: 0.3, x: 0.1, y: 0.1 };
describe('AcceptanceCommentModel', () => {
describe('create', () => {
+ it('stores independent video times in metadata and preserves retry identity and other facts', async () => {
+ const input = {
+ acceptanceId,
+ anchor: { checkItemId: 'c2', evidenceId, rect, time: { start: 2.5 } },
+ authorUserId: reviewer,
+ clientId: 'video-frame',
+ content: 'first frame',
+ metadata: { origin: 'reviewer' },
+ };
+ const { comment } = await model.create(input);
+ expect(comment.metadata).toEqual({
+ origin: 'reviewer',
+ evidenceAnchor: { time: { start: 2.5 } },
+ });
+ const second = await model.create({
+ ...input,
+ anchor: { ...input.anchor, time: { start: 6 } },
+ clientId: 'another-video-frame',
+ });
+ const retry = await model.create(input);
+ expect(retry.isDuplicate).toBe(true);
+ expect(retry.comment.id).toBe(comment.id);
+ expect((await model.findById(comment.id))?.metadata).toEqual(comment.metadata);
+ expect(second.comment.metadata).toMatchObject({ evidenceAnchor: { time: { start: 6 } } });
+ expect(await model.listByAcceptance(acceptanceId)).toHaveLength(2);
+ });
+
it('writes a global comment with the round it was written against', async () => {
const { comment, isDuplicate } = await model.create({
acceptanceId,
diff --git a/packages/database/src/models/acceptanceComment.ts b/packages/database/src/models/acceptanceComment.ts
index c10ff4bff5c..c3f3769813d 100644
--- a/packages/database/src/models/acceptanceComment.ts
+++ b/packages/database/src/models/acceptanceComment.ts
@@ -1,7 +1,9 @@
import type {
AcceptanceCommentAttachmentRef,
AcceptanceCommentKind,
+ AcceptanceCommentMetadata,
AcceptanceCommentSource,
+ AcceptanceCommentTime,
AcceptanceReviewAnnotation,
DocumentCommentJson,
} from '@lobechat/types';
@@ -32,6 +34,7 @@ export interface CreateAcceptanceCommentParams {
checkItemId: string;
evidenceId: string;
rect: AcceptanceReviewAnnotation['rect'];
+ time?: AcceptanceCommentTime;
};
/** Files to hang on the remark, kept apart from the body. */
attachments?: AcceptanceCommentAttachmentRef[];
@@ -45,7 +48,7 @@ export interface CreateAcceptanceCommentParams {
editorData?: DocumentCommentJson;
kind?: AcceptanceCommentKind;
/** Open, server-written per-remark facts. */
- metadata?: Record<string, unknown>;
+ metadata?: AcceptanceCommentMetadata;
parentCommentId?: string;
/**
* Ceiling for this author on this acceptance, enforced inside the write's own
@@ -132,7 +135,9 @@ export class AcceptanceCommentModel {
evidenceId: anchor?.evidenceId ?? null,
kind: isReply ? 'comment' : (params.kind ?? 'comment'),
parentCommentId: parentCommentId ?? null,
- metadata: params.metadata ?? null,
+ metadata: anchor?.time
+ ? { ...params.metadata, evidenceAnchor: { time: anchor.time } }
+ : (params.metadata ?? null),
// A page belongs to the thread it opened, never to a reply or reaction.
source: parentCommentId ? null : (params.source ?? null),
workspaceId: params.workspaceId ?? null,
diff --git a/packages/database/src/schemas/acceptanceComment.ts b/packages/database/src/schemas/acceptanceComment.ts
index 169d0608055..6de88e272d1 100644
--- a/packages/database/src/schemas/acceptanceComment.ts
+++ b/packages/database/src/schemas/acceptanceComment.ts
@@ -2,6 +2,7 @@ import type {
AcceptanceCommentAnchorType,
AcceptanceCommentAttachmentRef,
AcceptanceCommentKind,
+ AcceptanceCommentMetadata,
AcceptanceCommentSource,
AcceptanceReviewAnnotation,
DocumentCommentJson,
@@ -107,11 +108,11 @@ export const acceptanceComments = pgTable(
*/
source: jsonb('source').$type<AcceptanceCommentSource>(),
/**
- * Open bag for per-remark facts that do not warrant a column of their own
- * yet, so a new kind of annotation does not need a migration. Server-written
- * only; nothing reads it as a contract until a field earns a real column.
+ * Server-owned per-remark facts. Video comments store their time in
+ * evidenceAnchor.time, e.g. { evidenceAnchor: { time: { start: 2.5 } } }.
+ * Other producers' keys remain separate from this typed anchor.
*/
- metadata: jsonb('metadata').$type<Record<string, unknown>>(),
+ metadata: jsonb('metadata').$type<AcceptanceCommentMetadata>(),
/** Client-generated idempotency key for retried creates. */
clientId: text('client_id').notNull(),
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 0039b8a8df1..5ac07184bc5 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -1,4 +1,27 @@
export default {
+ 'acceptance.comments.evidenceUnavailable': 'This evidence is no longer available.',
+ 'acceptance.comments.video.hintPaused': 'Drag to circle an area · frame {{frame}}',
+ 'acceptance.comments.video.hintPlaying': 'Press to pause, then drag to circle',
+ 'acceptance.comments.video.emptyBody':
+ 'Pause on any frame and drag over the video. Each area you circle becomes its own comment, so you can mark several moments before sending.',
+ 'acceptance.comments.video.showFrame': 'Show the frame at {{time}}',
+ 'acceptance.comments.video.listTitle': '{{count}} comment(s) on this video',
+ 'acceptance.comments.draftsTitle': 'New comments',
+ 'acceptance.comments.draftEmptyTitle': 'Circle what you mean',
+ 'acceptance.comments.draftPlaceholder': 'Write a comment about this area…',
+ 'acceptance.comments.draftNumber': 'Comment {{index}}',
+ 'acceptance.comments.draftRemove': 'Remove comment {{index}}',
+ 'acceptance.comments.draftRemoved': 'Comment {{index}} removed',
+ 'acceptance.comments.undo': 'Undo',
+ 'acceptance.comments.draftSaved': 'Drafts are saved on this device',
+ 'acceptance.comments.draftNeedsRegion': 'Circle an area to start a comment',
+ 'acceptance.comments.draftNeedsText': 'Comment {{index}} needs text',
+ 'acceptance.comments.draftsUnsent':
+ '{{count}} comment(s) not sent. Your text is kept — send again.',
+ 'acceptance.comments.sendCount': 'Send {{count}} comments',
+ 'acceptance.comments.evidenceDrafts': '{{count}} unsent',
+ 'acceptance.comments.evidenceNumber': 'Evidence {{index}}',
+ 'acceptance.comments.evidenceModalTitle': 'Comment on evidence',
'acceptance.share.title': 'Share',
'acceptance.share.makePublic': 'Allow access with the link',
'acceptance.share.makePrivate': 'Restrict access',
@@ -255,7 +278,7 @@ export default {
'acceptance.comments.checkRejectedRegions': '{{count}} marked region(s)',
'acceptance.comments.regionOn': '{{name}} commented on',
'acceptance.comments.roundRejected': 'Round {{round}} delivery sent back',
- 'acceptance.comments.commentThisEvidence': 'Comment on this screenshot',
+ 'acceptance.comments.commentMedia': 'Comment on this evidence',
'acceptance.comments.signIn': 'Sign in',
'acceptance.comments.signInDescription': 'Sign in to comment, reply, and mark up screenshots.',
'acceptance.comments.signInTitle': 'Join the discussion',
diff --git a/packages/types/src/acceptanceComment.ts b/packages/types/src/acceptanceComment.ts
index ac73758ae10..747d45930c8 100644
--- a/packages/types/src/acceptanceComment.ts
+++ b/packages/types/src/acceptanceComment.ts
@@ -1,3 +1,5 @@
+import { z } from 'zod';
+
import type { ReviewAnchor } from './acceptanceReview';
import type { DocumentCommentJson } from './documentComment';
import type { AcceptanceAttachment, AcceptanceReviewAnnotation } from './verify';
@@ -6,7 +8,7 @@ import type { AcceptanceAttachment, AcceptanceReviewAnnotation } from './verify'
* Where a discussion thread hangs on the acceptance page.
*
* - `acceptance`: the delivery as a whole (the global discussion under the checklist).
- * - `evidence`: a region circled on one evidence image of one check.
+ * - `evidence`: a region on one image or video frame of one check.
*/
export type AcceptanceCommentAnchorType = 'acceptance' | 'evidence';
@@ -36,6 +38,22 @@ export interface AcceptanceCommentAttachmentRef {
export type AcceptanceCommentSource = ReviewAnchor;
+/** A video comment is anchored to a single frame. */
+export const acceptanceCommentTimeSchema = z
+ .object({
+ start: z.number().finite().nonnegative(),
+ })
+ .strict();
+
+export type AcceptanceCommentTime = z.infer<typeof acceptanceCommentTimeSchema>;
+
+/** Server-owned facts; other comment producers may retain their own keys. */
+export interface AcceptanceCommentMetadata extends Record<string, unknown> {
+ evidenceAnchor?: {
+ time: AcceptanceCommentTime;
+ };
+}
+
/** One emoji on one comment, already tallied for display. */
export interface AcceptanceCommentReaction {
/** Display names behind the count, for the "who reacted" tooltip. */
@@ -72,6 +90,8 @@ export interface AcceptanceCommentAnchor {
evidenceId?: string | null;
/** Normalized (0–1) region on the evidence image. */
rect?: AcceptanceReviewAnnotation['rect'] | null;
+ /** Video time in seconds, pinned to this evidence version. */
+ time?: AcceptanceCommentTime | null;
}
export interface AcceptanceCommentItem extends AcceptanceCommentAnchor {
@@ -143,6 +163,7 @@ export interface CreateAcceptanceCommentInput {
checkItemId: string;
evidenceId: string;
rect: AcceptanceReviewAnnotation['rect'];
+ time?: AcceptanceCommentTime;
};
/** Files to hang on the remark, already uploaded. */
attachments?: AcceptanceCommentAttachmentRef[];
diff --git a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx b/src/features/Acceptance/Viewer/Checks/CheckRow.tsx
index a71ad675b7e..ab30a3be413 100644
--- a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx
+++ b/src/features/Acceptance/Viewer/Checks/CheckRow.tsx
@@ -1,7 +1,6 @@
'use client';
import { readEvidenceChapters } from '@lobechat/const/verify';
-import type { AcceptanceCommentThread } from '@lobechat/types';
import {
ActionIcon,
Button,
@@ -33,28 +32,18 @@ import {
Repeat,
Route,
} from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
-
import { hasRenderableEvidence, readVisualizationManifest } from '../../Report/visualization';
import { VisualizationDeltaBadge, VisualizationRenderer } from '../../Report/VisualizationRenderer';
import { checkDisplayTitle } from '../../utils';
-import { useOptionalAcceptanceScope } from '../AcceptanceScope';
-import { useAcceptanceAuthorColor } 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 { HistoricalComments } from '../Comments/HistoricalComments';
+import { useCheckComments } from '../Comments/useCheckComments';
import {
canMarkEvidence,
evidenceCounts,
evidenceShortcut,
- hasAnnotatableEvidence,
isRejectable,
} from '../Evidence/evidence';
import { EvidenceList } from '../Evidence/EvidenceList';
@@ -63,8 +52,6 @@ import { openCheckRejectModal } from '../Review/CheckRejectModal';
import type { CheckProposal } from '../Review/proposal';
import { classifyProposalEdit } from '../Review/proposal';
import ProposalCard from '../Review/ProposalCard';
-import { useAcceptanceBundle, useEvidenceUrlRefresh } from '../useAcceptanceBundle';
-import { canCommentOnAcceptanceEvidence } from '../visibility';
import {
AcceptedNote,
collectEvidenceById,
@@ -165,106 +152,19 @@ export const AcceptanceCheckRow = memo<{
}, [proposalOpen, check.prediction]);
const hasHistory = hasCheckHistory(check, historyReviews);
- // 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 refreshEvidenceUrl = useEvidenceUrlRefresh(scope?.acceptanceId);
- const comments = useAcceptanceComments(scope?.acceptanceId);
- const authorColor = useAcceptanceAuthorColor();
- const viewerId = useUserStore(userProfileSelectors.userId);
- /**
- * Closing a note is a verdict on it: whoever raised it may close their own,
- * and the acceptance's reviewers may close anyone's. Ownership is read from
- * the author, not from `canDelete` — that flag also turns on for a
- * moderator, and borrowing it would silently hand the same power out.
- *
- * Memoized on the identity it reads: the profile arrives after the first
- * paint, and the overlay memo below would otherwise keep handing its
- * threads the answer computed while nobody was signed in.
- */
- const canResolveThread = useCallback(
- (thread: AcceptanceCommentThread) =>
- comments.canApprove ||
- (Boolean(viewerId) && thread.root.authorUserId === viewerId && !thread.root.deletedAt),
- [comments.canApprove, viewerId],
- );
- 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({
- authorAvatar: author.avatar,
- authorName: commentAuthorName(author),
- color: authorColor(authorUserId),
- comment: content,
- label: index + 1,
- panel: (
- <CommentThread
- canComment={comments.canComment}
- canResolve={canResolveThread(thread)}
- 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, canResolveThread, authorColor]);
- const canCommentEvidence =
- canCommentOnAcceptanceEvidence(bundle, comments.canComment) &&
- Boolean(check.result) &&
- hasAnnotatableEvidence(check);
- const openEvidenceComment = (initialEvidenceId?: string) =>
- openEvidenceCommentModal({
- evidence: check.evidence,
- initialEvidenceId,
- 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;
- },
- });
+ const {
+ comments,
+ checkThreads,
+ staleThreads,
+ commentOverlays,
+ canResolveThread,
+ commentActions,
+ canCommentEvidence,
+ openEvidenceComment,
+ refreshEvidenceUrl,
+ } = useCheckComments(check, proposalOverlays);
- // The picture's own shortcut opens whatever the bottom of the row offers:
- // a region comment for a reader, marking a send-back for the author, who
- // gives region feedback through the reject instead.
+ // Comments and review decisions have distinct entry points for every role.
const shortcut = evidenceShortcut({
canComment: canCommentEvidence,
canMark: reviewable && !activeReview && canMarkEvidence(check, desktop),
@@ -273,7 +173,7 @@ export const AcceptanceCheckRow = memo<{
});
const floatingComment =
shortcut === 'comment'
- ? { label: t('acceptance.comments.commentThisEvidence'), open: openEvidenceComment }
+ ? { label: t('acceptance.comments.commentMedia'), open: openEvidenceComment }
: shortcut === 'annotate'
? {
label: t('acceptance.review.annotate'),
@@ -694,41 +594,16 @@ export const AcceptanceCheckRow = memo<{
<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}
- canResolve={canResolveThread(thread)}
- thread={thread}
- {...commentActions}
- />
- </Flexbox>
- </Flexbox>
- );
- })}
+ <HistoricalComments
+ canComment={comments.canComment}
+ canResolveThread={canResolveThread}
+ evidenceById={evidenceById}
+ overlays={commentOverlays}
+ threads={staleThreads}
+ timeline={check.timeline}
+ onRefreshEvidenceUrl={refreshEvidenceUrl}
+ {...commentActions}
+ />
</Flexbox>
)}
{check.state === 'not_executed' && (
@@ -930,7 +805,7 @@ export const AcceptanceCheckRow = memo<{
openEvidenceComment();
}}
>
- {t('acceptance.comments.commentEvidence')}
+ {t('acceptance.comments.evidenceModalTitle')}
</Button>
) : (
<span />
diff --git a/src/features/Acceptance/Viewer/Comments/CommentThread.tsx b/src/features/Acceptance/Viewer/Comments/CommentThread.tsx
index 0f7ba7ac8e9..d32e2c066b1 100644
--- a/src/features/Acceptance/Viewer/Comments/CommentThread.tsx
+++ b/src/features/Acceptance/Viewer/Comments/CommentThread.tsx
@@ -5,7 +5,9 @@ import { Button, cx, Flexbox, Icon, Tag, toast } from '@lobehub/ui';
import { CheckCircle2 } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useLocation } from 'react-router';
+import { commentAnchorId, commentIdFromHash } from './anchor';
import CommentCard, { commentAuthorName } from './CommentCard';
import CommentComposer from './CommentComposer';
import { styles } from './styles';
@@ -40,10 +42,13 @@ const CommentThread = memo<CommentThreadProps>(
const [resolving, setResolving] = useState(false);
const [openOverride, setOpenOverride] = useState<boolean>();
const { root, replies } = thread;
+ const { hash } = useLocation();
+ const addressed = commentIdFromHash(hash);
+ const anchored = addressed === root.id || replies.some((reply) => reply.id === addressed);
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 open = openOverride ?? (anchored || !resolved);
const toggleResolved = async () => {
setResolving(true);
@@ -85,10 +90,17 @@ const CommentThread = memo<CommentThreadProps>(
return (
<Flexbox className={cx(resolved && styles.resolvedThread)}>
- <CommentCard badges={badges} comment={root} variant={'plain'} onDelete={onDelete} />
+ <CommentCard
+ anchored
+ 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} />
+ // A reply link lands on the reply itself, not just its thread.
+ <div className={styles.panelReply} id={commentAnchorId(reply.id)} key={reply.id}>
+ <CommentCard anchored comment={reply} variant={'plain'} onDelete={onDelete} />
</div>
))}
{canComment &&
diff --git a/src/features/Acceptance/Viewer/Comments/CommentWorkspace.tsx b/src/features/Acceptance/Viewer/Comments/CommentWorkspace.tsx
new file mode 100644
index 00000000000..b860a1d736d
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/CommentWorkspace.tsx
@@ -0,0 +1,335 @@
+'use client';
+
+import { ActionIcon, Button, Center, Flexbox, Icon, Text, TextArea } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { SquareDashedMousePointer, Trash2 } from 'lucide-react';
+import type { ReactNode, Ref } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/** The point where the side panel folds under the stage, matching the modal shell. */
+
+const styles = stylex.create({
+ root: { display: 'flex', flex: '1', flexDirection: 'column', minWidth: 0, minHeight: 0 },
+ body: {
+ display: { 'default': 'grid', '@media (width <= 767px)': 'flex' },
+ gridTemplateColumns: 'minmax(0, 1fr) 352px',
+ flex: '1',
+ minHeight: 0,
+ flexDirection: { 'default': null, '@media (width <= 767px)': 'column' },
+ overflowY: { 'default': null, '@media (width <= 767px)': 'auto' },
+ overscrollBehavior: { 'default': null, '@media (width <= 767px)': 'contain' },
+ gap: { 'default': null, '@media (width <= 767px)': 16 },
+ paddingBlockEnd: { 'default': null, '@media (width <= 767px)': 16 },
+ },
+ stage: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 12,
+ minWidth: 0,
+ minHeight: 0,
+ paddingBlock: { 'default': 16, '@media (width <= 767px)': '12px 0' },
+ paddingInline: { 'default': 16, '@media (width <= 767px)': 12 },
+ backgroundColor: { 'default': cssVar.colorBgLayout, '@media (width <= 767px)': 'transparent' },
+ flex: { 'default': null, '@media (width <= 767px)': 'none' },
+ },
+ fit: {
+ containerType: { 'default': 'size', '@media (width <= 767px)': 'normal' },
+ display: 'flex',
+ flex: { 'default': '1', '@media (width <= 767px)': 'none' },
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: 0,
+ },
+ scroll: {
+ overflow: 'auto',
+ flex: { 'default': '1', '@media (width <= 767px)': 'none' },
+ minHeight: 0,
+ },
+ panel: {
+ overflowY: { 'default': 'auto', '@media (width <= 767px)': 'visible' },
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 8,
+ minHeight: 0,
+ paddingBlock: { 'default': 16, '@media (width <= 767px)': 0 },
+ paddingInline: { 'default': 16, '@media (width <= 767px)': 12 },
+ borderInlineStartWidth: { 'default': 1, '@media (width <= 767px)': 0 },
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: cssVar.colorBorderSecondary,
+ flex: { 'default': null, '@media (width <= 767px)': 'none' },
+ },
+ footer: {
+ display: 'flex',
+ flex: 'none',
+ gap: { 'default': 12, '@media (width <= 767px)': 8 },
+ alignItems: { 'default': 'center', '@media (width <= 767px)': 'stretch' },
+ flexDirection: { 'default': 'row', '@media (width <= 767px)': 'column' },
+ paddingBlockStart: 12,
+ paddingBlockEnd: {
+ 'default': 12,
+ '@media (width <= 767px)': 'max(12px, env(safe-area-inset-bottom))',
+ },
+ paddingInline: { 'default': 16, '@media (width <= 767px)': 12 },
+ borderBlockStartWidth: 1,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ },
+ status: { flex: '1', minWidth: 0, fontSize: 12, color: cssVar.colorTextTertiary },
+ statusError: { color: cssVar.colorError },
+ cancel: { display: { 'default': null, '@media (width <= 767px)': 'none' } },
+ send: { minHeight: { 'default': null, '@media (width <= 767px)': 44 } },
+ note: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 8,
+ paddingBlock: 12,
+ paddingInline: { 'default': 12, '@media (width <= 767px)': 8 },
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: 'transparent',
+ borderRadius: cssVar.borderRadiusLG,
+ backgroundColor: {
+ 'default': 'transparent',
+ '@media (hover: hover)': { 'default': null, ':hover': cssVar.colorFillTertiary },
+ },
+ transition: {
+ 'default': `background ${cssVar.motionDurationMid}, border-color ${cssVar.motionDurationMid}`,
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ },
+ field: { fontSize: { 'default': null, '@media (width <= 767px)': 16 } },
+ noteActive: {
+ borderColor: cssVar.colorBorder,
+ boxShadow: cssVar.boxShadowTertiary,
+ backgroundColor: { 'default': cssVar.colorBgContainer, ':hover': cssVar.colorBgContainer },
+ },
+ statusLink: {
+ cursor: 'pointer',
+ padding: 0,
+ borderWidth: 0,
+ font: 'inherit',
+ color: { 'default': cssVar.colorText, ':hover': cssVar.colorPrimaryHover },
+ textDecoration: 'underline',
+ textUnderlineOffset: 3,
+ backgroundColor: 'transparent',
+ borderRadius: { 'default': null, ':focus-visible': 2 },
+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorPrimaryBorder}` },
+ },
+ badge: {
+ flex: 'none',
+ width: 18,
+ height: 18,
+ borderRadius: '50%',
+ fontSize: 11,
+ fontWeight: 600,
+ lineHeight: '18px',
+ color: cssVar.colorTextLightSolid,
+ textAlign: 'center',
+ backgroundColor: cssVar.colorError,
+ },
+ empty: {
+ flex: '1',
+ gap: 8,
+ minHeight: { 'default': 200, '@media (width <= 767px)': 0 },
+ paddingBlock: { 'default': 32, '@media (width <= 767px)': 16 },
+ paddingInline: 24,
+ textAlign: 'center',
+ },
+ emptyIcon: {
+ width: 40,
+ height: 40,
+ borderRadius: cssVar.borderRadiusLG,
+ color: cssVar.colorTextSecondary,
+ backgroundColor: cssVar.colorFillTertiary,
+ },
+});
+
+interface CommentWorkspaceProps {
+ footer: ReactNode;
+ inert?: boolean;
+ panel: ReactNode;
+ /** The picture being commented on. */
+ stage: ReactNode;
+ /**
+ * `fit` centres the stage and makes it a size container (a video sizes its
+ * frame to it); `scroll` lets a tall screenshot scroll inside it.
+ */
+ stageMode: 'fit' | 'scroll';
+ strip?: ReactNode;
+}
+
+/**
+ * The comment composer's frame: the evidence large on the left, the notes being
+ * written in a panel on the right, sending pinned underneath. On a phone the
+ * panel folds under the stage and the page scrolls; sending stays pinned.
+ */
+export const CommentWorkspace = ({
+ footer,
+ inert,
+ panel,
+ stage,
+ stageMode,
+ strip,
+}: CommentWorkspaceProps) => (
+ <div {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.body)}>
+ <div {...stylex.props(styles.stage)} inert={inert}>
+ {strip}
+ <div {...stylex.props(stageMode === 'fit' ? styles.fit : styles.scroll)}>{stage}</div>
+ </div>
+ <div {...stylex.props(styles.panel)} inert={inert}>
+ {panel}
+ </div>
+ </div>
+ <div {...stylex.props(styles.footer)}>{footer}</div>
+ </div>
+);
+
+export const DraftPanelHeading = ({ count }: { count: number }) => {
+ const { t } = useTranslation('verify');
+ return (
+ <Flexbox horizontal align={'baseline'} gap={8} style={{ paddingInline: 4 }}>
+ <Text strong>{t('acceptance.comments.draftsTitle')}</Text>
+ {count > 0 && (
+ <Text fontSize={12} style={{ color: cssVar.colorTextTertiary }}>
+ {count}
+ </Text>
+ )}
+ </Flexbox>
+ );
+};
+
+/** First use: show what to do with the picture, since nothing is written yet. */
+export const DraftEmpty = ({ body }: { body: string }) => {
+ const { t } = useTranslation('verify');
+ return (
+ <Center {...stylex.props(styles.empty)}>
+ <Center {...stylex.props(styles.emptyIcon)}>
+ <Icon icon={SquareDashedMousePointer} size={20} />
+ </Center>
+ <Text strong>{t('acceptance.comments.draftEmptyTitle')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {body}
+ </Text>
+ </Center>
+ );
+};
+
+interface DraftNoteProps {
+ active?: boolean;
+ autoFocus?: boolean;
+ fieldRef?: Ref<HTMLTextAreaElement>;
+ index: number;
+ onChange: (value: string) => void;
+ onFocus?: () => void;
+ onRemove: () => void;
+ onSubmit: () => void;
+ /** Where the note points — the video's moment, the image's region. */
+ stamp?: ReactNode;
+ value: string;
+}
+
+/** One comment being written: its number, where it points, its own words. */
+export const DraftNote = ({
+ active,
+ autoFocus,
+ fieldRef,
+ index,
+ onChange,
+ onFocus,
+ onRemove,
+ onSubmit,
+ stamp,
+ value,
+}: DraftNoteProps) => {
+ const { t } = useTranslation('verify');
+ return (
+ <div {...stylex.props([styles.note, active && styles.noteActive])}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <span {...stylex.props(styles.badge)}>{index}</span>
+ <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ {stamp}
+ </Flexbox>
+ <ActionIcon
+ aria-label={t('acceptance.comments.draftRemove', { index })}
+ icon={Trash2}
+ size={'small'}
+ title={t('acceptance.comments.draftRemove', { index })}
+ onClick={onRemove}
+ />
+ </Flexbox>
+ <TextArea
+ {...stylex.props(styles.field)}
+ aria-label={t('acceptance.comments.draftNumber', { index })}
+ autoFocus={autoFocus}
+ autoSize={{ maxRows: 8, minRows: 2 }}
+ placeholder={t('acceptance.comments.draftPlaceholder')}
+ ref={fieldRef}
+ value={value}
+ variant={active ? 'outlined' : 'filled'}
+ onChange={(event) => onChange(event.target.value)}
+ onFocus={onFocus}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ onSubmit();
+ }
+ }}
+ />
+ </div>
+ );
+};
+
+interface DraftFooterProps {
+ count: number;
+ disabled: boolean;
+ error?: boolean;
+ loading: boolean;
+ onCancel: () => void;
+ onSend: () => void;
+ status: ReactNode;
+}
+
+/** Why sending is or is not possible, then the one primary action. */
+export const DraftFooter = ({
+ count,
+ disabled,
+ error,
+ loading,
+ onCancel,
+ onSend,
+ status,
+}: DraftFooterProps) => {
+ const { t } = useTranslation('verify');
+ return (
+ <>
+ <div
+ aria-live={'polite'}
+ {...stylex.props([styles.status, error && styles.statusError])}
+ role={error ? 'alert' : undefined}
+ >
+ {status}
+ </div>
+ <Button {...stylex.props(styles.cancel)} disabled={loading} onClick={onCancel}>
+ {t('acceptance.actions.cancel')}
+ </Button>
+ <Button
+ {...stylex.props(styles.send)}
+ disabled={disabled}
+ loading={loading}
+ type={'primary'}
+ onClick={onSend}
+ >
+ {count > 1 ? t('acceptance.comments.sendCount', { count }) : t('acceptance.comments.send')}
+ </Button>
+ </>
+ );
+};
+
+/** A link-styled line in the footer status that takes you to what blocks sending. */
+export const StatusLink = ({ children, onClick }: { children: ReactNode; onClick: () => void }) => (
+ <button {...stylex.props(styles.statusLink)} type={'button'} onClick={onClick}>
+ {children}
+ </button>
+);
diff --git a/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx b/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx
index c778bc9ab40..0987ecc8353 100644
--- a/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx
+++ b/src/features/Acceptance/Viewer/Comments/EvidenceCommentModal.tsx
@@ -1,53 +1,125 @@
'use client';
-import type { AcceptanceReviewAnnotation } from '@lobechat/types';
+import type { AcceptanceCommentTime, AcceptanceReviewAnnotation } from '@lobechat/types';
import {
- Button,
createModal,
createStaticStyles,
cssVar,
cx,
Flexbox,
+ Icon,
Text,
- TextArea,
toast,
useModalContext,
} from '@lobehub/ui';
import { t } from 'i18next';
-import { memo, useState } from 'react';
+import { Film } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useReducer, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
import type { AcceptanceEvidence } from '../Checks/types';
import { AnnotationCanvas } from '../Evidence/Annotation';
-import { isAnnotatable } from '../Evidence/evidence';
+import { isCommentableEvidence } from '../Evidence/evidence';
+import {
+ CommentWorkspace,
+ DraftEmpty,
+ DraftFooter,
+ DraftNote,
+ DraftPanelHeading,
+} from './CommentWorkspace';
+import type { EvidenceCommentDraft } from './evidenceCommentDraft';
+import {
+ evidenceCommentDraftKey,
+ readEvidenceCommentDraft,
+ saveEvidenceCommentDraft,
+} from './evidenceCommentDraft';
+import { readVideoCommentDrafts } from './videoCommentDraft';
+import { VideoCommentEditor } from './VideoCommentEditor';
+
+const MODAL_WIDTH = 'min(1180px, calc(100vw - 48px))';
const styles = createStaticStyles(({ css }) => ({
- hint: css`
- font-size: 12px;
- color: ${cssVar.colorTextTertiary};
- `,
- stage: css`
- overflow: auto;
+ /** A review surface, not a dialog: the evidence needs the room to be circled precisely. */
+ popup: css`
+ > div {
+ display: flex;
+ flex-direction: column;
- max-height: min(60vh, 640px);
- border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: 8px;
+ width: ${MODAL_WIDTH};
+ max-width: ${MODAL_WIDTH};
+ height: min(860px, calc(100dvh - 48px));
+ }
+
+ @media (width <= 767px) {
+ align-items: stretch;
+ justify-content: stretch;
+
+ width: 100vw !important;
+ max-width: 100vw !important;
+ height: 100dvh;
- background: ${cssVar.colorFillQuaternary};
+ > div {
+ width: 100vw !important;
+ max-width: 100vw !important;
+ height: 100dvh;
+ max-height: 100dvh;
+ padding: 0;
+ border-radius: 0;
+ }
+ }
+ `,
+ header: css`
+ @media (width <= 767px) {
+ min-height: 56px;
+ padding-block: max(12px, env(safe-area-inset-top)) 12px;
+ padding-inline: 12px 52px;
+ }
+ `,
+ close: css`
+ @media (width <= 767px) {
+ inset-block-start: max(4px, env(safe-area-inset-top));
+ inset-inline-end: 4px;
+ width: 44px;
+ height: 44px;
+ }
+ `,
+ strip: css`
+ overflow-x: auto;
+ flex: none;
+ gap: 8px;
`,
thumb: css`
cursor: pointer;
+ position: relative;
+
overflow: hidden;
+ flex: none;
- width: 64px;
+ width: 72px;
height: 44px;
+ padding: 0;
border: 2px solid transparent;
- border-radius: 6px;
+ border-radius: ${cssVar.borderRadius};
background: ${cssVar.colorFillTertiary};
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 1px;
+ }
+
img {
+ display: block;
width: 100%;
height: 100%;
object-fit: cover;
@@ -56,125 +128,258 @@ const styles = createStaticStyles(({ css }) => ({
thumbActive: css`
border-color: ${cssVar.colorPrimary};
`,
+ /** A video has no poster to thumbnail without decoding it — an icon tile says what it is. */
+ videoThumb: css`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 100%;
+ height: 100%;
+
+ color: #fff;
+
+ background: #000;
+ `,
+ /** Unsent drafts on another piece of evidence: sending here leaves them where they are. */
+ draftCount: css`
+ position: absolute;
+ inset-block-start: 2px;
+ inset-inline-end: 2px;
+
+ min-width: 16px;
+ height: 16px;
+ padding-inline: 4px;
+ border-radius: 8px;
+
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 16px;
+ color: ${cssVar.colorBgContainer};
+
+ background: ${cssVar.colorText};
+ `,
}));
export interface EvidenceCommentValue {
+ clientId: string;
content: string;
evidenceId: string;
rect: AcceptanceReviewAnnotation['rect'];
+ time?: AcceptanceCommentTime;
}
interface EvidenceCommentModalProps {
+ acceptanceId: string;
evidence: AcceptanceEvidence[];
initialEvidenceId?: string;
+ initialTime?: number;
/** Persist the comment; resolve true to close, false to stay open. */
onConfirm: (value: EvidenceCommentValue) => Promise<boolean>;
+ onRefreshEvidenceUrl?: (id: string) => Promise<string | undefined>;
+}
+
+interface EditorProps extends EvidenceCommentModalProps {
+ active: AcceptanceEvidence;
+ onBusyChange: (busy: boolean) => void;
+ onDraftsChange: () => void;
+ strip?: ReactNode;
+ userId: string;
}
/**
- * 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.
+ * An image comment points at one region. Video editing owns its multi-frame drafts.
+ * Its anchor stays fixed until explicitly changed; submission never reviews a check.
*/
-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);
+const ImageCommentEditor = ({
+ acceptanceId,
+ active,
+ onConfirm,
+ onBusyChange,
+ onDraftsChange,
+ strip,
+ userId,
+}: EditorProps) => {
+ const { t } = useTranslation('verify');
+ const { close, setCanDismissByClickOutside } = useModalContext();
+ const key = evidenceCommentDraftKey(userId, acceptanceId, active.id);
+ const [draft, setDraft] = useState<EvidenceCommentDraft>(
+ () =>
+ readEvidenceCommentDraft(key) ?? {
+ clientId: crypto.randomUUID(),
+ content: '',
+ rect: null,
+ },
+ );
+ const current = useRef(draft);
+ const update = (patch: Partial<EvidenceCommentDraft>) => {
+ const next = { ...current.current, ...patch };
+ const counted = Boolean(next.rect) !== Boolean(current.current.rect);
+ current.current = next;
+ setDraft(next);
+ saveEvidenceCommentDraft(key, next);
+ if (counted) onDraftsChange();
+ };
+ const [submitting, setSubmitting] = useState(false);
+ const { rect, content, clientId } = draft;
+ const trimmed = content.trim();
+ const submit = async () => {
+ if (!rect || !trimmed || submitting) return;
+ setSubmitting(true);
+ onBusyChange(true);
+ try {
+ setCanDismissByClickOutside(false);
+ const done = await onConfirm({
+ clientId,
+ content: trimmed,
+ evidenceId: active.id,
+ rect,
+ });
+ if (done) {
+ saveEvidenceCommentDraft(key);
+ close();
}
- };
-
- 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();
- }
- }}
+ } catch (cause) {
+ console.error('[acceptance:comments]', cause);
+ toast.error(t('acceptance.comments.createFailed'));
+ } finally {
+ setSubmitting(false);
+ onBusyChange(false);
+ setCanDismissByClickOutside(true);
+ }
+ };
+
+ let status: string = t('acceptance.comments.draftSaved');
+ if (!rect) status = t('acceptance.comments.draftNeedsRegion');
+ else if (!trimmed) status = t('acceptance.comments.draftNeedsText', { index: 1 });
+
+ return (
+ <CommentWorkspace
+ inert={submitting}
+ stageMode={'scroll'}
+ strip={strip}
+ footer={
+ <DraftFooter
+ count={rect ? 1 : 0}
+ disabled={!rect || !trimmed}
+ loading={submitting}
+ status={status}
+ onCancel={close}
+ onSend={() => void submit()}
/>
- <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
- {!rect && (
- <Text fontSize={12} type={'secondary'}>
- {t('acceptance.comments.regionMissing')}
- </Text>
+ }
+ panel={
+ <>
+ <DraftPanelHeading count={rect ? 1 : 0} />
+ {rect ? (
+ <DraftNote
+ active
+ autoFocus
+ index={1}
+ value={content}
+ stamp={
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.comments.region')}
+ </Text>
+ }
+ onChange={(value) => update({ content: value })}
+ onRemove={() => update({ rect: null })}
+ onSubmit={() => void submit()}
+ />
+ ) : (
+ <DraftEmpty body={t('acceptance.comments.regionHint')} />
)}
- <Button
- disabled={!rect || !trimmed}
- loading={submitting}
- type={'primary'}
- onClick={() => void submit()}
- >
- {t('acceptance.comments.send')}
- </Button>
- </Flexbox>
- </Flexbox>
- );
- },
-);
+ </>
+ }
+ stage={
+ <AnnotationCanvas
+ annotations={rect ? [{ comment: '', rect }] : []}
+ src={active.fileUrl!}
+ onDraw={(next) => update({ rect: next })}
+ onRemove={() => update({ rect: null })}
+ onUpdate={(_index, next) => update({ rect: next })}
+ />
+ }
+ />
+ );
+};
+
+/** What is still unsent on a piece of evidence, as its tile in the strip counts it. */
+const draftCount = (userId: string, acceptanceId: string, item: AcceptanceEvidence) => {
+ const key = evidenceCommentDraftKey(userId, acceptanceId, item.id);
+ if (item.type === 'video') return readVideoCommentDrafts(key).length;
+ return readEvidenceCommentDraft(key)?.rect ? 1 : 0;
+};
+
+const EvidenceCommentContent = (options: EvidenceCommentModalProps) => {
+ const userId = useUserStore(userProfileSelectors.userId);
+ const { t } = useTranslation('verify');
+ const media = options.evidence.filter(isCommentableEvidence);
+ const [pending, setPending] = useState(false);
+ const [activeId, setActiveId] = useState(options.initialEvidenceId ?? media[0]?.id);
+ // Drafts live in storage; this re-reads the counts when an editor adds or drops one.
+ const [, recount] = useReducer((value: number) => value + 1, 0);
+ const active = media.find((item) => item.id === activeId) ?? media[0];
+ if (!active || !userId) return null;
-EvidenceCommentContent.displayName = 'AcceptanceEvidenceCommentContent';
+ const strip = media.length > 1 && (
+ <Flexbox horizontal className={styles.strip}>
+ {media.map((item, index) => {
+ const count = draftCount(userId, options.acceptanceId, item);
+ const label = t('acceptance.comments.evidenceNumber', { index: index + 1 });
+ return (
+ <button
+ aria-label={label}
+ aria-pressed={item.id === active.id}
+ className={cx(styles.thumb, item.id === active.id && styles.thumbActive)}
+ disabled={pending}
+ key={item.id}
+ type={'button'}
+ title={
+ count > 0 ? `${label} · ${t('acceptance.comments.evidenceDrafts', { count })}` : label
+ }
+ onClick={() => setActiveId(item.id)}
+ >
+ {item.type === 'video' ? (
+ <span className={styles.videoThumb}>
+ <Icon icon={Film} size={18} />
+ </span>
+ ) : (
+ <img alt={''} src={item.fileUrl!} />
+ )}
+ {count > 0 && <span className={styles.draftCount}>{count}</span>}
+ </button>
+ );
+ })}
+ </Flexbox>
+ );
+ const editorProps = {
+ ...options,
+ active,
+ // A later evidence opens at its own start, not at the moment captured on another.
+ initialTime: active.id === options.initialEvidenceId ? options.initialTime : undefined,
+ onBusyChange: setPending,
+ onDraftsChange: recount,
+ strip: strip || undefined,
+ userId,
+ };
+ const editorKey = `${active.id}:${userId}`;
+ return active.type === 'video' ? (
+ <VideoCommentEditor key={editorKey} {...editorProps} />
+ ) : (
+ <ImageCommentEditor key={editorKey} {...editorProps} />
+ );
+};
export const openEvidenceCommentModal = (options: EvidenceCommentModalProps) =>
createModal({
content: <EvidenceCommentContent {...options} />,
+ classNames: { close: styles.close, header: styles.header, popup: styles.popup },
footer: null,
maskClosable: true,
- styles: { content: { padding: 0 } },
- title: t('acceptance.comments.regionModalTitle', { ns: 'verify' }),
- width: 'min(880px, 92vw)',
+ styles: {
+ content: { padding: 0, display: 'flex', flex: 1, minHeight: 0, overflow: 'hidden' },
+ },
+ title: t('acceptance.comments.evidenceModalTitle', { ns: 'verify' }),
+ width: MODAL_WIDTH,
});
diff --git a/src/features/Acceptance/Viewer/Comments/HistoricalComments.tsx b/src/features/Acceptance/Viewer/Comments/HistoricalComments.tsx
new file mode 100644
index 00000000000..ffabcb4dd26
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/HistoricalComments.tsx
@@ -0,0 +1,91 @@
+'use client';
+
+import type { AcceptanceCommentThread } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import type { ComponentProps } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useOptionalAcceptanceScope } from '../AcceptanceScope';
+import type { AcceptanceCheck, AcceptanceEvidence } from '../Checks/types';
+import { EvidenceList } from '../Evidence/EvidenceList';
+import type { EvidenceOverlayMap } from '../Evidence/overlay';
+import { commentAnchorId, useCommentAnchor } from './anchor';
+import CommentThread from './CommentThread';
+import { historicalCommentEntries } from './historicalThreads';
+import ThreadEvidence from './ThreadEvidence';
+
+interface HistoricalCommentsProps extends Pick<
+ ComponentProps<typeof CommentThread>,
+ 'canComment' | 'onDelete' | 'onReply' | 'onResolve'
+> {
+ canResolveThread: (thread: AcceptanceCommentThread) => boolean;
+ evidenceById: Map<string, AcceptanceEvidence>;
+ onRefreshEvidenceUrl?: (id: string) => Promise<string | undefined>;
+ overlays?: EvidenceOverlayMap;
+ threads: AcceptanceCommentThread[];
+ timeline: AcceptanceCheck['timeline'];
+}
+
+/** Historical video discussions share the same player and index as current evidence. */
+export const HistoricalComments = ({
+ canComment,
+ canResolveThread,
+ evidenceById,
+ onDelete,
+ onRefreshEvidenceUrl,
+ onReply,
+ onResolve,
+ overlays,
+ threads,
+ timeline,
+}: HistoricalCommentsProps) => {
+ const { t } = useTranslation('verify');
+ const scope = useOptionalAcceptanceScope();
+ useCommentAnchor(threads, scope?.embedded);
+ return historicalCommentEntries(threads, evidenceById).map((entry) => {
+ const { evidence } = entry;
+ const roundIndex = timeline.find((round) =>
+ round.evidence.some((item) => item.id === evidence?.id),
+ )?.roundIndex;
+ if (entry.type === 'video')
+ return (
+ <Flexbox gap={4} key={entry.evidence.id}>
+ {roundIndex !== undefined && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.comments.evidenceFromRound', { round: roundIndex })}
+ </Text>
+ )}
+ <EvidenceList
+ evidence={[entry.evidence]}
+ overlays={overlays}
+ onRefreshEvidenceUrl={onRefreshEvidenceUrl}
+ />
+ </Flexbox>
+ );
+ const { thread } = entry;
+ return (
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ gap={12}
+ id={commentAnchorId(thread.root.id)}
+ key={thread.root.id}
+ wrap={'wrap'}
+ >
+ {evidence && (
+ <ThreadEvidence stale comment={thread.root} evidence={evidence} roundIndex={roundIndex} />
+ )}
+ <Flexbox flex={1} style={{ minWidth: 200 }}>
+ <CommentThread
+ canComment={canComment}
+ canResolve={canResolveThread(thread)}
+ thread={thread}
+ onDelete={onDelete}
+ onReply={onReply}
+ onResolve={onResolve}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+ });
+};
diff --git a/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx b/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx
index 089cc86309a..d90cbab313b 100644
--- a/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx
+++ b/src/features/Acceptance/Viewer/Comments/ThreadEvidence.tsx
@@ -1,12 +1,17 @@
'use client';
import type { AcceptanceCommentItem } from '@lobechat/types';
-import { createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
+import { Button, createModal, createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Play } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useOptionalAcceptanceScope } from '../AcceptanceScope';
import type { AcceptanceEvidence } from '../Checks/types';
import { AnnotatedImage } from '../Evidence/Annotation';
+import { VideoEvidencePlayer, type VideoMark } from '../Evidence/Video/VideoEvidencePlayer';
+import { formatVideoTime } from '../Evidence/Video/videoTime';
+import { useEvidenceUrlRefresh } from '../useAcceptanceBundle';
import { useAcceptanceAuthorColor } from './authorColor';
const THUMBNAIL_WIDTH = 220;
@@ -52,6 +57,34 @@ interface ThreadEvidenceProps {
stale: boolean;
}
+/** Mounted only inside the preview; each retry can replace an expired signed URL. */
+const ThreadVideoPreview = ({
+ mark,
+ onRefreshSource,
+ src,
+}: {
+ mark: VideoMark;
+ onRefreshSource?: () => Promise<string | undefined>;
+ src: string;
+}) => {
+ const [source, setSource] = useState(src);
+ return (
+ <VideoEvidencePlayer
+ initialTime={mark.time.start}
+ marks={[mark]}
+ src={source}
+ onRefreshSource={
+ onRefreshSource
+ ? async () => {
+ const next = await onRefreshSource();
+ if (next) setSource(next);
+ }
+ : undefined
+ }
+ />
+ );
+};
+
/**
* The picture the remark was written against, kept with the remark.
*
@@ -63,10 +96,25 @@ interface ThreadEvidenceProps {
const ThreadEvidence = memo<ThreadEvidenceProps>(({ comment, evidence, roundIndex, stale }) => {
const { t } = useTranslation('verify');
const authorColor = useAcceptanceAuthorColor();
+ const scope = useOptionalAcceptanceScope();
+ const refresh = useEvidenceUrlRefresh(scope?.acceptanceId);
// Imported or older evidence may carry no stored size; the picture itself
// knows it once loaded, and until then the crop stays at the top.
const [loaded, setLoaded] = useState<{ height: number; width: number }>();
- if (!evidence.fileUrl || !comment.rect) return null;
+ if (!evidence.fileUrl || !comment.rect)
+ return (
+ <Flexbox gap={4}>
+ {comment.time && <Text fontSize={12}>{formatVideoTime(comment.time.start)}</Text>}
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.comments.evidenceUnavailable')}
+ </Text>
+ {roundIndex !== undefined && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.comments.roundContext', { round: roundIndex })}
+ </Text>
+ )}
+ </Flexbox>
+ );
const size =
evidence.fileWidth && evidence.fileHeight
? { height: evidence.fileHeight, width: evidence.fileWidth }
@@ -74,25 +122,57 @@ const ThreadEvidence = memo<ThreadEvidenceProps>(({ comment, evidence, roundInde
return (
<Flexbox className={styles.wrapper} gap={4}>
- <div className={styles.crop}>
- <div
- style={{
- marginBlockStart: -thumbnailCropOffset(size ?? {}, comment.rect),
- }}
+ {evidence.type === 'video' && comment.time ? (
+ <Button
+ icon={<Icon icon={Play} />}
+ style={{ minHeight: 44, width: THUMBNAIL_WIDTH }}
+ onClick={() =>
+ createModal({
+ content: (
+ <ThreadVideoPreview
+ src={evidence.fileUrl!}
+ mark={{
+ color: authorColor(comment.authorUserId),
+ comment: comment.content,
+ key: comment.id,
+ rect: comment.rect!,
+ time: comment.time!,
+ }}
+ onRefreshSource={refresh ? () => refresh(evidence.id) : undefined}
+ />
+ ),
+ footer: null,
+ styles: { popup: { height: '100dvh', width: '100vw' } },
+ title: t('acceptance.comments.video.showFrame', {
+ time: formatVideoTime(comment.time!.start),
+ }),
+ width: 'min(900px, 96vw)',
+ })
+ }
>
- <AnnotatedImage
- annotations={[{ color: authorColor(comment.authorUserId), rect: comment.rect }]}
- imageStyle={{ width: THUMBNAIL_WIDTH }}
- showComments={false}
- src={evidence.fileUrl}
- onLoad={(event) => {
- const { naturalHeight, naturalWidth } = event.currentTarget;
- if (naturalWidth && naturalHeight)
- setLoaded({ height: naturalHeight, width: naturalWidth });
+ {t('acceptance.comments.video.showFrame', { time: formatVideoTime(comment.time.start) })}
+ </Button>
+ ) : (
+ <div className={styles.crop}>
+ <div
+ style={{
+ marginBlockStart: -thumbnailCropOffset(size ?? {}, comment.rect),
}}
- />
+ >
+ <AnnotatedImage
+ annotations={[{ color: authorColor(comment.authorUserId), rect: comment.rect }]}
+ imageStyle={{ width: THUMBNAIL_WIDTH }}
+ showComments={false}
+ src={evidence.fileUrl}
+ onLoad={(event) => {
+ const { naturalHeight, naturalWidth } = event.currentTarget;
+ if (naturalWidth && naturalHeight)
+ setLoaded({ height: naturalHeight, width: naturalWidth });
+ }}
+ />
+ </div>
</div>
- </div>
+ )}
<span className={styles.caption}>
{stale && roundIndex !== undefined
? t('acceptance.comments.evidenceFromRound', { round: roundIndex })
diff --git a/src/features/Acceptance/Viewer/Comments/VideoCommentEditor.tsx b/src/features/Acceptance/Viewer/Comments/VideoCommentEditor.tsx
new file mode 100644
index 00000000000..c71dcbc11f1
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/VideoCommentEditor.tsx
@@ -0,0 +1,289 @@
+'use client';
+
+import { Icon, Text, toast, useModalContext, useResponsive } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Crosshair } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useSingleton } from '@/hooks/useSingleton';
+
+import type { AcceptanceEvidence } from '../Checks/types';
+import {
+ VideoEvidencePlayer,
+ type VideoEvidencePlayerHandle,
+} from '../Evidence/Video/VideoEvidencePlayer';
+import { formatVideoTime, frameOf } from '../Evidence/Video/videoTime';
+import {
+ CommentWorkspace,
+ DraftEmpty,
+ DraftFooter,
+ DraftNote,
+ DraftPanelHeading,
+ StatusLink,
+} from './CommentWorkspace';
+import { evidenceCommentDraftKey } from './evidenceCommentDraft';
+import type { EvidenceCommentValue } from './EvidenceCommentModal';
+import {
+ orderVideoCommentDrafts,
+ readVideoCommentDrafts,
+ saveVideoCommentDrafts,
+ sendVideoCommentDrafts,
+ type VideoCommentDraft,
+} from './videoCommentDraft';
+
+const styles = stylex.create({
+ stamp: {
+ cursor: 'pointer',
+ display: 'inline-flex',
+ flex: 'none',
+ gap: 4,
+ alignItems: 'center',
+ height: 22,
+ paddingInline: 8,
+ borderWidth: 0,
+ borderRadius: cssVar.borderRadiusSM,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ fontVariantNumeric: 'tabular-nums',
+ color: cssVar.colorText,
+ backgroundColor: { 'default': cssVar.colorFillTertiary, ':hover': cssVar.colorFillSecondary },
+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorPrimaryBorder}` },
+ },
+});
+
+interface VideoCommentEditorProps {
+ acceptanceId: string;
+ active: AcceptanceEvidence;
+ initialTime?: number;
+ onBusyChange: (busy: boolean) => void;
+ onConfirm: (value: EvidenceCommentValue) => Promise<boolean>;
+ /** The number of drafts changed — the evidence strip counts them. */
+ onDraftsChange: () => void;
+ onRefreshEvidenceUrl?: (id: string) => Promise<string | undefined>;
+ strip?: ReactNode;
+ userId: string;
+}
+
+/**
+ * Several comments on one recording, written before any is sent. Each circled
+ * area is its own note with its own moment and words, numbered in playing
+ * order on the frame, the timeline and the list alike. Choosing a note shows
+ * its frame; the drafts survive closing and reloading, and a failed send keeps
+ * exactly the notes that did not go out.
+ */
+export const VideoCommentEditor = ({
+ acceptanceId,
+ active,
+ initialTime,
+ onBusyChange,
+ onConfirm,
+ onDraftsChange,
+ onRefreshEvidenceUrl,
+ strip,
+ userId,
+}: VideoCommentEditorProps) => {
+ const { t } = useTranslation('verify');
+ const { md: desktop = true } = useResponsive();
+ const { close, setCanDismissByClickOutside } = useModalContext();
+ const key = evidenceCommentDraftKey(userId, acceptanceId, active.id);
+ const [notes, setNotes] = useState(() => readVideoCommentDrafts(key));
+ const current = useRef(notes);
+ const [activeId, setActiveId] = useState<string>();
+ const [fresh, setFresh] = useState<string>();
+ const [submitting, setSubmitting] = useState(false);
+ const [unsent, setUnsent] = useState(false);
+ const [src, setSrc] = useState(active.fileUrl!);
+ const player = useRef<VideoEvidencePlayerHandle>(null);
+ const fields = useSingleton(() => new Map<string, HTMLTextAreaElement>());
+
+ const update = (next: VideoCommentDraft[]) => {
+ const counted = next.length !== current.current.length;
+ current.current = next;
+ setNotes(next);
+ saveVideoCommentDrafts(key, next);
+ if (counted) onDraftsChange();
+ };
+ const ordered = orderVideoCommentDrafts(notes);
+ const numberOf = (id: string) => ordered.findIndex((note) => note.clientId === id) + 1;
+ const blocked = ordered.find((note) => !note.content.trim());
+
+ const show = (note: VideoCommentDraft) => {
+ setActiveId(note.clientId);
+ player.current?.focus(note.time);
+ };
+ const edit = (note: VideoCommentDraft) => {
+ show(note);
+ fields.get(note.clientId)?.focus();
+ };
+ const remove = (note: VideoCommentDraft) => {
+ const index = numberOf(note.clientId);
+ const position = current.current.findIndex((item) => item.clientId === note.clientId);
+ update(current.current.filter((item) => item.clientId !== note.clientId));
+ if (activeId === note.clientId) setActiveId(undefined);
+ // Words are the part worth getting back; an empty circle costs one drag.
+ if (!note.content.trim()) return;
+ toast.info({
+ actions: [
+ {
+ label: t('acceptance.comments.undo'),
+ onClick: () => {
+ if (current.current.some((item) => item.clientId === note.clientId)) return;
+ update(current.current.toSpliced(position, 0, note));
+ show(note);
+ },
+ },
+ ],
+ title: t('acceptance.comments.draftRemoved', { index }),
+ });
+ };
+
+ const submit = async () => {
+ if (submitting || ordered.length === 0) return;
+ if (blocked) {
+ edit(blocked);
+ return;
+ }
+ setSubmitting(true);
+ setUnsent(false);
+ onBusyChange(true);
+ setCanDismissByClickOutside(false);
+ try {
+ const done = await sendVideoCommentDrafts(
+ orderVideoCommentDrafts(current.current),
+ (note) => onConfirm({ ...note, evidenceId: active.id }),
+ (id) => update(current.current.filter((note) => note.clientId !== id)),
+ );
+ if (done) close();
+ } catch (cause) {
+ console.error('[acceptance:comments]', cause);
+ setUnsent(true);
+ setActiveId(orderVideoCommentDrafts(current.current)[0]?.clientId);
+ toast.error(t('acceptance.comments.createFailed'));
+ } finally {
+ setSubmitting(false);
+ onBusyChange(false);
+ setCanDismissByClickOutside(true);
+ }
+ };
+
+ let status: ReactNode = t('acceptance.comments.draftSaved');
+ if (unsent && ordered.length > 0)
+ status = t('acceptance.comments.draftsUnsent', { count: ordered.length });
+ else if (ordered.length === 0) status = t('acceptance.comments.draftNeedsRegion');
+ else if (blocked)
+ status = (
+ <StatusLink onClick={() => edit(blocked)}>
+ {t('acceptance.comments.draftNeedsText', { index: numberOf(blocked.clientId) })}
+ </StatusLink>
+ );
+
+ return (
+ <CommentWorkspace
+ inert={submitting}
+ stageMode={'fit'}
+ strip={strip}
+ footer={
+ <DraftFooter
+ count={ordered.length}
+ disabled={ordered.length === 0 || Boolean(blocked)}
+ error={unsent && ordered.length > 0}
+ loading={submitting}
+ status={status}
+ onCancel={close}
+ onSend={() => void submit()}
+ />
+ }
+ panel={
+ <>
+ <DraftPanelHeading count={ordered.length} />
+ {ordered.length === 0 ? (
+ <DraftEmpty body={t('acceptance.comments.video.emptyBody')} />
+ ) : (
+ ordered.map((note, index) => (
+ <DraftNote
+ active={note.clientId === activeId}
+ autoFocus={desktop && note.clientId === fresh}
+ index={index + 1}
+ key={note.clientId}
+ value={note.content}
+ fieldRef={(element) => {
+ if (element) fields.set(note.clientId, element);
+ else fields.delete(note.clientId);
+ }}
+ stamp={
+ <>
+ <button
+ {...stylex.props(styles.stamp)}
+ type={'button'}
+ aria-label={t('acceptance.comments.video.showFrame', {
+ time: formatVideoTime(note.time.start),
+ })}
+ title={t('acceptance.comments.video.showFrame', {
+ time: formatVideoTime(note.time.start),
+ })}
+ onClick={() => show(note)}
+ >
+ <Icon icon={Crosshair} size={12} />
+ {formatVideoTime(note.time.start)}
+ </button>
+ <Text ellipsis fontSize={12} style={{ color: cssVar.colorTextTertiary }}>
+ {t('acceptance.video.frame', { frame: frameOf(note.time.start) })}
+ </Text>
+ </>
+ }
+ onRemove={() => remove(note)}
+ onSubmit={() => void submit()}
+ onChange={(content) =>
+ update(
+ current.current.map((item) =>
+ item.clientId === note.clientId ? { ...item, content } : item,
+ ),
+ )
+ }
+ onFocus={() => {
+ if (activeId !== note.clientId) show(note);
+ }}
+ />
+ ))
+ )}
+ </>
+ }
+ stage={
+ <VideoEvidencePlayer
+ activeMark={activeId}
+ frameMaxHeight={desktop ? 'calc(100cqh - 88px)' : '46svh'}
+ handleRef={player}
+ initialTime={initialTime ?? ordered[0]?.time.start}
+ src={src}
+ marks={ordered.map((note, index) => ({
+ // A draft is annotation red, like a region being drawn on a screenshot.
+ color: cssVar.colorError,
+ comment: note.content,
+ key: note.clientId,
+ label: index + 1,
+ rect: note.rect,
+ time: note.time,
+ }))}
+ onMarkClick={(id) => {
+ setActiveId(id);
+ fields.get(id)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }}
+ onRefreshSource={async () => {
+ const renewed = await onRefreshEvidenceUrl?.(active.id);
+ if (renewed) setSrc(renewed);
+ }}
+ onRegion={(anchor) => {
+ const note = { ...anchor, clientId: crypto.randomUUID(), content: '' };
+ update([...current.current, note]);
+ setActiveId(note.clientId);
+ setFresh(note.clientId);
+ setUnsent(false);
+ }}
+ />
+ }
+ />
+ );
+};
diff --git a/src/features/Acceptance/Viewer/Comments/anchor.test.ts b/src/features/Acceptance/Viewer/Comments/anchor.test.ts
index dea1a007015..6124d04293e 100644
--- a/src/features/Acceptance/Viewer/Comments/anchor.test.ts
+++ b/src/features/Acceptance/Viewer/Comments/anchor.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
-import { commentAnchorId, commentIdFromHash } from './anchor';
+import { commentAnchorId, commentIdFromHash, holdInView } from './anchor';
describe('comment anchors', () => {
it('round-trips a comment id through the fragment', () => {
@@ -17,3 +17,55 @@ describe('comment anchors', () => {
expect(commentIdFromHash('#comment-')).toBeUndefined();
});
});
+
+describe('holding a linked comment in view', () => {
+ let resize: () => void = () => {};
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: () => void) {
+ resize = callback;
+ }
+ disconnect() {
+ resize = () => {};
+ }
+ observe() {}
+ },
+ );
+ afterEach(() => vi.useRealTimers());
+
+ const linked = () => {
+ const scroller = document.createElement('div');
+ scroller.style.overflowY = 'auto';
+ const content = document.createElement('div');
+ const element = document.createElement('div');
+ content.append(element);
+ scroller.append(content);
+ document.body.append(scroller);
+ element.scrollIntoView = vi.fn();
+ return element;
+ };
+
+ // Screenshots above the comment load after the first scroll and push it away.
+ it('re-centres the comment while the content above it grows', () => {
+ const element = linked();
+ holdInView(element, 4000);
+ resize();
+ expect(element.scrollIntoView).toHaveBeenCalledWith({ block: 'center' });
+ });
+
+ it('lets go once the reader scrolls or the content settles', () => {
+ vi.useFakeTimers();
+ const element = linked();
+ holdInView(element, 4000);
+ window.dispatchEvent(new Event('wheel'));
+ resize();
+ expect(element.scrollIntoView).not.toHaveBeenCalled();
+
+ const other = linked();
+ holdInView(other, 4000);
+ vi.advanceTimersByTime(4001);
+ resize();
+ expect(other.scrollIntoView).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Comments/anchor.ts b/src/features/Acceptance/Viewer/Comments/anchor.ts
index 3a4fac90a72..89ecdd679bc 100644
--- a/src/features/Acceptance/Viewer/Comments/anchor.ts
+++ b/src/features/Acceptance/Viewer/Comments/anchor.ts
@@ -25,6 +25,36 @@ export const commentAnchorUrl = (commentId: string) => {
return `${origin}${pathname}${search}#${commentAnchorId(commentId)}`;
};
+/** How long a linked comment is held in view while the evidence above it loads. */
+const SETTLE_MS = 4000;
+const READER_INPUT = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const;
+
+/**
+ * Keep a linked comment centred while the page above it settles.
+ *
+ * The first scroll lands before the screenshots and recordings above the
+ * comment know their size; as they load they push it far below the fold. Each
+ * time the scrolling content grows the comment is centred again, until the
+ * content settles or the reader scrolls on their own — which always wins.
+ * Returns the release.
+ */
+export const holdInView = (element: HTMLElement, duration = SETTLE_MS) => {
+ let scroller = element.parentElement;
+ while (scroller && !/auto|scroll/.test(getComputedStyle(scroller).overflowY))
+ scroller = scroller.parentElement;
+ const observer = new ResizeObserver(() => element.scrollIntoView({ block: 'center' }));
+ for (const child of (scroller ?? document.body).children) observer.observe(child);
+ const release = () => {
+ observer.disconnect();
+ clearTimeout(timer);
+ for (const type of READER_INPUT) window.removeEventListener(type, release, true);
+ };
+ const timer = setTimeout(release, duration);
+ for (const type of READER_INPUT)
+ window.addEventListener(type, release, { capture: true, passive: true });
+ return release;
+};
+
/**
* Which comment the URL points at, and a one-shot scroll to it.
*
@@ -39,14 +69,18 @@ export const useCommentAnchor = (ready: unknown, embedded = false) => {
const { hash } = useLocation();
const anchoredId = embedded ? undefined : commentIdFromHash(hash);
const scrolledTo = useRef<string | undefined>(undefined);
+ const release = useRef<() => void>(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' });
+ release.current?.();
+ element.scrollIntoView({ block: 'center' });
+ release.current = holdInView(element);
}, [anchoredId, ready]);
+ useEffect(() => () => release.current?.(), []);
return anchoredId;
};
diff --git a/src/features/Acceptance/Viewer/Comments/evidenceCommentDraft.test.ts b/src/features/Acceptance/Viewer/Comments/evidenceCommentDraft.test.ts
new file mode 100644
index 00000000000..88e8c29edde
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/evidenceCommentDraft.test.ts
@@ -0,0 +1,38 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ evidenceCommentDraftKey,
+ readEvidenceCommentDraft,
+ saveEvidenceCommentDraft,
+} from './evidenceCommentDraft';
+
+const draft = {
+ clientId: 'stable-retry-id',
+ content: 'Check this image region',
+ rect: { x: 0, y: 0, width: 1, height: 1 },
+};
+
+beforeEach(() => localStorage.clear());
+
+describe('evidence comment drafts', () => {
+ it('restores an image region, text and retry identity after reopening', () => {
+ const key = evidenceCommentDraftKey('alice', 'delivery', 'image-1');
+ saveEvidenceCommentDraft(key, draft);
+ expect(readEvidenceCommentDraft(key)).toEqual(draft);
+ expect(
+ readEvidenceCommentDraft(evidenceCommentDraftKey('bob', 'delivery', 'image-1')),
+ ).toBeUndefined();
+ expect(
+ readEvidenceCommentDraft(evidenceCommentDraftKey('alice', 'delivery', 'image-2')),
+ ).toBeUndefined();
+ saveEvidenceCommentDraft(key);
+ expect(readEvidenceCommentDraft(key)).toBeUndefined();
+ });
+
+ it('ignores corrupt or invalid stored data', () => {
+ localStorage.setItem('bad', '{');
+ expect(readEvidenceCommentDraft('bad')).toBeUndefined();
+ localStorage.setItem('bad', JSON.stringify({ ...draft, rect: { ...draft.rect, x: -1 } }));
+ expect(readEvidenceCommentDraft('bad')).toBeUndefined();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Comments/evidenceCommentDraft.ts b/src/features/Acceptance/Viewer/Comments/evidenceCommentDraft.ts
new file mode 100644
index 00000000000..02d6a10260b
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/evidenceCommentDraft.ts
@@ -0,0 +1,38 @@
+import { z } from 'zod';
+
+export const evidenceCommentDraftSchema = z.object({
+ clientId: z.string().min(1),
+ content: z.string(),
+ rect: z
+ .object({
+ x: z.number().min(0).max(1),
+ y: z.number().min(0).max(1),
+ width: z.number().min(0).max(1),
+ height: z.number().min(0).max(1),
+ })
+ .nullable(),
+});
+
+export type EvidenceCommentDraft = z.infer<typeof evidenceCommentDraftSchema>;
+export const evidenceCommentDraftKey = (userId: string, acceptanceId: string, evidenceId: string) =>
+ `acceptance-comment-draft:${userId}:${acceptanceId}:${evidenceId}`;
+
+export const readEvidenceCommentDraft = (key: string): EvidenceCommentDraft | undefined => {
+ try {
+ const result = evidenceCommentDraftSchema.safeParse(
+ JSON.parse(localStorage.getItem(key) ?? 'null'),
+ );
+ return result.success ? result.data : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export const saveEvidenceCommentDraft = (key: string, draft?: EvidenceCommentDraft) => {
+ try {
+ if (draft) localStorage.setItem(key, JSON.stringify(draft));
+ else localStorage.removeItem(key);
+ } catch {
+ /* Private mode or quota: in-memory editing and retry still work. */
+ }
+};
diff --git a/src/features/Acceptance/Viewer/Comments/historicalThreads.test.ts b/src/features/Acceptance/Viewer/Comments/historicalThreads.test.ts
new file mode 100644
index 00000000000..6abc6d97cf2
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/historicalThreads.test.ts
@@ -0,0 +1,70 @@
+import type { AcceptanceCommentItem, AcceptanceCommentThread } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { AcceptanceEvidence } from '../Checks/types';
+import { historicalCommentEntries } from './historicalThreads';
+
+const evidence = (
+ id: string,
+ type = 'video',
+ fileUrl: string | null = 'https://example.com/video',
+) => ({ fileUrl, id, type }) as AcceptanceEvidence;
+const thread = (
+ id: string,
+ evidenceId: string,
+ time: number | null = 2,
+): AcceptanceCommentThread => ({
+ replies: [],
+ root: {
+ evidenceId,
+ id,
+ rect: { height: 0.2, width: 0.2, x: 0.1, y: 0.1 },
+ time: time === null ? null : { start: time },
+ } as AcceptanceCommentItem,
+});
+const videos = new Map([
+ ['video-a', evidence('video-a')],
+ ['video-b', evidence('video-b')],
+]);
+
+describe('historicalCommentEntries', () => {
+ it('mounts one evidence entry for many roots on the same video, including the same frame', () => {
+ const threads = [
+ thread('a', 'video-a', 2),
+ thread('b', 'video-a', 6),
+ thread('c', 'video-a', 6),
+ ];
+ expect(historicalCommentEntries(threads, videos)).toEqual([
+ { evidence: videos.get('video-a'), type: 'video' },
+ ]);
+ });
+
+ it('keeps different videos separate in first-occurrence order', () => {
+ const threads = [thread('b', 'video-b'), thread('a', 'video-a'), thread('c', 'video-b')];
+ expect(historicalCommentEntries(threads, videos).map((entry) => entry.evidence?.id)).toEqual([
+ 'video-b',
+ 'video-a',
+ ]);
+ });
+
+ it('retains every image, unavailable evidence and incomplete anchor as a readable thread', () => {
+ const items = new Map([
+ ...videos,
+ ['image', evidence('image', 'screenshot')],
+ ['unavailable', evidence('unavailable', 'video', null)],
+ ]);
+ const threads = [
+ thread('a', 'video-a'),
+ thread('b', 'image', null),
+ thread('c', 'image', null),
+ thread('d', 'unavailable'),
+ thread('e', 'missing'),
+ thread('f', 'video-a', null),
+ ];
+ const entries = historicalCommentEntries(threads, items);
+ expect(entries[0]).toEqual({ evidence: videos.get('video-a'), type: 'video' });
+ expect(
+ entries.slice(1).map((entry) => entry.type === 'thread' && entry.thread.root.id),
+ ).toEqual(['b', 'c', 'd', 'e', 'f']);
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Comments/historicalThreads.ts b/src/features/Acceptance/Viewer/Comments/historicalThreads.ts
new file mode 100644
index 00000000000..1da5bc738d3
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/historicalThreads.ts
@@ -0,0 +1,26 @@
+import type { AcceptanceCommentThread } from '@lobechat/types';
+
+import type { AcceptanceEvidence } from '../Checks/types';
+
+export type HistoricalCommentEntry =
+ | { evidence: AcceptanceEvidence; type: 'video' }
+ | { evidence?: AcceptanceEvidence; thread: AcceptanceCommentThread; type: 'thread' };
+
+/** Preserve comment order, sharing one player per original video. */
+export const historicalCommentEntries = (
+ threads: AcceptanceCommentThread[],
+ evidenceById: Map<string, AcceptanceEvidence>,
+): HistoricalCommentEntry[] => {
+ const entries: HistoricalCommentEntry[] = [];
+ const videos = new Set<string>();
+ for (const thread of threads) {
+ const evidence = evidenceById.get(thread.root.evidenceId ?? '');
+ if (evidence?.type === 'video' && evidence.fileUrl && thread.root.time && thread.root.rect) {
+ if (!videos.has(evidence.id)) {
+ videos.add(evidence.id);
+ entries.push({ evidence, type: 'video' });
+ }
+ } else entries.push({ evidence, thread, type: 'thread' });
+ }
+ return entries;
+};
diff --git a/src/features/Acceptance/Viewer/Comments/useCheckComments.tsx b/src/features/Acceptance/Viewer/Comments/useCheckComments.tsx
new file mode 100644
index 00000000000..8f42f828848
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/useCheckComments.tsx
@@ -0,0 +1,135 @@
+import type { AcceptanceCommentThread } from '@lobechat/types';
+import { useCallback, useMemo } from 'react';
+
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { useOptionalAcceptanceScope } from '../AcceptanceScope';
+import type { AcceptanceCheck } from '../Checks/types';
+import { isCommentableEvidence } from '../Evidence/evidence';
+import type { EvidenceOverlayMap } from '../Evidence/overlay';
+import { useAcceptanceBundle, useEvidenceUrlRefresh } from '../useAcceptanceBundle';
+import { canCommentOnAcceptanceEvidence } from '../visibility';
+import { useAcceptanceAuthorColor } from './authorColor';
+import { commentAuthorName } from './CommentCard';
+import CommentThread from './CommentThread';
+import { openEvidenceCommentModal } from './EvidenceCommentModal';
+import { useAcceptanceComments } from './hooks';
+import { threadsForCheck } from './threads';
+
+export const useCheckComments = (check: AcceptanceCheck, proposalOverlays?: EvidenceOverlayMap) => {
+ // 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 refreshEvidenceUrl = useEvidenceUrlRefresh(scope?.acceptanceId);
+ const comments = useAcceptanceComments(scope?.acceptanceId);
+ const authorColor = useAcceptanceAuthorColor();
+ const viewerId = useUserStore(userProfileSelectors.userId);
+ /**
+ * Closing a note is a verdict on it: whoever raised it may close their own,
+ * and the acceptance's reviewers may close anyone's. Ownership is read from
+ * the author, not from `canDelete` — that flag also turns on for a
+ * moderator, and borrowing it would silently hand the same power out.
+ *
+ * Memoized on the identity it reads: the profile arrives after the first
+ * paint, and the overlay memo below would otherwise keep handing its
+ * threads the answer computed while nobody was signed in.
+ */
+ const canResolveThread = useCallback(
+ (thread: AcceptanceCommentThread) =>
+ comments.canApprove ||
+ (Boolean(viewerId) && thread.root.authorUserId === viewerId && !thread.root.deletedAt),
+ [comments.canApprove, viewerId],
+ );
+ 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, time, id } = thread.root;
+ if (!evidenceId || !rect || (deletedAt && thread.replies.length === 0)) return;
+ const bucket = map.get(evidenceId) ?? [];
+ bucket.push({
+ authorAvatar: author.avatar,
+ authorName: commentAuthorName(author),
+ color: authorColor(authorUserId),
+ comment: content,
+ label: index + 1,
+ panel: (
+ <CommentThread
+ canComment={comments.canComment}
+ canResolve={canResolveThread(thread)}
+ thread={thread}
+ {...commentActions}
+ />
+ ),
+ rect,
+ time: time ?? undefined,
+ threadId: id,
+ commentIds: [id, ...thread.replies.map((reply) => reply.id)],
+ 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, canResolveThread, authorColor]);
+ const canCommentEvidence =
+ canCommentOnAcceptanceEvidence(bundle, comments.canComment) &&
+ Boolean(check.result) &&
+ check.evidence.some(isCommentableEvidence);
+ const openEvidenceComment = (initialEvidenceId?: string, initialTime?: number) =>
+ openEvidenceCommentModal({
+ acceptanceId: scope!.acceptanceId,
+ evidence: check.evidence,
+ initialTime,
+ onRefreshEvidenceUrl: refreshEvidenceUrl,
+ initialEvidenceId,
+ onConfirm: async ({ clientId, content, evidenceId, rect, time }) => {
+ await comments.create({
+ anchor: { checkItemId: check.id, evidenceId, rect, time },
+ clientId,
+ content,
+ contextRunId: bundle?.rounds.at(-1)?.run.id,
+ });
+ return true;
+ },
+ });
+
+ return {
+ comments,
+ checkThreads,
+ staleThreads,
+ commentOverlays,
+ canResolveThread,
+ commentActions,
+ canCommentEvidence,
+ openEvidenceComment,
+ refreshEvidenceUrl,
+ };
+};
diff --git a/src/features/Acceptance/Viewer/Comments/videoCommentDraft.test.ts b/src/features/Acceptance/Viewer/Comments/videoCommentDraft.test.ts
new file mode 100644
index 00000000000..7f875ca1721
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/videoCommentDraft.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ orderVideoCommentDrafts,
+ readVideoCommentDrafts,
+ saveVideoCommentDrafts,
+ sendVideoCommentDrafts,
+} from './videoCommentDraft';
+
+const notes = [1, 4].map((start) => ({
+ clientId: `frame-${start}`,
+ content: `Comment at ${start}`,
+ rect: { x: 0.1, y: 0.2, width: 0.3, height: 0.4 },
+ time: { start },
+}));
+beforeEach(() => localStorage.clear());
+
+describe('multi-frame video comments', () => {
+ it('restores independent anchors and text after revisiting multiple frames', () => {
+ saveVideoCommentDrafts('alice:video', notes);
+ expect(readVideoCommentDrafts('alice:video')).toEqual(notes);
+ expect(readVideoCommentDrafts('bob:video')).toEqual([]);
+ });
+ it('keeps only unsent drafts and stable retry ids after a partially failed send', async () => {
+ let pending = [...notes];
+ const remove = (id: string) => {
+ pending = pending.filter((note) => note.clientId !== id);
+ saveVideoCommentDrafts('video', pending);
+ };
+ const send = vi.fn().mockResolvedValueOnce(true).mockRejectedValueOnce(new Error('offline'));
+ await expect(sendVideoCommentDrafts(pending, send, remove)).rejects.toThrow('offline');
+ expect(readVideoCommentDrafts('video')).toEqual([notes[1]]);
+ const retry = vi.fn().mockResolvedValue(true);
+ await sendVideoCommentDrafts(readVideoCommentDrafts('video'), retry, remove);
+ expect(retry.mock.calls[0][0]).toEqual(notes[1]);
+ expect(readVideoCommentDrafts('video')).toEqual([]);
+ });
+ it('numbers notes in playing order, keeping drawing order on a shared frame', () => {
+ const drawn = [6, 2, 6].map((start, index) => ({
+ ...notes[0],
+ clientId: `n${index}`,
+ time: { start },
+ }));
+ expect(orderVideoCommentDrafts(drawn).map((note) => note.clientId)).toEqual(['n1', 'n0', 'n2']);
+ expect(drawn.map((note) => note.clientId)).toEqual(['n0', 'n1', 'n2']);
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Comments/videoCommentDraft.ts b/src/features/Acceptance/Viewer/Comments/videoCommentDraft.ts
new file mode 100644
index 00000000000..548c84e6e46
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/videoCommentDraft.ts
@@ -0,0 +1,48 @@
+import { z } from 'zod';
+
+import { evidenceCommentDraftSchema } from './evidenceCommentDraft';
+
+const noteSchema = evidenceCommentDraftSchema.extend({
+ rect: evidenceCommentDraftSchema.shape.rect.unwrap(),
+ time: z.object({ start: z.number().finite().nonnegative() }),
+});
+const notesSchema = z.array(noteSchema);
+export type VideoCommentDraft = z.infer<typeof noteSchema>;
+
+export const readVideoCommentDrafts = (key: string): VideoCommentDraft[] => {
+ try {
+ return notesSchema.parse(JSON.parse(localStorage.getItem(`${key}:frames`) ?? '[]'));
+ } catch {
+ return [];
+ }
+};
+
+export const saveVideoCommentDrafts = (key: string, notes: VideoCommentDraft[]) => {
+ try {
+ if (notes.length > 0) localStorage.setItem(`${key}:frames`, JSON.stringify(notes));
+ else localStorage.removeItem(`${key}:frames`);
+ } catch {
+ /* Editing and idempotent retry remain available without browser storage. */
+ }
+};
+
+/**
+ * Notes in the order the video plays them, so the numbers on the frame, the
+ * timeline and the list count up together. Notes on one frame keep the order
+ * they were drawn in.
+ */
+export const orderVideoCommentDrafts = (notes: VideoCommentDraft[]) =>
+ notes.toSorted((a, b) => a.time.start - b.time.start);
+
+/** A successful note is removed immediately; a later failure leaves only unsent notes for retry. */
+export const sendVideoCommentDrafts = async (
+ notes: VideoCommentDraft[],
+ send: (note: VideoCommentDraft) => Promise<boolean>,
+ onSent: (id: string) => void,
+) => {
+ for (const note of notes) {
+ if (!(await send({ ...note, content: note.content.trim() }))) return false;
+ onSent(note.clientId);
+ }
+ return true;
+};
diff --git a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx
index 6996f2f7d6c..b61e5834054 100644
--- a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx
@@ -25,12 +25,11 @@ import { IMAGE_EVIDENCE, imageRatio, isAnnotatable, isVisual } from './evidence'
import FloatingCommentAction, { FLOATING_ACTION_HOST } from './FloatingCommentAction';
import type { EvidenceOverlayMap } from './overlay';
import { styles } from './styles';
-import { VideoEvidencePlayer } from './Video/VideoEvidencePlayer';
+import { VideoEvidenceDiscussion } from './Video/VideoEvidenceDiscussion';
/** Flat media for a comparison side — the card frames it, so no own border/radius. */
-const comparisonContent = (item: AcceptanceEvidence, action?: ReactNode) => {
- if (item.type === 'video')
- return <video controls src={item.fileUrl!} style={{ display: 'block', width: '100%' }} />;
+const comparisonContent = (item: AcceptanceEvidence, action?: ReactNode, video?: ReactNode) => {
+ if (item.type === 'video') return video;
if (item.type === 'audio')
return (
<AudioPlayer
@@ -76,7 +75,7 @@ export const EvidenceList = memo<{
* Comment on (or mark) one picture straight from it — floats over each
* annotatable image, labelled for what it opens.
*/
- onComment?: { label: string; open: (id: string) => void };
+ onComment?: { label: string; open: (id: string, time?: number) => void };
onReviewEvidence?: (id: string) => void;
/**
* Regions to draw over an evidence image, keyed by evidence id. Used by the
@@ -116,12 +115,29 @@ export const EvidenceList = memo<{
.flatMap((group) => [group.before!.id, group.after!.id]),
);
+ const videoContent = (item: AcceptanceEvidence, caption?: ReactNode) => (
+ <VideoEvidenceDiscussion
+ caption={caption}
+ chapters={readEvidenceChapters(item.metadata)}
+ evidenceId={item.id}
+ notes={reviewNotes?.filter((note) => note.evidenceId === item.id)}
+ overlays={overlays?.get(item.id)}
+ src={item.fileUrl!}
+ onComment={onComment ? (time) => onComment.open(item.id, time) : undefined}
+ onRefreshSource={onRefreshEvidenceUrl ? () => onRefreshEvidenceUrl(item.id) : undefined}
+ />
+ );
+
const comparisonSide = (item: AcceptanceEvidence) => ({
caption:
readEvidenceComparison(item.metadata)?.label ??
meaningfulEvidenceCaption(item.description) ??
undefined,
- content: comparisonContent(item, commentAction(item)),
+ content: comparisonContent(
+ item,
+ commentAction(item),
+ item.type === 'video' ? videoContent(item) : undefined,
+ ),
});
const consumedScreenshotIds = new Set<string>();
@@ -148,18 +164,7 @@ export const EvidenceList = memo<{
const description = meaningfulEvidenceCaption(item.description);
const caption = description && <span className={styles.caption}>{description}</span>;
if (item.fileUrl && item.type === 'video')
- return (
- <VideoEvidencePlayer
- caption={caption}
- chapters={readEvidenceChapters(item.metadata)}
- key={item.id}
- notes={reviewNotes?.filter((note) => note.evidenceId === item.id)}
- src={item.fileUrl}
- onRefreshSource={
- onRefreshEvidenceUrl ? () => onRefreshEvidenceUrl(item.id) : undefined
- }
- />
- );
+ return <div key={item.id}>{videoContent(item, caption)}</div>;
if (item.fileUrl && item.type === 'audio')
return (
<Flexbox gap={4} key={item.id} width={'100%'}>
@@ -174,7 +179,17 @@ export const EvidenceList = memo<{
{caption}
</Flexbox>
);
- if (!md && onReviewEvidence && item.fileUrl && IMAGE_EVIDENCE.has(item.type)) {
+ const overlay = overlays?.get(item.id);
+ // Posted screenshot threads must remain readable on touch screens too.
+ const hasImageThreads =
+ item.type === 'screenshot' && overlay?.some((note) => note.threadId);
+ if (
+ !md &&
+ onReviewEvidence &&
+ item.fileUrl &&
+ IMAGE_EVIDENCE.has(item.type) &&
+ !hasImageThreads
+ ) {
const action = commentAction(item);
// The tap reviews; the comment shortcut sits beside the button rather
// than inside it, since a button cannot hold another one.
@@ -216,13 +231,14 @@ export const EvidenceList = memo<{
</div>
);
}
- const overlay = overlays?.get(item.id);
if (item.fileUrl && item.type === 'screenshot') {
const run = [item];
const start = sorted.indexOf(item);
for (let index = start + 1; index < sorted.length; index++) {
const next = sorted[index]!;
if (pairedIds.has(next.id) || !next.fileUrl || next.type !== 'screenshot') break;
+ if (!md && onReviewEvidence && !overlays?.get(next.id)?.some((note) => note.threadId))
+ break;
run.push(next);
consumedScreenshotIds.add(next.id);
}
diff --git a/src/features/Acceptance/Viewer/Evidence/FloatingCommentAction.tsx b/src/features/Acceptance/Viewer/Evidence/FloatingCommentAction.tsx
index 8a86b277aa1..1de97a77115 100644
--- a/src/features/Acceptance/Viewer/Evidence/FloatingCommentAction.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/FloatingCommentAction.tsx
@@ -69,6 +69,7 @@ const FloatingCommentAction = memo<{ onClick: () => void; title: string }>(({ on
return (
<div className={styles.rail}>
<ActionIcon
+ aria-label={title}
className={styles.button}
icon={MessageSquarePlus}
size={'small'}
diff --git a/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx b/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx
index b0e24d67f2b..63aa99ab1f4 100644
--- a/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/ScreenshotTiles.tsx
@@ -5,8 +5,10 @@ import { Check, MessageSquare, X } from 'lucide-react';
import { memo, type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useOptionalAcceptanceScope } from '../AcceptanceScope';
+import { commentAnchorId } from '../Comments/anchor';
import { FLOATING_ACTION_HOST } from './FloatingCommentAction';
-import type { EvidenceOverlay } from './overlay';
+import { type EvidenceOverlay, overlayColor } from './overlay';
import {
annotationInSlice,
isPortraitScreenshot,
@@ -14,6 +16,7 @@ import {
screenshotSlices,
screenshotTileWidth,
} from './screenshotSlices';
+import { useImageThreads } from './useImageThreads';
const styles = createStaticStyles(({ css }) => ({
badge: css`
@@ -252,9 +255,7 @@ 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 color = overlayColor(annotation);
const label = annotation.label ?? index + 1;
return (
<div
@@ -346,13 +347,12 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(
const [natural, setNatural] = useState(
fileWidth && fileHeight ? { height: fileHeight, width: fileWidth } : undefined,
);
- const [openedNote, setOpenedNote] = useState<number>();
+ const scope = useOptionalAcceptanceScope();
+ const { openedNote, toggleNote, close } = useImageThreads(annotations, scope?.embedded);
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 }) => {
@@ -368,6 +368,7 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(
const note = opened && (
<div
className={styles.note}
+ id={opened.threadId ? commentAnchorId(opened.threadId) : undefined}
style={{ insetBlockStart: `${Math.min(Math.max(opened.rect.y, 0), 0.62) * 100}%` }}
>
{/*
@@ -380,7 +381,7 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(
className={styles.noteClose}
title={t('acceptance.comments.collapseThread')}
type={'button'}
- onClick={() => setOpenedNote(undefined)}
+ onClick={close}
>
<Icon icon={X} size={12} />
</button>
@@ -412,9 +413,7 @@ export const ScreenshotTiles = memo<ScreenshotTilesProps>(
title={annotation.authorName}
type={'button'}
style={{
- background: annotation.resolved
- ? cssVar.colorTextQuaternary
- : (annotation.color ?? cssVar.colorError),
+ background: overlayColor(annotation),
insetBlockStart: `${Math.min(Math.max(annotation.rect.y, 0), 0.86) * 100}%`,
}}
onClick={() => toggleNote(index)}
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsx
index 7d04228527a..f9fcce05f19 100644
--- a/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useVideo } from '@lobehub/ui';
+import { cx, useVideo } from '@lobehub/ui';
import { styles } from './styles';
import { isOnFrame } from './videoTime';
@@ -16,27 +16,44 @@ const percent = (rect: Rect) => ({
/** A region drawn on a frame, shown only while that frame is on screen. */
export interface FrameRegion {
+ color?: string;
comment?: string;
key: number | string;
+ label?: number | string;
rect: Rect;
start: number;
}
-const Regions = ({ regions }: { regions: FrameRegion[] }) => {
+const Regions = ({ active, regions }: { active?: string; regions: FrameRegion[] }) => {
const time = useVideo((state) => state.time);
const paused = useVideo((state) => state.paused);
return regions
.filter((region) => isOnFrame(region.start, time, paused))
.map((region) => (
- <div className={styles.region} key={region.key} style={percent(region.rect)}>
- {region.comment && <span className={styles.regionLabel}>{region.comment}</span>}
+ <div
+ key={region.key}
+ style={{ ...percent(region.rect), borderColor: region.color }}
+ className={
+ region.label === undefined && region.color === undefined ? styles.region : styles.mark
+ }
+ >
+ {region.label !== undefined ? (
+ <span
+ className={cx(styles.markBadge, region.key === active && styles.markBadgeActive)}
+ style={{ background: region.color }}
+ >
+ {region.label}
+ </span>
+ ) : region.comment ? (
+ <span className={styles.regionLabel}>{region.comment}</span>
+ ) : null}
</div>
));
};
/** Regions follow the playhead; with none, nothing subscribes to it. */
-export const FrameRegions = ({ regions }: { regions: FrameRegion[] }) =>
- regions.length > 0 ? <Regions regions={regions} /> : null;
+export const FrameRegions = ({ active, regions }: { active?: string; regions: FrameRegion[] }) =>
+ regions.length > 0 ? <Regions active={active} regions={regions} /> : null;
export const DraftRegion = ({ rect }: { rect: Rect }) => (
<div className={styles.draft} style={percent(rect)} />
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidenceDiscussion.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidenceDiscussion.tsx
new file mode 100644
index 00000000000..a98a0dc2e35
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidenceDiscussion.tsx
@@ -0,0 +1,263 @@
+'use client';
+
+import type { AcceptanceReviewAnnotation, VerifyEvidenceChapter } from '@lobechat/types';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckCircle2, ChevronRight, MessageSquare } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useOptionalAcceptanceScope } from '../../AcceptanceScope';
+import { commentAnchorId } from '../../Comments/anchor';
+import { type EvidenceOverlay, overlayColor } from '../overlay';
+import { useVideoThreads, type VideoThread } from './useVideoThreads';
+import {
+ VideoEvidencePlayer,
+ type VideoEvidencePlayerHandle,
+ type VideoMark,
+} from './VideoEvidencePlayer';
+import { formatVideoTime } from './videoTime';
+
+const styles = stylex.create({
+ badgeColor: (color: string) => ({ backgroundColor: color }),
+ item: {
+ scrollMarginBlock: 96,
+ borderRadius: cssVar.borderRadius,
+ transition: `background ${cssVar.motionDurationMid}`,
+ },
+ itemOpen: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ boxShadow: `inset 0 0 0 1px ${cssVar.colorBorderSecondary}`,
+ },
+ row: {
+ cursor: 'pointer',
+ display: 'flex',
+ gap: 8,
+ alignItems: 'center',
+ width: '100%',
+ minHeight: 36,
+ paddingBlock: 6,
+ paddingInline: 8,
+ borderWidth: 0,
+ borderRadius: cssVar.borderRadius,
+ fontSize: 14,
+ color: cssVar.colorText,
+ textAlign: 'start',
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorPrimaryBorder}` },
+ outlineOffset: { 'default': null, ':focus-visible': -2 },
+ },
+ badge: {
+ flex: 'none',
+ width: 18,
+ height: 18,
+ borderRadius: '50%',
+ fontSize: 11,
+ fontWeight: 600,
+ lineHeight: '18px',
+ color: cssVar.colorTextLightSolid,
+ textAlign: 'center',
+ },
+ stamp: {
+ flex: 'none',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ fontVariantNumeric: 'tabular-nums',
+ color: cssVar.colorTextSecondary,
+ },
+ author: {
+ overflow: 'hidden',
+ flex: 'none',
+ maxWidth: '30%',
+ fontSize: 12,
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ display: { 'default': null, '@media (width <= 767px)': 'none' },
+ },
+ excerpt: {
+ overflow: 'hidden',
+ flex: '1',
+ minWidth: 0,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ resolved: { color: cssVar.colorTextTertiary },
+ meta: {
+ display: 'inline-flex',
+ flex: 'none',
+ gap: 4,
+ alignItems: 'center',
+ fontSize: 12,
+ color: cssVar.colorTextTertiary,
+ },
+ chevron: {
+ flex: 'none',
+ color: cssVar.colorTextTertiary,
+ transition: {
+ 'default': `transform ${cssVar.motionDurationMid}`,
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ },
+ chevronOpen: { transform: 'rotate(90deg)' },
+ thread: {
+ paddingBlockStart: 0,
+ paddingBlockEnd: 12,
+ paddingInlineStart: 36,
+ paddingInlineEnd: 12,
+ },
+});
+
+/**
+ * A video with its discussion. The posted comments sit under the player as an
+ * index in timeline order — number, moment, who, the first line — so a reader
+ * can scan them without the full threads stacking up below the recording.
+ * Opening one pauses on its frame, lifts its region and unfolds the thread with
+ * its replies and resolve action; a pin on the timeline opens the same row.
+ */
+export const VideoEvidenceDiscussion = ({
+ evidenceId,
+ src,
+ caption,
+ chapters,
+ overlays = [],
+ notes = [],
+ onComment,
+ onRefreshSource,
+}: {
+ caption?: ReactNode;
+ chapters?: VerifyEvidenceChapter[];
+ evidenceId: string;
+ /** Reject notes from an earlier review of this video. */
+ notes?: AcceptanceReviewAnnotation[];
+ onComment?: (time: number) => void;
+ onRefreshSource?: () => Promise<unknown>;
+ overlays?: EvidenceOverlay[];
+ src: string;
+}) => {
+ const { t } = useTranslation('verify');
+ const player = useRef<VideoEvidencePlayerHandle>(null);
+ const scope = useOptionalAcceptanceScope();
+ const { open, openId, threads, toggle } = useVideoThreads(
+ overlays,
+ (thread) => player.current?.focus(thread.time, { reveal: false }),
+ scope?.embedded,
+ );
+
+ // Numbered per video in playing order, so the list counts up the way the
+ // timeline reads; the check-wide thread number would start mid-way.
+ const marks: VideoMark[] = [
+ ...threads.map((item, index) => ({
+ color: overlayColor(item),
+ comment: item.comment,
+ key: item.threadId,
+ label: index + 1,
+ rect: item.rect,
+ time: item.time,
+ })),
+ ...notes.flatMap((note, index) =>
+ note.time
+ ? [
+ {
+ comment: note.comment,
+ key: `review-${evidenceId}-${index}`,
+ rect: note.rect,
+ time: note.time,
+ },
+ ]
+ : [],
+ ),
+ ];
+
+ // Opening a row keeps the reader on the thread they asked for: the player
+ // moves to the moment where it stands, without scrolling the row away (on a
+ // phone the two do not fit on one screen).
+ const select = (item: VideoThread) => {
+ if (toggle(item.threadId)) player.current?.focus(item.time, { reveal: false });
+ };
+
+ return (
+ <Flexbox gap={12}>
+ <VideoEvidencePlayer
+ activeMark={openId}
+ caption={caption}
+ chapters={chapters}
+ handleRef={player}
+ marks={marks}
+ src={src}
+ onComment={onComment}
+ onRefreshSource={onRefreshSource}
+ onMarkClick={(key) => {
+ if (!threads.some((item) => item.threadId === key)) return;
+ open(key);
+ requestAnimationFrame(() =>
+ document
+ .getElementById(`video-thread-${key}`)
+ ?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }),
+ );
+ }}
+ />
+ {threads.length > 0 && (
+ <Flexbox gap={4}>
+ <Text fontSize={12} style={{ paddingInline: 8 }} type={'secondary'}>
+ {t('acceptance.comments.video.listTitle', { count: threads.length })}
+ </Text>
+ {threads.map((item, index) => {
+ const isOpen = openId === item.threadId;
+ const messages = item.commentIds?.length ?? 1;
+ return (
+ <div
+ {...stylex.props([styles.item, isOpen && styles.itemOpen])}
+ id={`video-thread-${item.threadId}`}
+ key={item.threadId}
+ >
+ <button
+ aria-expanded={isOpen}
+ {...stylex.props(styles.row)}
+ type={'button'}
+ onClick={() => select(item)}
+ >
+ <span {...stylex.props(styles.badge, styles.badgeColor(overlayColor(item)))}>
+ {index + 1}
+ </span>
+ <span {...stylex.props(styles.stamp)}>{formatVideoTime(item.time.start)}</span>
+ {/* Open, the thread below names the author and says it in full. */}
+ <span {...stylex.props(styles.author)}>{isOpen ? '' : item.authorName}</span>
+ <span {...stylex.props([styles.excerpt, item.resolved && styles.resolved])}>
+ {isOpen ? '' : item.comment}
+ </span>
+ {messages > 1 && (
+ <span
+ {...stylex.props(styles.meta)}
+ title={t('acceptance.comments.sectionMessages', { count: messages })}
+ >
+ <Icon icon={MessageSquare} size={12} />
+ {messages}
+ </span>
+ )}
+ {item.resolved && (
+ <span {...stylex.props(styles.meta)} title={t('acceptance.comments.resolved')}>
+ <Icon icon={CheckCircle2} size={14} />
+ </span>
+ )}
+ <Icon
+ {...stylex.props([styles.chevron, isOpen && styles.chevronOpen])}
+ icon={ChevronRight}
+ size={14}
+ />
+ </button>
+ {isOpen && (
+ <div {...stylex.props(styles.thread)} id={commentAnchorId(item.threadId)}>
+ {item.panel}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsx
index 3b6fb5d3eb3..c092cacb578 100644
--- a/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsx
@@ -1,146 +1,236 @@
'use client';
import { isFullFrameRect } from '@lobechat/const/verify';
-import type { AcceptanceReviewAnnotation, VerifyEvidenceChapter } from '@lobechat/types';
-import { createStaticStyles, Flexbox, useVideoPlayer, useVideoState, Video } from '@lobehub/ui';
-import type { CSSProperties, ReactNode } from 'react';
-import { memo, useMemo, useState } from 'react';
+import type {
+ AcceptanceCommentTime,
+ AcceptanceReviewAnnotation,
+ VerifyEvidenceChapter,
+} from '@lobechat/types';
+import {
+ cx,
+ Flexbox,
+ useVideo,
+ useVideoPlayer,
+ useVideoState,
+ Video,
+ type VideoPlayer,
+} from '@lobehub/ui';
+import type { CSSProperties, ReactNode, RefObject } from 'react';
+import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { toClaimMarkers, toNoteMarkers, toSections } from './chapters';
+import FloatingCommentAction, { FLOATING_ACTION_HOST } from '../FloatingCommentAction';
+import { noteKeyOf, toClaimMarkers, toNoteMarkers, toSections } from './chapters';
import { readStoredRate, storeRate } from './playbackRate';
-import { FrameRegions } from './VideoChrome';
+import { styles } from './styles';
+import { useVideoRegionGesture } from './useVideoRegionGesture';
+import { DraftRegion, type FrameRegion, FrameRegions } from './VideoChrome';
import { VideoClaimList } from './VideoClaimList';
+import { frameOf } from './videoTime';
-/** Matches the plain `<video>` this replaces, so rows keep their rhythm. */
const MAX_HEIGHT = 360;
-/** Leave room for the controls even when the recording is portrait. */
const MIN_PLAYER_WIDTH = 480;
-const styles = createStaticStyles(({ css }) => ({
- player: css`
- &:fullscreen {
- display: flex;
- flex-direction: column;
- border-radius: 0;
- }
-
- &:fullscreen > [data-video-controls] {
- flex: none;
- }
- `,
- stage: css`
- display: flex;
- justify-content: center;
-
- :fullscreen > & {
- container-type: size;
- flex: 1;
- align-items: center;
-
- min-width: 0;
- min-height: 0;
- }
- `,
- frame: css`
- max-width: var(--acceptance-video-frame-width);
+export interface VideoEvidencePlayerHandle {
+ focus: (time: AcceptanceCommentTime, options?: { reveal?: boolean }) => void;
+}
- :fullscreen & {
- flex: none;
- width: min(100cqw, calc(100cqh * var(--acceptance-video-aspect)));
- max-width: none;
- height: min(100cqh, calc(100cqw / var(--acceptance-video-aspect)));
- }
- `,
-}));
+/** A comment, draft, or rejection note pinned to its original video frame. */
+export interface VideoMark {
+ color?: string;
+ comment?: string;
+ key: string;
+ label?: number | string;
+ rect: AcceptanceReviewAnnotation['rect'];
+ time: NonNullable<AcceptanceReviewAnnotation['time']>;
+}
interface VideoEvidencePlayerProps {
- /** The evidence description — laid out under the player, at the content area's width. */
+ activeMark?: string;
+ /** The description stays at content width even when the frame is portrait. */
caption?: ReactNode;
chapters?: VerifyEvidenceChapter[];
- /** Reviewer notes already made on this video, pinned to the timeline. */
- notes?: AcceptanceReviewAnnotation[];
- /** Re-sign the file link before retrying — an expired link never loads. */
+ frameMaxHeight?: string;
+ handleRef?: RefObject<VideoEvidencePlayerHandle | null>;
+ initialTime?: number;
+ marks?: VideoMark[];
+ onComment?: (time: number) => void;
+ onMarkClick?: (key: string) => void;
onRefreshSource?: () => Promise<unknown>;
+ onRegion?: (note: { rect: AcceptanceReviewAnnotation['rect']; time: { start: number } }) => void;
src: string;
}
-/**
- * A video evidence as a reviewer needs it: speed, frame stepping, the agent's
- * steps as sections and its claims captioned over the frame, and earlier notes
- * pinned where they were made.
- */
+/** Only the drawing surface subscribes to playback; typing does not redraw the workspace. */
+const CommentSurface = ({
+ active,
+ player,
+ regions,
+ onRegion,
+}: {
+ active?: string;
+ onRegion: NonNullable<VideoEvidencePlayerProps['onRegion']>;
+ player: VideoPlayer;
+ regions: FrameRegion[];
+}) => {
+ const ready = useVideo((state) => state.status === 'ready');
+ const frame = useVideo((state) => frameOf(state.time));
+ const paused = useVideo((state) => state.paused);
+ const { t } = useTranslation('verify');
+ const gesture = useVideoRegionGesture(player, onRegion);
+ if (!ready) return null;
+ return (
+ <div className={cx(styles.overlay, styles.drawable)} onPointerDown={gesture.onPointerDown}>
+ <FrameRegions active={active} regions={regions} />
+ {gesture.draft ? (
+ <DraftRegion rect={gesture.draft} />
+ ) : (
+ <div className={styles.hint}>
+ {t(
+ paused
+ ? 'acceptance.comments.video.hintPaused'
+ : 'acceptance.comments.video.hintPlaying',
+ { frame },
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
export const VideoEvidencePlayer = memo<VideoEvidencePlayerProps>(
- ({ caption, chapters = [], notes = [], onRefreshSource, src }) => {
+ ({
+ activeMark,
+ caption,
+ chapters = [],
+ frameMaxHeight,
+ handleRef,
+ initialTime = 0,
+ marks = [],
+ onComment,
+ onMarkClick,
+ onRefreshSource,
+ onRegion,
+ src,
+ }) => {
const { t } = useTranslation('verify');
const player = useVideoPlayer();
const size = useVideoState(player, (state) => state.size);
const aspect = size?.height ? size.width / size.height : 16 / 9;
const frameWidth = Math.round(MAX_HEIGHT * aspect);
const [defaultRate] = useState(readStoredRate);
-
- const timed = useMemo(
- () => notes.flatMap((note) => (note.time ? [{ ...note, time: note.time }] : [])),
- [notes],
+ const root = useRef<HTMLDivElement>(null);
+ const requestedTime = useRef(initialTime);
+ // Seek only once the shared player has metadata; a deep link may arrive before it does.
+ useEffect(() => {
+ let sought = false;
+ const seek = () => {
+ if (sought || player.getState().status !== 'ready') return;
+ sought = true;
+ player.pause();
+ player.seek(requestedTime.current);
+ };
+ seek();
+ return player.subscribe(seek);
+ }, [player, src]);
+ useImperativeHandle(
+ handleRef,
+ () => ({
+ focus: (target, { reveal = true } = {}) => {
+ requestedTime.current = target.start;
+ player.pause();
+ player.seek(target.start);
+ if (reveal) root.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ },
+ }),
+ [player],
);
+
const sections = useMemo(() => toSections(chapters), [chapters]);
const markers = useMemo(
() => [
...toClaimMarkers(chapters, (kind) => t(`acceptance.video.claim.${kind}`)),
...toNoteMarkers(
- timed.map((note, index) => ({
- comment: note.comment,
- key: index,
- start: note.time.start,
+ marks.map((mark) => ({
+ color: mark.color,
+ comment: mark.comment,
+ key: mark.key,
+ start: mark.time.start,
})),
),
],
- [chapters, t, timed],
- );
- const regions = useMemo(
- () =>
- timed
- .filter((note) => !isFullFrameRect(note.rect))
- .map((note, index) => ({
- comment: note.comment,
- key: index,
- rect: note.rect,
- start: note.time.start,
- })),
- [timed],
+ [chapters, marks, t],
);
+ const regions = marks
+ .filter((mark) => !isFullFrameRect(mark.rect))
+ .map((mark) => ({
+ color: mark.color,
+ comment: mark.comment,
+ key: mark.key,
+ label: mark.label,
+ rect: mark.rect,
+ start: mark.time.start,
+ }));
return (
- <Flexbox gap={8} width={'100%'}>
- <Video.Root
- className={styles.player}
- defaultPlaybackRate={defaultRate}
- markers={markers}
- maxHeight={MAX_HEIGHT}
- player={player}
- sections={sections}
- src={src}
- style={
- {
- '--acceptance-video-aspect': aspect,
- '--acceptance-video-frame-width': `${frameWidth}px`,
- 'maxWidth': `min(100%, ${Math.max(MIN_PLAYER_WIDTH, frameWidth)}px)`,
- } as CSSProperties
- }
- onRateChange={storeRate}
- onRetry={onRefreshSource}
- >
- {/* The fullscreen frame fits the space left by the controls, not the viewport width. */}
- <div className={styles.stage}>
- <Video.Frame className={styles.frame}>
- <FrameRegions regions={regions} />
- <Video.Caption />
- <Video.CenterPlay />
- <Video.LoadError />
- </Video.Frame>
- </div>
- <Video.Controls frameStep />
- </Video.Root>
+ <Flexbox gap={8} ref={root} width={'100%'}>
+ <div {...{ [FLOATING_ACTION_HOST]: '' }} style={{ position: 'relative', width: '100%' }}>
+ <Video.Root
+ className={cx(styles.player, styles.compactControls)}
+ defaultPlaybackRate={defaultRate}
+ markers={markers}
+ maxHeight={frameMaxHeight ? undefined : MAX_HEIGHT}
+ player={player}
+ sections={sections}
+ src={src}
+ style={
+ {
+ '--acceptance-video-aspect': aspect,
+ '--acceptance-video-frame-width': frameMaxHeight
+ ? `calc(${frameMaxHeight} * ${aspect})`
+ : `${frameWidth}px`,
+ 'width': frameMaxHeight ? '100%' : undefined,
+ 'maxWidth': frameMaxHeight
+ ? `max(${MIN_PLAYER_WIDTH}px, calc(${frameMaxHeight} * ${aspect}))`
+ : `min(100%, ${Math.max(MIN_PLAYER_WIDTH, frameWidth)}px)`,
+ } as CSSProperties
+ }
+ onRateChange={storeRate}
+ onRetry={onRefreshSource}
+ onMarkerClick={(marker) => {
+ const key = noteKeyOf(marker);
+ if (key !== undefined) onMarkClick?.(key);
+ }}
+ >
+ <div data-acceptance-video-stage className={styles.stage}>
+ <Video.Frame className={styles.frame}>
+ {onRegion ? (
+ <CommentSurface
+ active={activeMark}
+ player={player}
+ regions={regions}
+ onRegion={onRegion}
+ />
+ ) : (
+ <FrameRegions active={activeMark} regions={regions} />
+ )}
+ <Video.Caption />
+ {!onRegion && <Video.CenterPlay />}
+ <Video.LoadError />
+ </Video.Frame>
+ </div>
+ <Video.Controls frameStep />
+ </Video.Root>
+ {onComment && (
+ <FloatingCommentAction
+ title={t('acceptance.comments.commentMedia')}
+ onClick={() => {
+ player.pause();
+ onComment(player.getState().time);
+ }}
+ />
+ )}
+ </div>
{caption && <div style={{ overflowWrap: 'anywhere' }}>{caption}</div>}
<VideoClaimList
chapters={chapters}
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/chapters.ts b/src/features/Acceptance/Viewer/Evidence/Video/chapters.ts
index 528785436fa..e79f7261ca2 100644
--- a/src/features/Acceptance/Viewer/Evidence/Video/chapters.ts
+++ b/src/features/Acceptance/Viewer/Evidence/Video/chapters.ts
@@ -13,6 +13,7 @@ export interface ClaimMarker extends VideoMarker {
}
export interface TimedNote {
+ color?: string;
comment?: string;
end?: number;
key: number | string;
@@ -38,7 +39,7 @@ export const toClaimMarkers = (
// Notes carry only a label: the hover preview names them, the caption stays for claims.
export const toNoteMarkers = (notes: TimedNote[]): VideoMarker[] =>
notes.map((note) => ({
- color: 'error',
+ color: note.color ?? 'error',
key: `note-${note.key}`,
label: note.comment,
time: note.start,
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/styles.ts b/src/features/Acceptance/Viewer/Evidence/Video/styles.ts
index 3e6b4ba8a7c..af14057be85 100644
--- a/src/features/Acceptance/Viewer/Evidence/Video/styles.ts
+++ b/src/features/Acceptance/Viewer/Evidence/Video/styles.ts
@@ -2,6 +2,48 @@ import type { VerifyEvidenceChapterKind } from '@lobechat/types';
import { createStaticStyles, cssVar } from '@lobehub/ui';
export const styles = createStaticStyles(({ css }) => ({
+ player: css`
+ &:fullscreen {
+ display: flex;
+ flex-direction: column;
+ border-radius: 0;
+ }
+
+ &:fullscreen > [data-video-controls] {
+ flex: none;
+ }
+
+ &:fullscreen > [data-acceptance-video-stage] {
+ container-type: size;
+ flex: 1;
+ align-items: center;
+
+ min-width: 0;
+ min-height: 0;
+ }
+
+ &:fullscreen > [data-acceptance-video-stage] > .lobe-video__frame {
+ flex: none;
+ width: min(100cqw, calc(100cqh * var(--acceptance-video-aspect)));
+ max-width: none;
+ height: min(100cqh, calc(100cqw / var(--acceptance-video-aspect)));
+ }
+ `,
+ stage: css`
+ display: flex;
+ justify-content: center;
+ `,
+ frame: css`
+ max-width: var(--acceptance-video-frame-width);
+ `,
+ // Keep stepping and fullscreen visible on a phone; the frame is also named on its comment card.
+ compactControls: css`
+ @media (width <= 767px) {
+ .lobe-video__frame-number {
+ display: none;
+ }
+ }
+ `,
overlay: css`
position: absolute;
inset: 0;
@@ -40,6 +82,50 @@ export const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorError};
`,
+ /**
+ * A comment region, drawn exactly like the region on a screenshot
+ * (`Evidence/Annotation` and `ScreenshotTiles`): a 2px box with two rings —
+ * the dark one separates it from a light frame, the light one from a dark
+ * frame — in the annotation colour (`colorError`) unless the caller passes
+ * the colour the screenshot overlay uses for the same comment.
+ */
+ mark: css`
+ pointer-events: none;
+
+ position: absolute;
+
+ border: 2px solid ${cssVar.colorError};
+ border-radius: 4px;
+
+ box-shadow:
+ 0 0 0 1px rgb(0 0 0 / 45%),
+ inset 0 0 0 1px rgb(255 255 255 / 45%);
+ `,
+ /** The screenshot's numbered badge: 18px disc on the box's top-left corner. */
+ markBadge: css`
+ position: absolute;
+ inset-block-start: -9px;
+ inset-inline-start: -9px;
+
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1;
+ color: ${cssVar.colorTextLightSolid};
+
+ background: ${cssVar.colorError};
+ `,
+ /** Selected reads the way an opened screenshot note does: a light outline on its disc. */
+ markBadgeActive: css`
+ outline: 2px solid ${cssVar.colorTextLightSolid};
+ `,
draft: css`
pointer-events: none;
position: absolute;
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/useVideoRegionGesture.test.ts b/src/features/Acceptance/Viewer/Evidence/Video/useVideoRegionGesture.test.ts
new file mode 100644
index 00000000000..e018e9d61b2
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/Video/useVideoRegionGesture.test.ts
@@ -0,0 +1,54 @@
+import type { VideoPlayer } from '@lobehub/ui';
+import { act, renderHook } from '@testing-library/react';
+import type { PointerEvent as ReactPointerEvent } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useVideoRegionGesture } from './useVideoRegionGesture';
+
+describe('video region gesture', () => {
+ const setup = () => {
+ const clock = {
+ getState: vi.fn(() => ({ paused: false, time: 2.25 })),
+ pause: vi.fn(),
+ toggle: vi.fn(),
+ } as unknown as VideoPlayer;
+ const onRegion = vi.fn();
+ const element = document.createElement('div');
+ element.setPointerCapture = vi.fn();
+ element.getBoundingClientRect = () => ({ left: 0, top: 0, width: 200, height: 100 }) as DOMRect;
+ const hook = renderHook(() => useVideoRegionGesture(clock, onRegion));
+ act(() =>
+ hook.result.current.onPointerDown({
+ currentTarget: element,
+ pointerId: 1,
+ clientX: 20,
+ clientY: 10,
+ } as ReactPointerEvent<HTMLDivElement>),
+ );
+ return { clock, onRegion, element, hook };
+ };
+
+ it('pins the region to the displayed frame at pointer-down, not the later playhead', () => {
+ const { clock, onRegion, element } = setup();
+ vi.mocked(clock.getState).mockReturnValue({ ...clock.getState(), time: 3 });
+ act(() => {
+ element.dispatchEvent(new PointerEvent('pointermove', { clientX: 120, clientY: 60 }));
+ element.dispatchEvent(new PointerEvent('pointerup'));
+ });
+ expect(onRegion).toHaveBeenCalledWith({
+ rect: { x: 0.1, y: 0.1, width: 0.5, height: 0.5 },
+ time: { start: 2.25 },
+ });
+ });
+
+ it('cancels an interrupted gesture without publishing a selection', () => {
+ const { onRegion, element, hook } = setup();
+ act(() => {
+ element.dispatchEvent(new PointerEvent('pointermove', { clientX: 120, clientY: 60 }));
+ element.dispatchEvent(new PointerEvent('pointercancel'));
+ element.dispatchEvent(new PointerEvent('pointerup'));
+ });
+ expect(onRegion).not.toHaveBeenCalled();
+ expect(hook.result.current.draft).toBeNull();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/useVideoRegionGesture.ts b/src/features/Acceptance/Viewer/Evidence/Video/useVideoRegionGesture.ts
new file mode 100644
index 00000000000..a31ce79e984
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/Video/useVideoRegionGesture.ts
@@ -0,0 +1,56 @@
+import type { AcceptanceReviewAnnotation } from '@lobechat/types';
+import type { VideoPlayer } from '@lobehub/ui';
+import type { PointerEvent as ReactPointerEvent } from 'react';
+import { useState } from 'react';
+
+type Rect = AcceptanceReviewAnnotation['rect'];
+
+/** Draw a comment against the frame shown when the gesture starts. */
+export const useVideoRegionGesture = (
+ player: VideoPlayer,
+ onRegion?: (note: { rect: Rect; time: { start: number } }) => void,
+) => {
+ const [draft, setDraft] = useState<Rect | null>(null);
+ const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const element = event.currentTarget;
+ const box = element.getBoundingClientRect();
+ const origin = {
+ x: (event.clientX - box.left) / box.width,
+ y: (event.clientY - box.top) / box.height,
+ };
+ const wasPlaying = !player.getState().paused;
+ const start = player.getState().time;
+ player.pause();
+ element.setPointerCapture(event.pointerId);
+ let current: Rect | null = null;
+ const clamp = (value: number) => Math.min(Math.max(value, 0), 1);
+ const move = (next: PointerEvent) => {
+ const x = clamp((next.clientX - box.left) / box.width);
+ const y = clamp((next.clientY - box.top) / box.height);
+ current = {
+ height: Math.abs(y - origin.y),
+ width: Math.abs(x - origin.x),
+ x: Math.min(x, origin.x),
+ y: Math.min(y, origin.y),
+ };
+ setDraft(current);
+ };
+ const clean = () => {
+ element.removeEventListener('pointermove', move);
+ element.removeEventListener('pointerup', up);
+ element.removeEventListener('pointercancel', cancel);
+ setDraft(null);
+ };
+ const cancel = () => clean();
+ const up = () => {
+ clean();
+ if (current && current.width > 0.02 && current.height > 0.02)
+ onRegion?.({ rect: current, time: { start } });
+ else if (!wasPlaying) player.toggle();
+ };
+ element.addEventListener('pointermove', move);
+ element.addEventListener('pointerup', up);
+ element.addEventListener('pointercancel', cancel);
+ };
+ return { draft, onPointerDown };
+};
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/useVideoThreads.test.ts b/src/features/Acceptance/Viewer/Evidence/Video/useVideoThreads.test.ts
new file mode 100644
index 00000000000..9f7b6cd1dfe
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/Video/useVideoThreads.test.ts
@@ -0,0 +1,111 @@
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { createElement, type PropsWithChildren, useLayoutEffect } from 'react';
+import { MemoryRouter } from 'react-router';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { commentAnchorId } from '../../Comments/anchor';
+import type { EvidenceOverlay } from '../overlay';
+import { useVideoThreads, videoThreadsOf } from './useVideoThreads';
+
+const overlay = (threadId: string, start?: number, replies: string[] = []): EvidenceOverlay => ({
+ commentIds: [threadId, ...replies],
+ rect: { height: 0.2, width: 0.2, x: 0.1, y: 0.1 },
+ threadId,
+ time: start === undefined ? undefined : { start },
+});
+
+const overlays = [overlay('late', 6), overlay('image'), overlay('early', 2, ['early-reply'])];
+
+const router = (commentId?: string) =>
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(MemoryRouter, {
+ children,
+ initialEntries: [
+ `/acceptance/test/checks/check#${commentId ? commentAnchorId(commentId) : ''}`,
+ ],
+ });
+ };
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('video threads', () => {
+ it('lists only timed threads, in playing order', () => {
+ expect(videoThreadsOf(overlays).map((item) => item.threadId)).toEqual(['early', 'late']);
+ });
+
+ it('keeps one thread unfolded and folds it on a second press', () => {
+ const { result } = renderHook(() => useVideoThreads(overlays, vi.fn()), { wrapper: router() });
+ expect(result.current.openId).toBeUndefined();
+
+ act(() => {
+ expect(result.current.toggle('early')).toBe(true);
+ });
+ expect(result.current.openId).toBe('early');
+ act(() => result.current.open('late'));
+ expect(result.current.openId).toBe('late');
+ act(() => {
+ expect(result.current.toggle('late')).toBe(false);
+ });
+ expect(result.current.openId).toBeUndefined();
+ });
+
+ it('opens the thread a reply link addresses and shows its frame once', () => {
+ const onAnchor = vi.fn();
+ const { result, rerender } = renderHook(() => useVideoThreads(overlays, onAnchor), {
+ wrapper: router('early-reply'),
+ });
+ expect(result.current.openId).toBe('early');
+ expect(onAnchor).toHaveBeenCalledWith(expect.objectContaining({ threadId: 'early' }));
+
+ act(() => result.current.toggle('early'));
+ rerender();
+ expect(result.current.openId).toBeUndefined();
+ expect(onAnchor).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['early', 'early-reply'])(
+ 'scrolls to %s after asynchronously loaded comments unfold',
+ (commentId) => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+ const target = document.createElement('div');
+ target.id = commentAnchorId(commentId);
+ target.scrollIntoView = vi.fn();
+ const onAnchor = vi.fn();
+ const { result, rerender } = renderHook(
+ ({ items }) => {
+ const state = useVideoThreads(items, onAnchor);
+ // The thread's DOM is committed only when the addressed row opens.
+ useLayoutEffect(() => {
+ if (state.openId === 'early') document.body.append(target);
+ return () => target.remove();
+ }, [state.openId]);
+ return state;
+ },
+ { initialProps: { items: [] as EvidenceOverlay[] }, wrapper: router(commentId) },
+ );
+ expect(target.scrollIntoView).not.toHaveBeenCalled();
+ rerender({ items: overlays });
+ expect(result.current.openId).toBe('early');
+ expect(target.scrollIntoView).toHaveBeenCalledWith({ block: 'center' });
+ expect(onAnchor).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('does not claim the page fragment in an embedded viewer', () => {
+ const onAnchor = vi.fn();
+ const { result } = renderHook(() => useVideoThreads(overlays, onAnchor, true), {
+ wrapper: router('early-reply'),
+ });
+ expect(result.current.openId).toBeUndefined();
+ expect(onAnchor).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Evidence/Video/useVideoThreads.ts b/src/features/Acceptance/Viewer/Evidence/Video/useVideoThreads.ts
new file mode 100644
index 00000000000..a050e22854d
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/Video/useVideoThreads.ts
@@ -0,0 +1,64 @@
+import type { AcceptanceCommentTime } from '@lobechat/types';
+import { useEffect, useRef, useState } from 'react';
+import { useLocation } from 'react-router';
+
+import { commentIdFromHash, useCommentAnchor } from '../../Comments/anchor';
+import type { EvidenceOverlay } from '../overlay';
+
+export type VideoThread = EvidenceOverlay & {
+ threadId: string;
+ time: AcceptanceCommentTime;
+};
+
+/** The posted threads on one video, in the order it plays them. */
+export const videoThreadsOf = (overlays: EvidenceOverlay[]) =>
+ overlays
+ .filter((item): item is VideoThread => Boolean(item.time && item.threadId))
+ .toSorted((a, b) => a.time.start - b.time.start);
+
+/** The thread a comment link points at — its root or any reply in it. */
+export const threadAddressedBy = (threads: VideoThread[], commentId?: string) =>
+ commentId
+ ? threads.find((item) => item.threadId === commentId || item.commentIds?.includes(commentId))
+ : undefined;
+
+/**
+ * Which posted thread under a video is unfolded. One at a time: opening a
+ * thread is reading it on its frame, and the frame can only show one moment.
+ * A comment link opens its thread once and asks the caller to show its frame.
+ */
+export const useVideoThreads = (
+ overlays: EvidenceOverlay[],
+ onAnchor: (thread: VideoThread) => void,
+ embedded = false,
+) => {
+ const { hash } = useLocation();
+ const anchored = embedded ? undefined : commentIdFromHash(hash);
+ const threads = videoThreadsOf(overlays);
+ const [openId, setOpenId] = useState(() => threadAddressedBy(threads, anchored)?.threadId);
+ const handled = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ const thread = threadAddressedBy(threads, anchored);
+ if (!thread || handled.current === anchored) return;
+ handled.current = anchored;
+ setOpenId(thread.threadId);
+ onAnchor(thread);
+ // The list arrives after the fragment is read; re-check when it does.
+ }, [anchored, overlays]);
+
+ // Expanding an asynchronously loaded thread commits its root/reply anchors
+ // in a second render. Retry the scroll after that commit, not just on fetch.
+ useCommentAnchor(openId, embedded);
+
+ return {
+ open: (id: string) => setOpenId(id),
+ openId,
+ threads,
+ /** A second press on the open row folds it. */
+ toggle: (id: string) => {
+ const opening = openId !== id;
+ setOpenId(opening ? id : undefined);
+ return opening;
+ },
+ };
+};
diff --git a/src/features/Acceptance/Viewer/Evidence/evidence.ts b/src/features/Acceptance/Viewer/Evidence/evidence.ts
index 224aaca741c..82a3d38ca09 100644
--- a/src/features/Acceptance/Viewer/Evidence/evidence.ts
+++ b/src/features/Acceptance/Viewer/Evidence/evidence.ts
@@ -20,12 +20,14 @@ export const hasAnnotatableEvidence = (check: AcceptanceCheck) =>
/**
* What a reject can point into: images by region, videos by frame or span.
- * Discussion threads stay image-only ({@link isAnnotatable}) — their anchor has
- * no time yet.
+ * Discussion uses the same media capability; its video anchors carry a time.
*/
export const isRejectable = (item: AcceptanceEvidence) =>
isAnnotatable(item) || (Boolean(item.fileUrl) && item.type === 'video');
+/** Discussion can point at images and video, independently of a decision. */
+export const isCommentableEvidence = isRejectable;
+
export const hasRejectableEvidence = (check: AcceptanceCheck) => check.evidence.some(isRejectable);
/**
diff --git a/src/features/Acceptance/Viewer/Evidence/overlay.test.ts b/src/features/Acceptance/Viewer/Evidence/overlay.test.ts
new file mode 100644
index 00000000000..083f4112f19
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/overlay.test.ts
@@ -0,0 +1,13 @@
+import { cssVar } from '@lobehub/ui';
+import { describe, expect, it } from 'vitest';
+
+import { overlayColor } from './overlay';
+
+describe('overlayColor', () => {
+ // Screenshots and videos draw posted comments through this one rule.
+ it('greys a settled mark, keeps an open one in its colour, falls back to annotation red', () => {
+ expect(overlayColor({ color: 'author-hue', resolved: true })).toBe(cssVar.colorTextQuaternary);
+ expect(overlayColor({ color: 'author-hue' })).toBe('author-hue');
+ expect(overlayColor({})).toBe(cssVar.colorError);
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Evidence/overlay.ts b/src/features/Acceptance/Viewer/Evidence/overlay.ts
index 31eebfc53ac..508474c0eeb 100644
--- a/src/features/Acceptance/Viewer/Evidence/overlay.ts
+++ b/src/features/Acceptance/Viewer/Evidence/overlay.ts
@@ -1,4 +1,5 @@
-import type { AcceptanceReviewAnnotation } from '@lobechat/types';
+import type { AcceptanceCommentTime, AcceptanceReviewAnnotation } from '@lobechat/types';
+import { cssVar } from '@lobehub/ui';
import type { ReactNode } from 'react';
/**
@@ -21,6 +22,8 @@ export interface EvidenceOverlay {
/** Author colour — border, badge and marker share it. Falls back to the error red. */
color?: string;
comment?: string;
+ /** Root and reply permalinks all open the same evidence thread. */
+ commentIds?: 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.
@@ -35,6 +38,18 @@ export interface EvidenceOverlay {
rect: AcceptanceReviewAnnotation['rect'];
/** A handled thread reads as settled rather than an open concern. */
resolved?: boolean;
+ threadId?: string;
+ time?: AcceptanceCommentTime;
}
export type EvidenceOverlayMap = Map<string, EvidenceOverlay[]>;
+
+/**
+ * The colour of a posted mark — box, number, pin — wherever it is drawn:
+ * a settled one drops to grey so it does not compete with open ones, an open
+ * one wears its overlay colour, and a mark without one falls back to the
+ * annotation red. Screenshots and videos share it so a comment reads the same
+ * on either.
+ */
+export const overlayColor = ({ color, resolved }: Pick<EvidenceOverlay, 'color' | 'resolved'>) =>
+ resolved ? cssVar.colorTextQuaternary : (color ?? cssVar.colorError);
diff --git a/src/features/Acceptance/Viewer/Evidence/useImageThreads.test.ts b/src/features/Acceptance/Viewer/Evidence/useImageThreads.test.ts
new file mode 100644
index 00000000000..bc3fbb0e77d
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/useImageThreads.test.ts
@@ -0,0 +1,87 @@
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { createElement, type PropsWithChildren, useLayoutEffect } from 'react';
+import { MemoryRouter, useNavigate } from 'react-router';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { commentAnchorId } from '../Comments/anchor';
+import type { EvidenceOverlay } from './overlay';
+import { useImageThreads } from './useImageThreads';
+
+const annotations: EvidenceOverlay[] = ['first', 'second'].map((threadId) => ({
+ threadId,
+ commentIds: [threadId, `${threadId}-reply`],
+ rect: { x: 0.1, y: 0.1, width: 0.2, height: 0.2 },
+}));
+const router = (id = '') =>
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(MemoryRouter, {
+ children,
+ initialEntries: [`/acceptance/test/check/c1#${id ? commentAnchorId(id) : ''}`],
+ });
+ };
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('image comment links', () => {
+ it.each(['second', 'second-reply'])(
+ 'opens and scrolls to %s after comments arrive asynchronously',
+ (id) => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+ const target = document.createElement('div');
+ target.id = commentAnchorId(id);
+ target.scrollIntoView = vi.fn();
+ const { result, rerender } = renderHook(
+ ({ items }) => {
+ const state = useImageThreads(items);
+ useLayoutEffect(() => {
+ if (state.openedNote === 1) document.body.append(target);
+ return () => target.remove();
+ }, [state.openedNote]);
+ return state;
+ },
+ { initialProps: { items: [] as EvidenceOverlay[] }, wrapper: router(id) },
+ );
+ expect(target.scrollIntoView).not.toHaveBeenCalled();
+ rerender({ items: annotations });
+ expect(result.current.openedNote).toBe(1);
+ expect(target.scrollIntoView).toHaveBeenCalledWith({ block: 'center' });
+ act(() => result.current.close());
+ rerender({ items: [...annotations] });
+ expect(result.current.openedNote).toBeUndefined();
+ },
+ );
+
+ it('follows another fragment during navigation and allows manual pin toggling', () => {
+ const { result } = renderHook(
+ () => ({ ...useImageThreads(annotations), navigate: useNavigate() }),
+ { wrapper: router('first') },
+ );
+ expect(result.current.openedNote).toBe(0);
+ act(() => result.current.navigate('#comment-second-reply'));
+ expect(result.current.openedNote).toBe(1);
+ act(() => result.current.toggleNote(0));
+ expect(result.current.openedNote).toBe(0);
+ act(() => result.current.toggleNote(0));
+ expect(result.current.openedNote).toBeUndefined();
+ });
+
+ it('leaves unrelated images and embedded viewers closed', () => {
+ const { result } = renderHook(() => useImageThreads(annotations), {
+ wrapper: router('another-image'),
+ });
+ expect(result.current.openedNote).toBeUndefined();
+ const embedded = renderHook(() => useImageThreads(annotations, true), {
+ wrapper: router('first'),
+ });
+ expect(embedded.result.current.openedNote).toBeUndefined();
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Evidence/useImageThreads.ts b/src/features/Acceptance/Viewer/Evidence/useImageThreads.ts
new file mode 100644
index 00000000000..ed6724e6a27
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Evidence/useImageThreads.ts
@@ -0,0 +1,33 @@
+import { useEffect, useRef, useState } from 'react';
+import { useLocation } from 'react-router';
+
+import { commentIdFromHash, useCommentAnchor } from '../Comments/anchor';
+import type { EvidenceOverlay } from './overlay';
+
+/** Image pins open manually or through a root/reply link once their comments arrive. */
+export const useImageThreads = (annotations: EvidenceOverlay[] = [], embedded = false) => {
+ const { hash } = useLocation();
+ const addressed = embedded ? undefined : commentIdFromHash(hash);
+ const index = addressed
+ ? annotations.findIndex(
+ (item) => item.threadId === addressed || item.commentIds?.includes(addressed),
+ )
+ : -1;
+ const [openedNote, setOpenedNote] = useState<number>();
+ const handled = useRef<string | undefined>(undefined);
+ useEffect(() => {
+ if (index < 0 || handled.current === addressed) return;
+ handled.current = addressed;
+ setOpenedNote(index);
+ }, [addressed, index]);
+
+ // The panel and its anchors mount in the render after selecting the pin.
+ useCommentAnchor(openedNote, embedded || index < 0);
+
+ return {
+ openedNote,
+ close: () => setOpenedNote(undefined),
+ toggleNote: (index: number) =>
+ setOpenedNote((current) => (current === index ? undefined : index)),
+ };
+};
diff --git a/src/features/Acceptance/Viewer/visibility.test.ts b/src/features/Acceptance/Viewer/visibility.test.ts
index caab65f8dcd..2e20457a4df 100644
--- a/src/features/Acceptance/Viewer/visibility.test.ts
+++ b/src/features/Acceptance/Viewer/visibility.test.ts
@@ -9,8 +9,8 @@ import {
} from './visibility';
describe('canCommentOnAcceptanceEvidence', () => {
- it('hides standalone region comments from the acceptance author', () => {
- expect(canCommentOnAcceptanceEvidence({ isOwner: true }, true)).toBe(false);
+ it('allows the acceptance author to comment without rejecting', () => {
+ expect(canCommentOnAcceptanceEvidence({ isOwner: true }, true)).toBe(true);
});
it('keeps region comments available to another viewer with comment access', () => {
diff --git a/src/features/Acceptance/Viewer/visibility.ts b/src/features/Acceptance/Viewer/visibility.ts
index f85693e483e..184bb39858f 100644
--- a/src/features/Acceptance/Viewer/visibility.ts
+++ b/src/features/Acceptance/Viewer/visibility.ts
@@ -34,8 +34,8 @@ export const isReadOnlyAcceptanceDecider = (
canApprove: boolean,
) => Boolean(bundle) && !canReviewAcceptance(bundle) && canApprove;
-/** Authors give region feedback through the check's rejection action. */
+/** Evidence discussion follows comment access, independently of review decisions. */
export const canCommentOnAcceptanceEvidence = (
bundle: { isOwner: boolean } | null | undefined,
canComment: boolean,
-) => canComment && bundle?.isOwner === false;
+) => canComment && Boolean(bundle);