🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(acceptance): review video evidence by frame and span, with agent chapters (#20194)
Arvin Xu20a6eb7f1991
diff --git a/apps/cli/src/commands/acceptanceEvidence.ts b/apps/cli/src/commands/acceptanceEvidence.tsindex 5cdaef82f82..9d69b5561f2 100644--- a/apps/cli/src/commands/acceptanceEvidence.ts+++ b/apps/cli/src/commands/acceptanceEvidence.ts@@ -109,7 +109,13 @@ export async function uploadReportEvidence(const absolutePath = path.resolve(params.dir, input.path);const type = evidenceTypeForFile(absolutePath);const description = evidenceDescriptionForFile(input.description, absolutePath);- const metadata = input.comparison ? { comparison: input.comparison } : undefined;+ const metadata =+ input.comparison || input.chapters+ ? {+ ...(input.chapters ? { chapters: input.chapters } : {}),+ ...(input.comparison ? { comparison: input.comparison } : {}),+ }+ : undefined;let fileId: string | undefined;let missing = false;try {diff --git a/apps/cli/src/commands/acceptanceRun.test.ts b/apps/cli/src/commands/acceptanceRun.test.tsindex cd81455f013..16fa650a50a 100644--- a/apps/cli/src/commands/acceptanceRun.test.ts+++ b/apps/cli/src/commands/acceptanceRun.test.ts@@ -60,6 +60,7 @@ describe('acceptance publication with missing evidence', () => {client.verify.uploadEvidence.mutate.mockResolvedValue({ id: 'evidence-1' });dir = await mkdtemp(path.join(tmpdir(), 'lh-evidence-'));await writeFile(path.join(dir, "screen's shot.png"), 'image fixture');+ await writeFile(path.join(dir, 'scroll.mp4'), 'video fixture');await writeFile(path.join(dir, 'output.txt'), 'Observed the expected response.');});@@ -627,6 +628,34 @@ describe('acceptance publication with missing evidence', () => {expect(process.exitCode).toBeUndefined();});+ it('uploads a video with its chapters so the reviewer can seek to each claim', async () => {+ const chapters = [+ { kind: 'step', label: 'Scroll #3', t: 6 },+ { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },+ ];+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [+ {+ evidence: [{ chapters, description: 'five scrolls at the top', path: 'scroll.mp4' }],+ id: 'scroll',+ name: '滑到顶部后继续上滑不出现骨架',+ status: 'passed',+ },+ ],+ plan: [+ { id: 'scroll', requiredEvidence: ['video'], title: '滑到顶部后继续上滑不出现骨架' },+ ],+ }),+ );+ await run('ingest', dir, '--json');++ expect(client.verify.uploadEvidence.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ metadata: { chapters }, type: 'video' }),+ );+ });+it('retries only the failed attachment, reusing its file and preserving its caption and comparison', async () => {const description = "Before: user's input $(printf should-not-expand)";const comparison = { id: 'input', role: 'before' };diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.tsindex 9b28d546b22..ce7a3f911a6 100644--- a/apps/cli/src/commands/verify.test.ts+++ b/apps/cli/src/commands/verify.test.ts@@ -10,6 +10,7 @@ import {deriveReportVerdict,evidenceTypeForFile,formatAnnotationRegion,+ formatDisputedChapter,genericContextFromResult,inlineTextEvidenceForFile,originFromEnv,@@ -287,6 +288,55 @@ describe('reportEvidence — comparison normalization', () => {});});+describe('reportEvidence — video chapters', () => {+ beforeEach(() => {+ vi.mocked(log.warn).mockClear();+ });++ it('carries well-formed chapters on a video, sorted by time', () => {+ const [item] = reportEvidence([+ {+ chapters: [+ { kind: 'check', note: 'no skeleton', t: 7.9 },+ { kind: 'step', label: 'Scroll #1', t: 2 },+ ],+ path: 'proof/scroll.mp4',+ },+ ]);++ expect(item.chapters).toEqual([+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'check', note: 'no skeleton', t: 7.9 },+ ]);+ expect(log.warn).not.toHaveBeenCalled();+ });++ // A dropped marker is a claim the agent believes the reviewer will see.+ it('names how many markers it dropped and why', () => {+ const [item] = reportEvidence([+ {+ chapters: [+ { kind: 'step', label: 'Open', t: 0 },+ { kind: 'check', t: 3 },+ ],+ path: 'clip.webm',+ },+ ]);++ expect(item.chapters).toEqual([{ kind: 'step', label: 'Open', t: 0 }]);+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('dropped 1 of 2 chapters'));+ });++ it('ignores chapters on a still image, and a chapters field that is not a list', () => {+ expect(+ reportEvidence([{ chapters: [{ kind: 'step', label: 'x', t: 0 }], path: 'a.png' }])[0]+ .chapters,+ ).toBeUndefined();+ expect(reportEvidence([{ chapters: 'intro', path: 'a.mp4' }])[0].chapters).toBeUndefined();+ expect(log.warn).toHaveBeenCalledTimes(2);+ });+});+describe('visualizationMetadata', () => {const input = {datasets: [@@ -1476,6 +1526,37 @@ describe('formatAnnotationRegion', () => {expect(formatAnnotationRegion({ comment: 'just a note' })).toBeUndefined();expect(formatAnnotationRegion({ rect: { x: 0.1 } })).toBeUndefined();});+ it('leads with the frame on a video, then the region circled on it', () => {+ expect(+ formatAnnotationRegion(+ { evidenceId: 'ev-1', rect, time: { start: 7.2 } },+ new Map([['ev-1', 'scroll.mp4']]),+ ),+ ).toBe('scroll.mp4 @ frame at 0:07.20 · 31%,24% · 12%×3%');+ });++ it('prints a span, and no region at all when the note covers the whole frame', () => {+ expect(+ formatAnnotationRegion({+ evidenceId: 'ev-1',+ rect: { height: 1, width: 1, x: 0, y: 0 },+ time: { end: 67.65, start: 66.75 },+ }),+ ).toBe('ev-1 @ 1:06.75–1:07.65');+ });+});++describe('formatDisputedChapter', () => {+ it('quotes the agent claim the reviewer objected to', () => {+ expect(+ formatDisputedChapter({ kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 }),+ ).toBe('your check at 0:07.90: "no skeleton after scroll #3"');+ });++ it('says nothing when there is no claim to quote', () => {+ expect(formatDisputedChapter(undefined)).toBeUndefined();+ expect(formatDisputedChapter({ kind: 'check', t: 1 })).toBeUndefined();+ });});describe('file evidence descriptions', () => {diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/verifyAcceptance.tsindex 8d6ea326710..4336df76699 100644--- a/apps/cli/src/commands/verifyAcceptance.ts+++ b/apps/cli/src/commands/verifyAcceptance.ts@@ -15,7 +15,7 @@ import { collectCommentFeedback } from './acceptanceCommentFeedback';import { attachAcceptanceFlowCommands } from './acceptanceFlow';import { attachAcceptanceRunCommands } from './acceptanceRun';import type { ReviewAnnotationRegion } from './verifyHelpers';-import { formatAnnotationRegion, parseSubjectRef } from './verifyHelpers';+import { formatAnnotationRegion, formatDisputedChapter, parseSubjectRef } from './verifyHelpers';/*** Resolve an acceptance from either its uuid or a `type:id` subject reference —@@ -456,6 +456,8 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecatif (annotation.comment && annotation.comment !== entry.comment)console.log(` ${pc.dim('region:')} ${annotation.comment}`);if (annotation.region) console.log(` ${pc.dim(`└ ${annotation.region}`)}`);+ const disputed = formatDisputedChapter(annotation.disputes);+ if (disputed) console.log(` ${pc.dim(`└ disputes ${disputed}`)}`);}if (entry.fileIds?.length)console.log(` ${pc.dim(`attachments: ${entry.fileIds.join(', ')}`)}`);diff --git a/apps/cli/src/commands/verifyHelpers.ts b/apps/cli/src/commands/verifyHelpers.tsindex b404dc4aa42..4ded3475791 100644--- a/apps/cli/src/commands/verifyHelpers.ts+++ b/apps/cli/src/commands/verifyHelpers.ts@@ -4,16 +4,20 @@ import path from 'node:path';import type {AcceptanceSubjectType,+ VerifyEvidenceChapter,VerifyRunOrigin,VerifyRunScenario,VerifySurface,} from '@lobechat/const/verify';import {acceptanceSubjectTypes,+ formatVideoTimestamp,GOMS_KLM_TRACE_FILE,+ isFullFrameRect,isProgrammaticTestCheck,normalizeVerifySurface,PROGRAMMATIC_TEST_CHECK_HINT,+ readEvidenceChapters,verifyEvidenceTypes,verifyRunScenarios,verifySurfaces,@@ -139,6 +143,8 @@ export function inlineTextEvidenceForFile(/** Normalize a case's `evidence` field (string | string[] | {path}[]) to path strings. */export interface ReportEvidenceInput {+ /** Video only: agent markers on the timeline — steps it took, claims it checked, flags it raised. */+ chapters?: VerifyEvidenceChapter[];comparison?: {id: string;label?: string;@@ -419,6 +425,7 @@ export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {}const layout = comparison?.layout === 'vertical' ? 'vertical' : undefined;return {+ chapters: reportEvidenceChapters(evidencePath, value.chapters),comparison:id && (role === 'before' || role === 'after')? { id, label: firstString(comparison?.label), layout, role }@@ -430,6 +437,33 @@ export function reportEvidence(evidence: unknown): ReportEvidenceInput[] {.filter((item): item is ReportEvidenceInput => item !== null);}+/**+ * A video's chapters, with every dropped marker named: a marker the reviewer+ * never sees is a claim the agent believes it made, so the author must know.+ */+function reportEvidenceChapters(+ evidencePath: string,+ raw: unknown,+): VerifyEvidenceChapter[] | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (evidenceTypeForFile(evidencePath) !== 'video') {+ log.warn(`evidence ${evidencePath}: chapters only apply to video evidence — ignoring them`);+ return undefined;+ }+ if (!Array.isArray(raw)) {+ log.warn(`evidence ${evidencePath}: chapters must be an array — ignoring them`);+ return undefined;+ }+ const chapters = readEvidenceChapters(raw) ?? [];+ const dropped = raw.length - chapters.length;+ if (dropped > 0) {+ log.warn(+ `evidence ${evidencePath}: dropped ${dropped} of ${raw.length} chapters — each needs a non-negative "t" (seconds), a "kind" of step/check/flag, a "label" for a step and a "note" for a check or flag`,+ );+ }+ return chapters.length > 0 ? chapters : undefined;+}+export function firstString(...values: unknown[]): string | undefined {return values.find((v): v is string => typeof v === 'string' && v.length > 0);}@@ -1015,13 +1049,22 @@ export function statusColor(status: string): string {return pc.dim(status);}-/** A region a reviewer circled on one evidence image. */+/** A region a reviewer circled on one evidence image, or on one video frame or span. */export interface ReviewAnnotationRegion {comment?: string;+ /** The agent chapter the reviewer disagrees with. */+ disputes?: { kind?: string; note?: string; t?: number };evidenceId?: string;rect?: { height?: number; width?: number; x?: number; y?: number };+ time?: { end?: number; start?: number };}+/** `m:ss.cc` — shared with the acceptance page so both read the same moment. */+export const formatVideoTime = formatVideoTimestamp;++const isSeconds = (value?: number): value is number =>+ typeof value === 'number' && Number.isFinite(value) && value >= 0;+const asPercent = (value?: number) =>typeof value === 'number' && Number.isFinite(value) ? `${Math.round(value * 100)}%` : undefined;@@ -1031,7 +1074,8 @@ const asPercent = (value?: number) =>* The comment alone is not enough to act on: a screenshot usually has several* plausible targets, and without the image and the rect the reader has to guess* which one was circled. `rect` is normalized to the image box (0–1), so it is- * printed as percentages.+ * printed as percentages. On a video the frame or span comes first, since the+ * reader has to seek there before any region means anything.** Returns `undefined` when the annotation carries no location at all — an older* review, or one made before regions existed.@@ -1044,20 +1088,49 @@ export function formatAnnotationRegion(? (evidenceLabels?.get(annotation.evidenceId) ?? annotation.evidenceId): undefined;- const { rect } = annotation;+ const { rect, time } = annotation;+ let moment: string | undefined;+ if (isSeconds(time?.start))+ moment = isSeconds(time.end)+ ? `${formatVideoTime(time.start)}–${formatVideoTime(time.end)}`+ : `frame at ${formatVideoTime(time.start)}`;+ // A video note that marks a moment without circling an area spans the whole+ // frame; printing "0%,0% · 100%×100%" would read as a real region.+ const wholeFrame =+ moment !== undefined &&+ rect !== undefined &&+ isFullFrameRect({+ height: rect.height ?? 0,+ width: rect.width ?? 0,+ x: rect.x ?? -1,+ y: rect.y ?? -1,+ });+const x = asPercent(rect?.x);const y = asPercent(rect?.y);const width = asPercent(rect?.width);const height = asPercent(rect?.height);const at = x && y ? `${x},${y}` : undefined;const size = width && height ? `${width}×${height}` : undefined;- const position = [at, size].filter(Boolean).join(' · ');+ const position = [moment, wholeFrame ? undefined : at, wholeFrame ? undefined : size]+ .filter(Boolean)+ .join(' · ');if (!label && !position) return undefined;if (!position) return label;return label ? `${label} @ ${position}` : position;}+/**+ * The agent's own claim a reviewer objected to, quoted back so the repair run+ * sees exactly which of its statements was judged wrong.+ */+export function formatDisputedChapter(disputes?: ReviewAnnotationRegion['disputes']) {+ if (!disputes?.note) return undefined;+ const at = isSeconds(disputes.t) ? ` at ${formatVideoTime(disputes.t)}` : '';+ return `your ${disputes.kind ?? 'claim'}${at}: "${disputes.note}"`;+}+/** Keep file identity when small text artifacts are stored inline. */export function evidenceDescriptionForFile(description?: string,diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.tsindex 83285b915ac..e89ff6c5ad4 100644--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts@@ -673,6 +673,42 @@ describe('verifyRouter', () => {).rejects.toThrow('Provide exactly one of `content` or `fileId`.');});+ it('stores only well-formed chapters, and only on video evidence', async () => {+ const chapters = [+ { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'check', t: 3 }, // a claim without a note says nothing+ { kind: 'guess', note: 'unknown kind', t: 4 },+ { kind: 'flag', note: 'negative time', t: -1 },+ ];+ modelMocks.findResultById.mockResolvedValue({ id: 'result-1' });++ await createCaller().uploadEvidence({+ checkResultId: 'result-1',+ fileId: 'files-video',+ metadata: { chapters, comparison: { id: 'pair', role: 'after' } },+ type: 'video',+ });+ await createCaller().uploadEvidence({+ checkResultId: 'result-1',+ fileId: 'files-shot',+ metadata: { chapters },+ type: 'screenshot',+ });++ expect(modelMocks.createEvidence.mock.calls.map(([row]) => row.metadata)).toEqual([+ {+ chapters: [+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'check', note: 'no skeleton after scroll #3', t: 7.9 },+ ],+ comparison: { id: 'pair', role: 'after' },+ },+ null,+ ]);+ modelMocks.findResultById.mockReset();+ });+it('rejects evidence without inline content or fileId', async () => {await expect(createCaller().uploadEvidence({diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex 7418813980d..e477fa0fd81 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -5,6 +5,7 @@ import {acceptanceVisibilities,reviewAdjudications,reviewProposalEdits,+ verifyEvidenceChapterKinds,} from '@lobechat/const/verify';import type { AcceptanceAttachment } from '@lobechat/types';import { verifyCheckDefinitionSchema } from '@lobechat/types';@@ -53,6 +54,37 @@ import {import { canManageAcceptance, filterManageableAcceptances } from './_helpers/acceptanceWriteScope';import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';+/**+ * A reviewer's circled region. On video evidence it also carries the frame+ * (`time.start`) or span (`time.start`–`time.end`) it is about, and optionally+ * quotes the agent chapter it disputes.+ */+const reviewAnnotationSchema = z.object({+ comment: z.string().max(2000).optional(),+ disputes: z+ .object({+ kind: z.enum(verifyEvidenceChapterKinds),+ note: z.string().max(500).optional(),+ t: z.number().min(0),+ })+ .optional(),+ evidenceId: z.string(),+ rect: z.object({+ height: z.number().min(0).max(1),+ width: z.number().min(0).max(1),+ x: z.number().min(0).max(1),+ y: z.number().min(0).max(1),+ }),+ time: z+ .object({ end: z.number().min(0).optional(), start: z.number().min(0) })+ .refine((time) => time.end === undefined || time.end > time.start, {+ message: 'time.end must be after time.start',+ })+ .optional(),+});++const reviewAnnotationsSchema = z.array(reviewAnnotationSchema).max(20).optional();+const flowDefinitionSchema = z.object({title: z.string().min(1).max(200),entryNodeId: z.string().uuid(),@@ -329,21 +361,7 @@ export const acceptanceRouter = router({attemptId: z.string().uuid(),review: z.enum(['accepted', 'rejected']),comment: z.string().max(4000),- annotations: z- .array(- z.object({- comment: z.string().max(2000).optional(),- evidenceId: z.string(),- rect: z.object({- height: z.number().min(0).max(1),- width: z.number().min(0).max(1),- x: z.number().min(0).max(1),- y: z.number().min(0).max(1),- }),- }),- )- .max(20)- .optional(),+ annotations: reviewAnnotationsSchema,fileIds: z.array(z.string()).max(10).optional(),}),)@@ -983,21 +1001,7 @@ export const acceptanceRouter = router({z.object({action: z.enum(acceptanceCheckReviewActions),- annotations: z- .array(- z.object({- comment: z.string().max(2000).optional(),- evidenceId: z.string(),- rect: z.object({- height: z.number().min(0).max(1),- width: z.number().min(0).max(1),- x: z.number().min(0).max(1),- y: z.number().min(0).max(1),- }),- }),- )- .max(20)- .optional(),+ annotations: reviewAnnotationsSchema,checkItemIds: z.array(z.string()).min(1).max(200),comment: z.string().max(2000).optional(),fileIds: z.array(z.string()).max(10).optional(),diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex 55bf794162b..b683bce2a8f 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -1,5 +1,6 @@import { fetchAcceptanceSkillBundle } from '@lobechat/builtin-skills/acceptance';import {+ normalizeEvidenceMetadata,normalizeVerifySurface,verifyRunScenarios,verifySurfaces,@@ -969,7 +970,7 @@ export const verifyRouter = router({content: input.content ?? null,description: input.description ?? null,fileId: input.fileId ?? null,- metadata: input.metadata ?? null,+ metadata: normalizeEvidenceMetadata(input.metadata, input.type) ?? null,type: input.type,});}),diff --git a/apps/server/src/services/expertise/annotationRegion.test.ts b/apps/server/src/services/expertise/annotationRegion.test.tsnew file mode 100644index 00000000000..810791dac56--- /dev/null+++ b/apps/server/src/services/expertise/annotationRegion.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { renderAnnotationRegion } from './annotationRegion';++const rect = { height: 0.2, width: 0.5, x: 0.1, y: 0.3 };++describe('renderAnnotationRegion', () => {+ it('describes a circled screenshot region by frame and position', () => {+ expect(+ renderAnnotationRegion({ comment: 'too faint', evidenceId: 'ev', rect }, 'frame 2'),+ ).toBe(' circled on frame 2 at 10%,30% sized 50%×20%: too faint');+ });++ // The frame is never attached, so coordinates would describe a picture the+ // model cannot see; it gets the moment and the words, and is told why.+ it('places a video note in time without a region the model cannot see', () => {+ expect(+ renderAnnotationRegion({ comment: 'skeleton', evidenceId: 'ev', rect, time: { start: 7.2 } }),+ ).toBe(+ ' marked at 7.2s into the video (video frame not attached — judge from the note alone): skeleton',+ );+ expect(+ renderAnnotationRegion({+ evidenceId: 'ev',+ rect: { height: 1, width: 1, x: 0, y: 0 },+ time: { end: 7.65, start: 6.75 },+ }),+ ).toBe(+ ' marked from 6.75s to 7.65s of the video (video frame not attached — judge from the note alone): (no note)',+ );+ });++ it('quotes the agent claim the reviewer disputes', () => {+ expect(+ renderAnnotationRegion({+ comment: 'it flashed before this frame',+ disputes: { kind: 'check', note: 'no skeleton', t: 7.9 },+ evidenceId: 'ev',+ rect: { height: 1, width: 1, x: 0, y: 0 },+ time: { start: 7.9 },+ }),+ ).toBe(+ ` marked at 7.9s into the video (video frame not attached — judge from the note alone) (disputing the agent's check: "no skeleton"): it flashed before this frame`,+ );+ });+});diff --git a/apps/server/src/services/expertise/annotationRegion.ts b/apps/server/src/services/expertise/annotationRegion.tsnew file mode 100644index 00000000000..94351e3adc9--- /dev/null+++ b/apps/server/src/services/expertise/annotationRegion.ts@@ -0,0 +1,34 @@+import { isFullFrameRect } from '@lobechat/const/verify';+import type { AcceptanceReviewAnnotation } from '@lobechat/types';++// Regions are normalized 0-1; percentages read better to a model than raw floats.+const pct = (value: number) => `${Math.round(value * 100)}%`;++const seconds = (value: number) => `${Number(value.toFixed(2))}s`;++/**+ * One reviewer annotation as a prompt line: where it points (image frame label,+ * video moment, circled region) and what the reviewer said about it.+ *+ * Video frames are never attached to these prompts, so a video note keeps its+ * moment and the reviewer's words but not a region: coordinates on a picture+ * the model cannot see would invite it to imagine what was circled.+ */+export const renderAnnotationRegion = (annotation: AcceptanceReviewAnnotation, frame?: string) => {+ const { disputes, rect, time } = annotation;+ let when = '';+ if (time)+ when =+ time.end === undefined+ ? ` at ${seconds(time.start)} into the video`+ : ` from ${seconds(time.start)} to ${seconds(time.end)} of the video`;+ let at = '';+ if (time && !frame) at = ' (video frame not attached — judge from the note alone)';+ // A video note over the whole frame marks a moment, not an area.+ else if (rect && !(time && isFullFrameRect(rect)))+ at = ` at ${pct(rect.x)},${pct(rect.y)} sized ${pct(rect.width)}×${pct(rect.height)}`;+ const disputed = disputes?.note+ ? ` (disputing the agent's ${disputes.kind}: "${disputes.note}")`+ : '';+ return ` ${time ? 'marked' : 'circled'}${frame ? ` on ${frame}` : ''}${when}${at}${disputed}: ${annotation.comment?.trim() || '(no note)'}`;+};diff --git a/apps/server/src/services/expertise/consolidation.ts b/apps/server/src/services/expertise/consolidation.tsindex e4c0bf185cc..1abb348c690 100644--- a/apps/server/src/services/expertise/consolidation.ts+++ b/apps/server/src/services/expertise/consolidation.ts@@ -29,6 +29,7 @@ import { AiGenerationService } from '@/server/services/aiGeneration';import { FileService } from '@/server/services/file';import { resolveModelReadableFrameUrl } from '@/server/services/verify/modelFrames';+import { renderAnnotationRegion } from './annotationRegion';import { resolveExpertiseModelConfig } from './modelConfig';const log = debug('lobe-server:expertise-consolidation');@@ -60,8 +61,6 @@ const MAX_SHIPPED = 6;/** Total frames inlined. Each is a full base64 body, so this is a payload budget. */const MAX_FRAMES = 10;-const pct = (value: number) => `${Math.round(value * 100)}%`;-const ConsolidationSchema = z.object({currentLimitsArePlaceholder: z.boolean(),generalized: z.boolean(),@@ -397,13 +396,9 @@ export class ExpertiseConsolidationService {},frameLabel: Map<string, string>,) => {- const regions = (delivery.detail?.annotations ?? []).map((annotation) => {- const frame = frameLabel.get(`${delivery.id}:${annotation.evidenceId}`);- const at = annotation.rect- ? ` at ${pct(annotation.rect.x)},${pct(annotation.rect.y)} sized ${pct(annotation.rect.width)}×${pct(annotation.rect.height)}`- : '';- return ` circled${frame ? ` on ${frame}` : ''}${at}: ${annotation.comment?.trim() || '(no note)'}`;- });+ const regions = (delivery.detail?.annotations ?? []).map((annotation) =>+ renderAnnotationRegion(annotation, frameLabel.get(`${delivery.id}:${annotation.evidenceId}`)),+ );const frames = [...frameLabel].filter(([key]) => key.startsWith(`${delivery.id}:`)).map(([, label]) => label);diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex 37e224ecbbc..39de07f3f12 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -41,6 +41,7 @@ import { AiGenerationService } from '@/server/services/aiGeneration';import { FileService } from '@/server/services/file';import { resolveModelReadableFrameUrl } from '@/server/services/verify/modelFrames';+import { renderAnnotationRegion } from './annotationRegion';import type { ConsolidationResult } from './consolidation';import { ExpertiseConsolidationService } from './consolidation';import { resolveExpertiseModelConfig } from './modelConfig';@@ -58,9 +59,6 @@ const MAX_CONTEXT_CHARS = 24_000;const MAX_REJECTION_FRAMES = 8;const VISUAL_REJECTION_EVIDENCE_TYPES = new Set(['screenshot', 'gif']);-/** Normalized 0-1 region coordinates read better to a model as percentages. */-const pct = (value: number) => `${Math.round(value * 100)}%`;-const LESSON_CODE_PATTERN = /^P-\d+$/;const AnalysisSchema = z.object({domains: z.array(@@ -521,14 +519,9 @@ export class ExpertiseIngestionService {);const rendered = labelled.map((rejection) => {- const regions = (rejection.detail?.annotations ?? []).map((annotation) => {- const frame = frameLabelByEvidence.get(annotation.evidenceId);- // Regions are normalized 0-1; percentages read better to a model than raw floats.- const at = annotation.rect- ? ` at ${pct(annotation.rect.x)},${pct(annotation.rect.y)} sized ${pct(annotation.rect.width)}×${pct(annotation.rect.height)}`- : '';- return ` circled${frame ? ` on ${frame}` : ''}${at}: ${annotation.comment?.trim() || '(no note)'}`;- });+ const regions = (rejection.detail?.annotations ?? []).map((annotation) =>+ renderAnnotationRegion(annotation, frameLabelByEvidence.get(annotation.evidenceId)),+ );return [`[${rejection.ref}] promised: ${rejection.title ?? '(untitled check)'}`,rejection.detail?.comment?.trim() && ` said: ${rejection.detail.comment.trim()}`,diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 7085429c2a5..783d87ba23d 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -330,6 +330,44 @@"acceptance.tray.goalModal.save": "Save goal","acceptance.tray.goalModal.setTitle": "Set the goal","acceptance.verdict.inProgress": "Acceptance in progress",+ "acceptance.video.annotateHint": "Press on the video to pause on that frame and circle a region; press M to mark the whole frame, or drag the lane below the timeline to comment on a span.",+ "acceptance.video.captionsHide": "Hide agent notes",+ "acceptance.video.captionsShow": "Show agent notes",+ "acceptance.video.circled": "circled",+ "acceptance.video.claim.check": "Agent's self-check",+ "acceptance.video.claim.flag": "Agent flagged",+ "acceptance.video.claim.step": "Agent step",+ "acceptance.video.claimsSummary": "Agent notes in this recording: {{checks}} self-checks · {{flags}} flagged",+ "acceptance.video.clearRange": "Clear span (Esc)",+ "acceptance.video.commentRange": "Comment on this span",+ "acceptance.video.dispute": "Disagree",+ "acceptance.video.disputed": "Disputed",+ "acceptance.video.download": "Download file",+ "acceptance.video.frame": "Frame {{frame}}",+ "acceptance.video.fullscreen": "Full screen",+ "acceptance.video.hintPaused": "Drag to circle the problem · frame {{frame}}",+ "acceptance.video.hintPlaying": "Press to pause and circle this frame",+ "acceptance.video.inPoint": "In point {{time}}",+ "acceptance.video.keysFrame": "frame by frame",+ "acceptance.video.keysRange": "span in / out",+ "acceptance.video.loadFailed": "The video failed to load — its link may have expired",+ "acceptance.video.loop": "Loop",+ "acceptance.video.markFrame": "Mark this frame",+ "acceptance.video.nextFrame": "Next frame",+ "acceptance.video.noteEmpty": "(no note)",+ "acceptance.video.notePlaceholderDispute": "What is wrong with this claim?",+ "acceptance.video.notePlaceholderFrame": "What is wrong on this frame?",+ "acceptance.video.notePlaceholderRange": "What happens during this span?",+ "acceptance.video.notesEmpty": "After you circle, mark a frame or select a span on the video, your notes appear here.",+ "acceptance.video.outPoint": "Out point {{time}}",+ "acceptance.video.pause": "Pause",+ "acceptance.video.play": "Play",+ "acceptance.video.previousFrame": "Previous frame",+ "acceptance.video.rangeLane": "Drag here to select a span · or press I / O",+ "acceptance.video.rangeSeconds": "{{seconds}}s",+ "acceptance.video.reload": "Reload",+ "acceptance.video.seek": "Seek",+ "acceptance.video.speed": "Speed","acceptance.viewFullReport": "View full report","acceptance.workspace.actions.delete": "Delete","acceptance.workspace.actions.markAccepted": "Mark as accepted",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 76b94f59d2d..5d272786fed 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -235,7 +235,7 @@"acceptance.review.acceptAll": "全部验收","acceptance.review.acceptAllDone": "已全部验收","acceptance.review.acceptedNote": "已于 {{time}} 确认验收",- "acceptance.review.annotate": "在截图上圈选评论",+ "acceptance.review.annotate": "在证据上标注评论","acceptance.review.annotateHint": "在图片上拖拽画框圈出区域,并为该区域留下评论。","acceptance.review.annotationPlaceholder": "区域 {{index}} 的问题…","acceptance.review.attach": "添加截图",@@ -330,6 +330,44 @@"acceptance.tray.goalModal.save": "保存目标","acceptance.tray.goalModal.setTitle": "设定目标","acceptance.verdict.inProgress": "验收进行中",+ "acceptance.video.annotateHint": "在画面上按下即暂停在当前帧并框选;按 M 标注整帧;在时间轴下方的细轨道上拖动可评论一段区间。",+ "acceptance.video.captionsHide": "隐藏 Agent 说明",+ "acceptance.video.captionsShow": "显示 Agent 说明",+ "acceptance.video.circled": "框选",+ "acceptance.video.claim.check": "Agent 自查",+ "acceptance.video.claim.flag": "Agent 提示",+ "acceptance.video.claim.step": "Agent 操作",+ "acceptance.video.claimsSummary": "Agent 在录屏里留下的说法:{{checks}} 条自查 · {{flags}} 条提示",+ "acceptance.video.clearRange": "清除区间(Esc)",+ "acceptance.video.commentRange": "评论这段",+ "acceptance.video.dispute": "有异议",+ "acceptance.video.disputed": "已提异议",+ "acceptance.video.download": "下载原文件",+ "acceptance.video.frame": "帧 {{frame}}",+ "acceptance.video.fullscreen": "全屏",+ "acceptance.video.hintPaused": "拖动框出问题区域 · 帧 {{frame}}",+ "acceptance.video.hintPlaying": "按下即暂停并框选当前帧",+ "acceptance.video.inPoint": "入点 {{time}}",+ "acceptance.video.keysFrame": "逐帧",+ "acceptance.video.keysRange": "入点 / 出点",+ "acceptance.video.loadFailed": "视频加载失败,可能是链接已过期",+ "acceptance.video.loop": "循环播放",+ "acceptance.video.markFrame": "标注此帧",+ "acceptance.video.nextFrame": "下一帧",+ "acceptance.video.noteEmpty": "(无文字)",+ "acceptance.video.notePlaceholderDispute": "这条说法哪里不对?",+ "acceptance.video.notePlaceholderFrame": "这一帧哪里不对?",+ "acceptance.video.notePlaceholderRange": "这段时间里发生了什么?",+ "acceptance.video.notesEmpty": "在左侧视频上框选、标注整帧或选一段区间后,评论会出现在这里。",+ "acceptance.video.outPoint": "出点 {{time}}",+ "acceptance.video.pause": "暂停",+ "acceptance.video.play": "播放",+ "acceptance.video.previousFrame": "上一帧",+ "acceptance.video.rangeLane": "在此拖动选一段区间 · 或按 I / O",+ "acceptance.video.rangeSeconds": "{{seconds}} 秒",+ "acceptance.video.reload": "重新加载",+ "acceptance.video.seek": "进度",+ "acceptance.video.speed": "倍速","acceptance.viewFullReport": "查看完整报告","acceptance.workspace.actions.delete": "删除","acceptance.workspace.actions.markAccepted": "标记为已验收",diff --git a/packages/const/src/verify.test.ts b/packages/const/src/verify.test.tsindex 01f95e619ac..946be5707ab 100644--- a/packages/const/src/verify.test.ts+++ b/packages/const/src/verify.test.ts@@ -10,6 +10,8 @@ import type {VerifierType,VerifyCheckResultStatus,VerifyEvidenceCapturedBy,+ VerifyEvidenceChapter as VerifyEvidenceChapterType,+ VerifyEvidenceChapterKind,VerifyEvidenceType,VerifyOnFailStrategy,VerifyRunOrigin as VerifyRunOriginType,@@ -34,6 +36,8 @@ import type {verifierTypes,verifyCheckResultStatuses,verifyEvidenceCapturedBy,+ VerifyEvidenceChapter,+ verifyEvidenceChapterKinds,verifyEvidenceTypes,verifyOnFailStrategies,VerifyRunOrigin,@@ -44,7 +48,13 @@ import type {verifyUserDecisions,verifyVerdicts,} from './verify';-import { isProgrammaticTestCheck, normalizeVerifySurface } from './verify';+import {+ formatVideoTimestamp,+ isProgrammaticTestCheck,+ normalizeEvidenceMetadata,+ normalizeVerifySurface,+ readEvidenceChapters,+} from './verify';/*** `@lobechat/types` declares these unions independently — it cannot import them@@ -71,6 +81,10 @@ describe('verify vocabulary', () => {(typeof verifyEvidenceCapturedBy)[number]>().toEqualTypeOf<VerifyEvidenceCapturedBy>();expectTypeOf<VerifyRunOrigin>().toEqualTypeOf<VerifyRunOriginType>();+ expectTypeOf<+ (typeof verifyEvidenceChapterKinds)[number]+ >().toEqualTypeOf<VerifyEvidenceChapterKind>();+ expectTypeOf<VerifyEvidenceChapter>().toEqualTypeOf<VerifyEvidenceChapterType>();expectTypeOf<(typeof acceptanceSubjectTypes)[number]>().toEqualTypeOf<AcceptanceSubjectType>();expectTypeOf<(typeof acceptanceStatuses)[number]>().toEqualTypeOf<AcceptanceStatus>();expectTypeOf<@@ -160,3 +174,90 @@ describe('isProgrammaticTestCheck', () => {expect(isProgrammaticTestCheck('', undefined, null)).toBe(false);});});++describe('readEvidenceChapters', () => {+ it('keeps well-formed markers sorted by time and trims their text', () => {+ expect(+ readEvidenceChapters({+ chapters: [+ { kind: 'check', note: ' no skeleton ', t: 7.9 },+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'flag', note: 'request count 0 → 1', t: 7 },+ ],+ }),+ ).toEqual([+ { kind: 'step', label: 'Scroll #1', t: 2 },+ { kind: 'flag', note: 'request count 0 → 1', t: 7 },+ { kind: 'check', note: 'no skeleton', t: 7.9 },+ ]);+ });++ it('drops markers that cannot be placed or say nothing, instead of failing', () => {+ expect(+ readEvidenceChapters([+ { kind: 'step', t: 1 }, // a step needs a label+ { kind: 'check', label: 'only a label', t: 2 }, // a claim needs a note+ { kind: 'guess', note: 'unknown kind', t: 3 },+ { kind: 'flag', note: 'negative', t: -1 },+ { kind: 'flag', note: 'not a number', t: '4' },+ null,+ ]),+ ).toBeUndefined();+ expect(readEvidenceChapters({ comparison: {} })).toBeUndefined();+ expect(readEvidenceChapters('chapters')).toBeUndefined();+ });++ it('caps a runaway list at 100 markers', () => {+ const chapters = Array.from({ length: 150 }, (_, i) => ({+ kind: 'step',+ label: `#${i}`,+ t: i,+ }));+ expect(readEvidenceChapters(chapters)).toHaveLength(100);+ });+});++describe('normalizeEvidenceMetadata', () => {+ const chapters = [+ { kind: 'step', label: 'Open', t: 0 },+ { kind: 'check', t: 1 },+ ];++ it('keeps only valid chapters on a video and leaves other keys alone', () => {+ expect(normalizeEvidenceMetadata({ chapters, comparison: { id: 'a' } }, 'video')).toEqual({+ chapters: [{ kind: 'step', label: 'Open', t: 0 }],+ comparison: { id: 'a' },+ });+ });++ it('strips chapters from media without a timeline', () => {+ expect(normalizeEvidenceMetadata({ chapters, comparison: { id: 'a' } }, 'screenshot')).toEqual({+ comparison: { id: 'a' },+ });+ expect(normalizeEvidenceMetadata({ chapters }, 'screenshot')).toBeNull();+ });++ it('passes metadata without chapters through untouched', () => {+ const metadata = { comparison: { id: 'a' } };+ expect(normalizeEvidenceMetadata(metadata, 'video')).toBe(metadata);+ expect(normalizeEvidenceMetadata(undefined, 'video')).toBeUndefined();+ });+});++describe('formatVideoTimestamp', () => {+ it('formats to the hundredth', () => {+ expect(formatVideoTimestamp(7.2)).toBe('0:07.20');+ expect(formatVideoTimestamp(66.75)).toBe('1:06.75');+ });++ // Rounding the seconds after taking the minutes produced `0:60.00`.+ it('carries a rounded-up second into the next minute', () => {+ expect(formatVideoTimestamp(59.999)).toBe('1:00.00');+ expect(formatVideoTimestamp(119.996)).toBe('2:00.00');+ });++ it('reads an unusable time as the start', () => {+ expect(formatVideoTimestamp(Number.NaN)).toBe('0:00.00');+ expect(formatVideoTimestamp(-1)).toBe('0:00.00');+ });+});diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.tsindex 22d0155b549..d7fcfdbf9f3 100644--- a/packages/const/src/verify.ts+++ b/packages/const/src/verify.ts@@ -371,6 +371,100 @@ export const verifyEvidenceCapturedBy = [] as const;export type VerifyEvidenceCapturedBy = (typeof verifyEvidenceCapturedBy)[number];+/**+ * How an agent marker on a video reads.+ *+ * - step: an action the agent performed, logged while driving the recording+ * - check: something the agent verified on this frame — a claim for the reviewer+ * to audit, never a pass+ * - flag: an anomaly the agent noticed and judged harmless, disclosed so the+ * reviewer can disagree+ */+export const verifyEvidenceChapterKinds = ['check', 'flag', 'step'] as const;+export type VerifyEvidenceChapterKind = (typeof verifyEvidenceChapterKinds)[number];++/** An agent-authored marker on a video evidence (`verify_evidence.metadata.chapters`). */+export interface VerifyEvidenceChapter {+ kind: VerifyEvidenceChapterKind;+ /** Short name shown on the timeline; required for `step`. */+ label?: string;+ /** What the agent claims or noticed; required for `check` and `flag`. */+ note?: string;+ /** Seconds from the start of the video. */+ t: number;+}++/** Upper bound on chapters per video — a timeline, not a transcript. */+export const MAX_VERIFY_EVIDENCE_CHAPTERS = 100;++const trimmedText = (value: unknown, max: number) =>+ typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : undefined;++/**+ * Read `chapters` from an evidence metadata bag (or a raw array), dropping+ * malformed entries instead of failing: chapters guide the reviewer, so one bad+ * marker must never cost the upload. Returns them sorted by time, or+ * `undefined` when none survive.+ */+export const readEvidenceChapters = (value: unknown): VerifyEvidenceChapter[] | undefined => {+ let raw: unknown;+ if (Array.isArray(value)) raw = value;+ else if (value && typeof value === 'object') raw = (value as { chapters?: unknown }).chapters;+ if (!Array.isArray(raw)) return undefined;++ const chapters: VerifyEvidenceChapter[] = [];+ for (const entry of raw) {+ if (!entry || typeof entry !== 'object') continue;+ const { kind, label, note, t } = entry as Record<string, unknown>;+ if (typeof t !== 'number' || !Number.isFinite(t) || t < 0) continue;+ if (!verifyEvidenceChapterKinds.includes(kind as VerifyEvidenceChapterKind)) continue;+ const chapter: VerifyEvidenceChapter = { kind: kind as VerifyEvidenceChapterKind, t };+ const text = { label: trimmedText(label, 80), note: trimmedText(note, 500) };+ if (chapter.kind === 'step' ? !text.label : !text.note) continue;+ if (text.label) chapter.label = text.label;+ if (text.note) chapter.note = text.note;+ chapters.push(chapter);+ }+ if (chapters.length === 0) return undefined;+ return chapters.sort((a, b) => a.t - b.t).slice(0, MAX_VERIFY_EVIDENCE_CHAPTERS);+};++/**+ * Canonicalize the `chapters` key of an evidence metadata bag before it is+ * stored: malformed markers are dropped, and chapters on anything but a video+ * are removed (they have no timeline to sit on). Other keys pass through.+ */+export const normalizeEvidenceMetadata = (metadata: unknown, type: string): unknown => {+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return metadata;+ if (!('chapters' in metadata)) return metadata;+ const { chapters: _chapters, ...rest } = metadata as Record<string, unknown>;+ const chapters = type === 'video' ? readEvidenceChapters(metadata) : undefined;+ if (chapters) return { ...rest, chapters };+ return Object.keys(rest).length > 0 ? rest : null;+};++/**+ * A video timestamp as `m:ss.cc` — a skeleton flash can last a handful of+ * frames. Rounds to whole centiseconds first so 59.999s carries into the next+ * minute (`1:00.00`) instead of reading `0:60.00`.+ */+export const formatVideoTimestamp = (seconds: number) => {+ if (!Number.isFinite(seconds) || seconds < 0) return '0:00.00';+ const centiseconds = Math.round(seconds * 100);+ const minutes = Math.floor(centiseconds / 6000);+ const rest = (centiseconds - minutes * 6000) / 100;+ return `${minutes}:${rest.toFixed(2).padStart(5, '0')}`;+};++/**+ * The whole frame. A reviewer note on a video that marks a moment or a span+ * without circling an area carries this region.+ */+export const FULL_FRAME_RECT = { height: 1, width: 1, x: 0, y: 0 } as const;++export const isFullFrameRect = (rect: { height: number; width: number; x: number; y: number }) =>+ rect.x === 0 && rect.y === 0 && rect.width === 1 && rect.height === 1;+/** Default cap on automatic repair rounds when a rubric doesn't override it. */export const DEFAULT_MAX_REPAIR_ROUNDS = 3;diff --git a/packages/database/src/models/__tests__/acceptanceFlow.test.ts b/packages/database/src/models/__tests__/acceptanceFlow.test.tsindex ccb2aed1033..bc690124a3a 100644--- a/packages/database/src/models/__tests__/acceptanceFlow.test.ts+++ b/packages/database/src/models/__tests__/acceptanceFlow.test.ts@@ -1,12 +1,20 @@// @vitest-environment nodeimport { randomUUID } from 'node:crypto';-import type { AcceptanceFlowDefinition } from '@lobechat/types';+import { FULL_FRAME_RECT } from '@lobechat/const/verify';+import type { AcceptanceFlowDefinition, AcceptanceReviewAnnotation } from '@lobechat/types';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { acceptances, users, verifyCheckResults, verifyCriteria, verifyRuns } from '../../schemas';+import {+ acceptances,+ users,+ verifyCheckResults,+ verifyCriteria,+ verifyEvidence,+ verifyRuns,+} from '../../schemas';import { AcceptanceFlowModel, validateFlow } from '../acceptanceFlow';const db = await getTestDB();@@ -386,6 +394,44 @@ describe('check assets and round snapshots', () => {).toHaveLength(0);});+ it('accepts video annotations only when they name a frame, and screenshot ones only without', async () => {+ const { flowId } = await model.publish(acceptanceId, definition);+ const run = await model.start(acceptanceId, flowId);+ const plan = (await roundPlan(run.id)).plan!;+ const result = await model.record(acceptanceId, {+ checkItemId: plan[0].id,+ observation: 'Skeleton flashed',+ verdict: 'passed',+ verifyRunId: run.id,+ });+ const [video, screenshot] = await db+ .insert(verifyEvidence)+ .values([+ { checkResultId: result.id, content: 'clip', type: 'video', userId: owner },+ { checkResultId: result.id, content: 'shot', type: 'screenshot', userId: owner },+ ])+ .returning();+ const rect = { height: 0.2, width: 0.5, x: 0.1, y: 0.1 };+ const reject = (annotations: AcceptanceReviewAnnotation[]) =>+ model.review(acceptanceId, result.id, 'rejected', 'Flashes', owner, { annotations });++ await expect(reject([{ evidenceId: video.id, rect }])).rejects.toThrow('video frame');+ await expect(reject([{ evidenceId: screenshot.id, rect, time: { start: 1 } }])).rejects.toThrow(+ 'video frame',+ );++ const updated = await reject([+ { comment: 'skeleton here', evidenceId: video.id, rect, time: { start: 7.2 } },+ { evidenceId: video.id, rect: FULL_FRAME_RECT, time: { end: 7.6, start: 6.8 } },+ { evidenceId: screenshot.id, rect },+ ]);+ expect(updated.userDecisionDetail?.annotations?.map((a) => a.time)).toEqual([+ { start: 7.2 },+ { end: 7.6, start: 6.8 },+ undefined,+ ]);+ });+it('keeps old definitions unchanged after asset edits and allows replay of the frozen round', async () => {const { flowId } = await model.publish(acceptanceId, definition);const first = await model.start(acceptanceId, flowId);diff --git a/packages/database/src/models/acceptanceFlow.ts b/packages/database/src/models/acceptanceFlow.tsindex b363b152057..488ce8fb735 100644--- a/packages/database/src/models/acceptanceFlow.ts+++ b/packages/database/src/models/acceptanceFlow.ts@@ -954,12 +954,19 @@ export class AcceptanceFlowModel {.flatMap((f) => f.versions.flatMap((v) => v.runs.flatMap((r) => r.attempts))).find((r) => r.id === resultId);if (!result) throw new Error('Result not found');+ // A screenshot region is a place; a video region is a place at a moment, so+ // it must say which frame (or span) it was drawn on.if (feedback?.annotations?.some(- (a) => !result.evidence.some((e) => e.id === a.evidenceId && e.type === 'screenshot'),+ (a) =>+ !result.evidence.some(+ (e) =>+ e.id === a.evidenceId &&+ (e.type === 'video' ? a.time !== undefined : e.type === 'screenshot' && !a.time),+ ),))- throw new Error('Annotation must reference this result screenshot');+ throw new Error('Annotation must reference this result screenshot, or a video frame');const [updated] = await this.db.update(verifyCheckResults).set({diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex f637a695f3f..5ab53e45e4b 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -8,6 +8,47 @@ export default {'Only the creator and workspace members will be able to read this acceptance and its rounds. Copies already downloaded cannot be recalled.','acceptance.share.saved': 'Sharing permissions updated','acceptance.share.copyFailed': 'Could not copy the link. Copy it from the address bar.',+ 'acceptance.video.annotateHint':+ 'Press on the video to pause on that frame and circle a region; press M to mark the whole frame, or drag the lane below the timeline to comment on a span.',+ 'acceptance.video.captionsHide': 'Hide agent notes',+ 'acceptance.video.captionsShow': 'Show agent notes',+ 'acceptance.video.circled': 'circled',+ 'acceptance.video.claim.check': "Agent's self-check",+ 'acceptance.video.claim.flag': 'Agent flagged',+ 'acceptance.video.claim.step': 'Agent step',+ 'acceptance.video.claimsSummary':+ 'Agent notes in this recording: {{checks}} self-checks · {{flags}} flagged',+ 'acceptance.video.clearRange': 'Clear span (Esc)',+ 'acceptance.video.commentRange': 'Comment on this span',+ 'acceptance.video.dispute': 'Disagree',+ 'acceptance.video.disputed': 'Disputed',+ 'acceptance.video.download': 'Download file',+ 'acceptance.video.frame': 'Frame {{frame}}',+ 'acceptance.video.fullscreen': 'Full screen',+ 'acceptance.video.hintPaused': 'Drag to circle the problem · frame {{frame}}',+ 'acceptance.video.hintPlaying': 'Press to pause and circle this frame',+ 'acceptance.video.inPoint': 'In point {{time}}',+ 'acceptance.video.keysFrame': 'frame by frame',+ 'acceptance.video.keysRange': 'span in / out',+ 'acceptance.video.loadFailed': 'The video failed to load — its link may have expired',+ 'acceptance.video.loop': 'Loop',+ 'acceptance.video.markFrame': 'Mark this frame',+ 'acceptance.video.nextFrame': 'Next frame',+ 'acceptance.video.noteEmpty': '(no note)',+ 'acceptance.video.notePlaceholderDispute': 'What is wrong with this claim?',+ 'acceptance.video.notePlaceholderFrame': 'What is wrong on this frame?',+ 'acceptance.video.notePlaceholderRange': 'What happens during this span?',+ 'acceptance.video.notesEmpty':+ 'After you circle, mark a frame or select a span on the video, your notes appear here.',+ 'acceptance.video.outPoint': 'Out point {{time}}',+ 'acceptance.video.pause': 'Pause',+ 'acceptance.video.play': 'Play',+ 'acceptance.video.previousFrame': 'Previous frame',+ 'acceptance.video.rangeLane': 'Drag here to select a span · or press I / O',+ 'acceptance.video.rangeSeconds': '{{seconds}}s',+ 'acceptance.video.reload': 'Reload',+ 'acceptance.video.seek': 'Seek',+ 'acceptance.video.speed': 'Speed','flow.graphView': 'Graph','flow.outlineView': 'Steps','flow.plan.requestChanges': 'Request changes',diff --git a/packages/prompts/src/prompts/verify/index.ts b/packages/prompts/src/prompts/verify/index.tsindex 5335206d6eb..22ec0360ab5 100644--- a/packages/prompts/src/prompts/verify/index.ts+++ b/packages/prompts/src/prompts/verify/index.ts@@ -99,4 +99,4 @@ export const buildAcceptanceRepairPrompt = (acceptanceId: string, rejectComment?lh acceptance feedback ${acceptanceId} --actionable-Every entry it prints (per-check comments, circled-region annotations on the evidence screenshots, and attachments) is the full set of feedback to handle this round. Fix the code item by item; then re-run verification and ingest the new result back into the SAME acceptance (reuse the existing check ids, and use supersedes for any check whose meaning changed). Keep the final report in the same language the previous rounds used.`;+Every entry it prints (per-check comments, circled-region annotations on the evidence screenshots, frames or spans marked on the evidence videos, and attachments) is the full set of feedback to handle this round. A video note names a timestamp such as \`frame at 0:07.20\`: open the recording at that moment (for example \`ffmpeg -ss 7.2 -i <video> -frames:v 1 frame.png\`) before acting on it, and where it disputes one of your own chapter claims, that claim was judged wrong. Fix the code item by item; then re-run verification and ingest the new result back into the SAME acceptance (reuse the existing check ids, and use supersedes for any check whose meaning changed). Keep the final report in the same language the previous rounds used.`;diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 83f91416bb3..94a971f9907 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -252,16 +252,57 @@ export interface ReviewProposalOutcome {respondedAt: string;}+/**+ * Where on a video evidence an annotation sits, in seconds from the start.+ * `start` alone pins one frame; `start` + `end` marks a span.+ */+export interface AcceptanceReviewAnnotationTime {+ end?: number;+ start: number;+}+/*** A user-drawn region on one evidence image, in coordinates normalized to the- * image box (0–1) so the overlay renders at any display size.+ * image box (0–1) so the overlay renders at any display size. On video evidence+ * the region is drawn on the frame at `time.start`; a note that marks a moment+ * or a span without circling an area carries the whole frame+ * (`FULL_FRAME_RECT` in `@lobechat/const/verify`).*/export interface AcceptanceReviewAnnotation {/** The note attached to this region. */comment?: string;+ /**+ * The agent chapter this note disputes, quoted so the objection still reads+ * correctly after the evidence is re-uploaded.+ */+ disputes?: Pick<VerifyEvidenceChapter, 'kind' | 'note' | 't'>;/** The evidence row (`verify_evidence.id`) the region was drawn on. */evidenceId: string;rect: { height: number; width: number; x: number; y: number };+ /** Video evidence only: the frame or span the note is about. */+ time?: AcceptanceReviewAnnotationTime;+}++/**+ * How an agent marker on a video reads (runtime set: `verifyEvidenceChapterKinds`).+ *+ * - `step`: an action the agent performed, logged while driving the recording.+ * - `check`: something the agent verified on this frame — a claim for the reviewer+ * to audit, never a pass.+ * - `flag`: an anomaly the agent noticed and judged harmless, disclosed so the+ * reviewer can disagree.+ */+export type VerifyEvidenceChapterKind = 'check' | 'flag' | 'step';++/** An agent-authored marker on a video evidence (`verify_evidence.metadata.chapters`). */+export interface VerifyEvidenceChapter {+ kind: VerifyEvidenceChapterKind;+ /** Short name shown on the timeline; required for `step`. */+ label?: string;+ /** What the agent claims or noticed; required for `check` and `flag`. */+ note?: string;+ /** Seconds from the start of the video. */+ t: number;}/**diff --git a/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx b/src/features/Acceptance/Viewer/Checks/CheckHistory.tsxindex 946909c7688..e4a6198978a 100644--- a/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx+++ b/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx@@ -16,6 +16,7 @@ import { AnnotatedImage } from '../Evidence/Annotation';import { AttachmentThumbs } from '../Evidence/attachments';import { IMAGE_EVIDENCE, imageRatio } from '../Evidence/evidence';import { styles as evidenceStyles } from '../Evidence/styles';+import { VideoFeedbackNotes } from '../Evidence/Video/VideoFeedbackNotes';import { styles } from './styles';import type { AcceptanceCheck, AcceptanceCheckReviewEntry, AcceptanceEvidence } from './types';@@ -67,13 +68,10 @@ export const FeedbackCard = memo<{if (review.action === 'accept') return <AcceptedNote review={review} />;if (review.action === 'ignore') return <IgnoredNote review={review} />;- const groups = new Map<- string,- { comment?: string; rect: AcceptanceReviewAnnotation['rect'] }[]- >();+ const groups = new Map<string, AcceptanceReviewAnnotation[]>();for (const annotation of review.annotations ?? []) {const bucket = groups.get(annotation.evidenceId) ?? [];- bucket.push({ comment: annotation.comment, rect: annotation.rect });+ bucket.push(annotation);groups.set(annotation.evidenceId, bucket);}@@ -101,6 +99,8 @@ export const FeedbackCard = memo<{{annotation.comment}</Text>));+ if (evidence.type === 'video')+ return <VideoFeedbackNotes key={evidenceId} notes={annotations} />;return (<AnnotatedImageannotations={annotations}diff --git a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx b/src/features/Acceptance/Viewer/Checks/CheckRow.tsxindex 7b48eb11162..4a6acb89ecd 100644--- a/src/features/Acceptance/Viewer/Checks/CheckRow.tsx+++ b/src/features/Acceptance/Viewer/Checks/CheckRow.tsx@@ -1,5 +1,6 @@'use client';+import { readEvidenceChapters } from '@lobechat/const/verify';import type { AcceptanceCommentThread } from '@lobechat/types';import { copyToClipboard, Flexbox, Icon, TextArea, Tooltip } from '@lobehub/ui';import { ActionIcon, Button, Tag, Text } from '@lobehub/ui/base-ui';@@ -38,14 +39,19 @@ import { openEvidenceCommentModal } from '../Comments/EvidenceCommentModal';import { useAcceptanceComments } from '../Comments/hooks';import ThreadEvidence from '../Comments/ThreadEvidence';import { threadsForCheck } from '../Comments/threads';-import { evidenceCounts, hasAnnotatableEvidence, isAnnotatable } from '../Evidence/evidence';+import {+ canMarkEvidence,+ evidenceCounts,+ hasAnnotatableEvidence,+ isRejectable,+} from '../Evidence/evidence';import { EvidenceList } from '../Evidence/EvidenceList';import type { EvidenceOverlayMap } from '../Evidence/overlay';import { openCheckRejectModal } from '../Review/CheckRejectModal';import type { CheckProposal } from '../Review/proposal';import { classifyProposalEdit } from '../Review/proposal';import ProposalCard from '../Review/ProposalCard';-import { useAcceptanceBundle } from '../useAcceptanceBundle';+import { useAcceptanceBundle, useEvidenceUrlRefresh } from '../useAcceptanceBundle';import { canCommentOnAcceptanceEvidence } from '../visibility';import {AcceptedNote,@@ -151,6 +157,7 @@ export const AcceptanceCheckRow = memo<{// 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);@@ -259,12 +266,16 @@ export const AcceptanceCheckRow = memo<{previousAnnotations:activeReview?.action === 'reject' ? activeReview.annotations : undefined,previousComment: activeReview?.action === 'reject' ? activeReview.comment : undefined,+ refreshEvidenceUrl,checkDescription: check.planItem?.description,checkTitle: `C${check.seq} · ${title}`,draftKey: `${check.result?.id ?? 'unexecuted'}:${check.id}`,- evidence: check.evidence- .filter((item) => isAnnotatable(item))- .map((item) => ({ fileUrl: item.fileUrl!, id: item.id })),+ evidence: check.evidence.filter(isRejectable).map((item) => ({+ chapters: item.type === 'video' ? readEvidenceChapters(item.metadata) : undefined,+ fileUrl: item.fileUrl!,+ id: item.id,+ type: item.type,+ })),initialAnnotations: fromProposal?.annotations ?? undefined,initialComment: fromProposal?.comment ?? reviewComment,onConfirm: async ({ annotations, comment, fileIds }) => {@@ -641,6 +652,8 @@ export const AcceptanceCheckRow = memo<{<EvidenceListevidence={check.evidence}overlays={commentOverlays}+ reviewNotes={activeReview?.action === 'reject' ? activeReview.annotations : undefined}+ onRefreshEvidenceUrl={refreshEvidenceUrl}onReviewEvidence={canReview ? (id) => openReject(undefined, id) : undefined}/>{staleThreads.length > 0 && (@@ -829,7 +842,7 @@ export const AcceptanceCheckRow = memo<{not a verdict. The rounds this check already went through thensit between that and the verdict buttons: context for thedecision, never an appendix to one already made. */}- {detailMode && reviewable && !activeReview && hasAnnotatableEvidence(check) && (+ {detailMode && reviewable && !activeReview && canMarkEvidence(check, desktop) && (<Buttonoutdenticon={<Icon icon={Images} />}diff --git a/src/features/Acceptance/Viewer/Evidence/DesktopEvidenceReview.tsx b/src/features/Acceptance/Viewer/Evidence/DesktopEvidenceReview.tsxindex 981afd189dc..13f16c1e20f 100644--- a/src/features/Acceptance/Viewer/Evidence/DesktopEvidenceReview.tsx+++ b/src/features/Acceptance/Viewer/Evidence/DesktopEvidenceReview.tsx@@ -1,10 +1,10 @@'use client';-import { Flexbox, TextArea } from '@lobehub/ui';+import { Flexbox, Icon, TextArea } from '@lobehub/ui';import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';-import { ZoomIn, ZoomOut } from 'lucide-react';-import { memo } from 'react';+import { Film, ZoomIn, ZoomOut } from 'lucide-react';+import { memo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { ZOOM_STEPS } from '../Review/rejectDraft';@@ -12,6 +12,9 @@ import type { RejectReviewModel } from '../Review/useRejectReview';import { AttachmentStrip, AttachmentUploadButton } from './attachments';import { EvidenceStage } from './EvidenceStage';import { RegionNotes } from './RegionNotes';+import { VideoNotes } from './Video/VideoNotes';+import type { VideoReviewStageHandle } from './Video/VideoReviewStage';+import { VideoReviewStage } from './Video/VideoReviewStage';const styles = createStaticStyles(({ css }) => ({body: css`@@ -62,6 +65,16 @@ const styles = createStaticStyles(({ css }) => ({object-fit: cover;}`,+ /** 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;++ color: #fff;++ background: #000;+ `,thumbActive: css`border-color: ${cssVar.colorPrimary};`,@@ -122,6 +135,8 @@ export const DesktopEvidenceReview = memo<DesktopEvidenceReviewProps>(({ model }uploading,zoom,} = model;+ const videoStage = useRef<VideoReviewStageHandle>(null);+ const isVideo = activeEvidence?.type === 'video';return (<div className={styles.body}>@@ -146,57 +161,97 @@ export const DesktopEvidenceReview = memo<DesktopEvidenceReviewProps>(({ model })}onClick={() => model.selectEvidence(index)}>- <img alt={''} src={item.fileUrl} />+ {item.type === 'video' ? (+ <span className={styles.videoThumb} style={{ height: '100%' }}>+ <Icon icon={Film} size={18} />+ </span>+ ) : (+ <img alt={''} src={item.fileUrl} />+ )}</button>))}</Flexbox>)}<div className={styles.stageRow} style={{ position: 'relative' }}>- <EvidenceStage- drawing- annotations={activeAnnotations}- src={activeEvidence.fileUrl}- zoom={zoom}- onDraw={canvas.onDraw}- onRemove={canvas.onRemove}- onUpdate={canvas.onUpdate}- />- <div className={styles.zoomBar}>- <ActionIcon- disabled={zoom <= ZOOM_STEPS[0]}- icon={ZoomOut}- size={'small'}- title={t('acceptance.review.zoomOut')}- onClick={() => model.stepZoom(-1)}+ {isVideo ? (+ <VideoReviewStage+ activeNoteKey={model.activeNoteKey}+ chapters={activeEvidence.chapters ?? []}+ handleRef={videoStage}+ key={activeEvidence.id}+ notes={activeAnnotations}+ src={activeEvidence.fileUrl}+ onAddNote={model.addVideoNote}+ onSelectNote={model.setActiveNoteKey}+ onRefreshSource={+ model.refreshEvidenceUrl+ ? () => model.refreshEvidenceUrl!(activeEvidence.id)+ : undefined+ }/>- <span className={styles.zoomLabel}>{Math.round(zoom * 100)}%</span>- <ActionIcon- disabled={zoom >= ZOOM_STEPS.at(-1)!}- icon={ZoomIn}- size={'small'}- title={t('acceptance.review.zoomIn')}- onClick={() => model.stepZoom(1)}+ ) : (+ <EvidenceStage+ drawing+ annotations={activeAnnotations}+ src={activeEvidence.fileUrl}+ zoom={zoom}+ onDraw={canvas.onDraw}+ onRemove={canvas.onRemove}+ onUpdate={canvas.onUpdate}/>- </div>+ )}+ {!isVideo && (+ <div className={styles.zoomBar}>+ <ActionIcon+ disabled={zoom <= ZOOM_STEPS[0]}+ icon={ZoomOut}+ size={'small'}+ title={t('acceptance.review.zoomOut')}+ onClick={() => model.stepZoom(-1)}+ />+ <span className={styles.zoomLabel}>{Math.round(zoom * 100)}%</span>+ <ActionIcon+ disabled={zoom >= ZOOM_STEPS.at(-1)!}+ icon={ZoomIn}+ size={'small'}+ title={t('acceptance.review.zoomIn')}+ onClick={() => model.stepZoom(1)}+ />+ </div>+ )}<div className={styles.notes}><Flexbox gap={2}><Text strong fontSize={13}>{t('acceptance.review.regionComments')}</Text><Text fontSize={12} type={'secondary'}>- {t('acceptance.review.annotateHint')}+ {isVideo+ ? t('acceptance.video.annotateHint')+ : t('acceptance.review.annotateHint')}</Text></Flexbox>{activeAnnotations.length === 0 && (<Text fontSize={12} type={'secondary'}>- {t('acceptance.review.regionCommentsEmpty')}+ {isVideo+ ? t('acceptance.video.notesEmpty')+ : t('acceptance.review.regionCommentsEmpty')}</Text>)}- <RegionNotes- annotations={activeAnnotations}- onChange={model.editAnnotation}- onRemove={model.removeAnnotation}- />+ {isVideo ? (+ <VideoNotes+ activeNoteKey={model.activeNoteKey}+ notes={activeAnnotations}+ onChange={model.editAnnotation}+ onFocusNote={(note) => videoStage.current?.focusNote(note)}+ onRemove={model.removeAnnotation}+ />+ ) : (+ <RegionNotes+ annotations={activeAnnotations}+ onChange={model.editAnnotation}+ onRemove={model.removeAnnotation}+ />+ )}</div></div></Flexbox>diff --git a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsxindex 2a3ea5e0d74..6d7e5f42eec 100644--- a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx+++ b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx@@ -1,5 +1,7 @@'use client';+import { readEvidenceChapters } from '@lobechat/const/verify';+import type { AcceptanceReviewAnnotation } from '@lobechat/types';import { Flexbox, Image } from '@lobehub/ui';import { useResponsive } from 'antd-style';import { memo } from 'react';@@ -23,6 +25,7 @@ import { ScreenshotTiles } from '../Evidence/ScreenshotTiles';import { IMAGE_EVIDENCE, imageRatio, isVisual } from './evidence';import type { EvidenceOverlayMap } from './overlay';import { styles } from './styles';+import { VideoEvidencePlayer } from './Video/VideoEvidencePlayer';/** Flat media for a comparison side — the card frames it, so no own border/radius. */const comparisonContent = (item: AcceptanceEvidence) => {@@ -69,7 +72,11 @@ export const EvidenceList = memo<{* in one row), the boxes land on the image that is already here.*/overlays?: EvidenceOverlayMap;-}>(({ evidence, overlays, onReviewEvidence }) => {+ /** A freshly signed URL for one evidence — lets a video recover an expired link. */+ onRefreshEvidenceUrl?: (evidenceId: string) => Promise<string | undefined>;+ /** The standing reject's notes — video ones are pinned to the player's timeline. */+ reviewNotes?: AcceptanceReviewAnnotation[];+}>(({ evidence, overlays, onRefreshEvidenceUrl, onReviewEvidence, reviewNotes }) => {const { md = true } = useResponsive();const sorted = [...evidence].sort((a, b) => (isVisual(b) ? 1 : 0) - (isVisual(a) ? 1 : 0));if (sorted.length === 0) return null;@@ -125,14 +132,16 @@ export const EvidenceList = memo<{const caption = description && <span className={styles.caption}>{description}</span>;if (item.fileUrl && item.type === 'video')return (- <Flexbox gap={4} key={item.id} style={{ maxWidth: '100%', width: 'fit-content' }}>- <video- controls- src={item.fileUrl}- style={{ borderRadius: 8, maxHeight: 360, maxWidth: '100%', width: 'auto' }}- />- {caption}- </Flexbox>+ <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+ }+ />);if (item.fileUrl && item.type === 'audio')return (diff --git a/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.test.tsx b/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.test.tsxindex f846d84d612..4f09eed2273 100644--- a/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.test.tsx+++ b/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.test.tsx@@ -37,6 +37,7 @@ const buildModel = (overrides: Partial<RejectReviewModel> = {}): RejectReviewModactiveEvidence: undefined,activeIndex: -1,annotations: [],+ editableAnnotations: [],attachments: [],canSubmit: false,canvas: { onDraw: vi.fn(), onRemove: vi.fn(), onUpdate: vi.fn() },@@ -133,7 +134,11 @@ describe('MobileEvidenceReview notes button', () => {});it('keeps marked regions visible without auto-opening the notes', () => {- render(<MobileEvidenceReview model={buildModel({ annotations: [region] })} />);+ render(+ <MobileEvidenceReview+ model={buildModel({ annotations: [region], editableAnnotations: [region] })}+ />,+ );// Regions have their own always-visible section; the notes stay closed.expect(screen.getByText('acceptance.review.regionComments')).toBeInTheDocument();@@ -214,7 +219,12 @@ describe('MobileEvidenceReview marking mode', () => {it('lists the circled regions for their notes while marking', () => {render(<MobileEvidenceReview- model={withImage({ activeAnnotations: [region], annotations: [region], drawing: true })}+ model={withImage({+ activeAnnotations: [region],+ annotations: [region],+ drawing: true,+ editableAnnotations: [region],+ })}/>,);diff --git a/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.tsx b/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.tsxindex 05dc8928170..c45758fba4e 100644--- a/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.tsx+++ b/src/features/Acceptance/Viewer/Evidence/MobileEvidenceReview.tsx@@ -116,7 +116,9 @@ export const MobileEvidenceReview = memo<{ model: RejectReviewModel }>(({ modelactiveAnnotations,activeEvidence,activeIndex,- annotations,+ // Only what this phone can edit — videos' notes are kept in the model and+ // submitted untouched, but have no stage here to point back to.+ editableAnnotations: annotations,attachments,canSubmit,canvas,diff --git a/src/features/Acceptance/Viewer/Evidence/RegionNotes.tsx b/src/features/Acceptance/Viewer/Evidence/RegionNotes.tsxindex 085079b57ad..62e362843b6 100644--- a/src/features/Acceptance/Viewer/Evidence/RegionNotes.tsx+++ b/src/features/Acceptance/Viewer/Evidence/RegionNotes.tsx@@ -54,6 +54,8 @@ const styles = createStaticStyles(({ css }) => ({}));interface RegionNoteRowProps {+ /** Focus the field on mount — a note just made is a note about to be written. */+ autoFocus?: boolean;/** Rendered beside the field — the desktop's number badge. */badge?: ReactNode;/** Rendered above the field — the phone's jump-back link. */@@ -68,8 +70,8 @@ interface RegionNoteRowProps {value: string;}-const RegionNoteRow = memo<RegionNoteRowProps>(- ({ badge, caption, fontSize, index, placeholder, value, onChange, onRemove }) => {+export const RegionNoteRow = memo<RegionNoteRowProps>(+ ({ autoFocus, badge, caption, fontSize, index, placeholder, value, onChange, onRemove }) => {const { t } = useTranslation('verify');return (@@ -79,6 +81,7 @@ const RegionNoteRow = memo<RegionNoteRowProps>({badge}<TextAreaaria-label={t('acceptance.review.annotationPlaceholder', { index })}+ autoFocus={autoFocus}autoSize={{ maxRows: 5, minRows: 1 }}placeholder={placeholder}style={{ flex: 1, fontSize }}diff --git a/src/features/Acceptance/Viewer/Evidence/Video/ClaimLabel.tsx b/src/features/Acceptance/Viewer/Evidence/Video/ClaimLabel.tsxnew file mode 100644index 00000000000..5d036fa1c12--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/ClaimLabel.tsx@@ -0,0 +1,52 @@+'use client';++import type { VerifyEvidenceChapterKind } from '@lobechat/types';+import type { CSSProperties } from 'react';+import { useTranslation } from 'react-i18next';++import { CLAIM_COLOR } from './styles';++export const ClaimDot = ({ kind }: { kind: VerifyEvidenceChapterKind }) => (+ <span+ aria-hidden+ style={{+ background: CLAIM_COLOR[kind],+ borderRadius: '50%',+ flex: 'none',+ height: 6,+ width: 6,+ }}+ />+);++/**+ * Who said it and what kind of remark it is: a coloured dot (green for the+ * agent's self-check, yellow for a flag) beside a label in the surrounding text+ * colour. The colour sits on the dot only, so the label stays as readable as+ * the text it introduces.+ */+export const ClaimLabel = ({+ kind,+ style,+}: {+ kind: VerifyEvidenceChapterKind;+ style?: CSSProperties;+}) => {+ const { t } = useTranslation('verify');++ return (+ <span+ style={{+ alignItems: 'center',+ display: 'inline-flex',+ flex: 'none',+ fontWeight: 600,+ gap: 6,+ ...style,+ }}+ >+ <ClaimDot kind={kind} />+ {t(`acceptance.video.claim.${kind}`)}+ </span>+ );+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.test.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.test.tsxnew file mode 100644index 00000000000..6161ac297fb--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.test.tsx@@ -0,0 +1,87 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import type { VideoClock } from './useVideoClock';+import { ClaimCaption, handlePlaybackKey } from './VideoChrome';+import { VideoTimeline } from './VideoTimeline';++const clock = () =>+ ({+ controls: {+ seek: vi.fn(),+ setRate: vi.fn(),+ step: vi.fn(),+ toggle: vi.fn(),+ },+ rate: 1,+ time: 0,+ }) as unknown as VideoClock;++describe('handlePlaybackKey', () => {+ it('plays on Space, but leaves Space and Enter to a focused button', () => {+ const player = clock();+ const button = document.createElement('button');++ expect(handlePlaybackKey(new KeyboardEvent('keydown', { key: ' ' }), player)).toBe(true);+ const onButton = new KeyboardEvent('keydown', { key: ' ' });+ Object.defineProperty(onButton, 'target', { value: button });+ const enterOnButton = new KeyboardEvent('keydown', { key: 'Enter' });+ Object.defineProperty(enterOnButton, 'target', { value: button });++ expect(handlePlaybackKey(onButton, player)).toBe(false);+ expect(handlePlaybackKey(enterOnButton, player)).toBe(false);+ expect(player.controls.toggle).toHaveBeenCalledTimes(1);+ });+});++describe('VideoTimeline markers', () => {+ // Enter / Space on a focused button dispatch click, not pointerdown.+ it('seek from a click, so they work from the keyboard', () => {+ const onClaimClick = vi.fn();+ const onNoteClick = vi.fn();+ const onSeek = vi.fn();+ render(+ <VideoTimeline+ chapters={[{ kind: 'check', note: 'no skeleton', t: 7.9 }]}+ duration={15}+ notes={[{ comment: 'flash', key: 1, start: 7.2 }]}+ src={'clip.mp4'}+ time={0}+ onClaimClick={onClaimClick}+ onNoteClick={onNoteClick}+ onSeek={onSeek}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: /no skeleton/ }));+ fireEvent.click(screen.getByRole('button', { name: /flash/ }));++ expect(onClaimClick).toHaveBeenCalledWith(expect.objectContaining({ t: 7.9 }));+ expect(onNoteClick).toHaveBeenCalledWith(expect.objectContaining({ start: 7.2 }));+ expect(onSeek).not.toHaveBeenCalled();+ });+});++describe('ClaimCaption', () => {+ it('gives each claim on the frame its own action', () => {+ const onDispute = vi.fn();+ render(+ <ClaimCaption+ action={(claim) => (+ <button type={'button'} onClick={() => onDispute(claim.note)}>+ {`dispute ${claim.note}`}+ </button>+ )}+ claims={[+ { kind: 'check', note: 'no skeleton', t: 7.9 },+ { kind: 'check', note: 'first question in place', t: 7.9 },+ ]}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'dispute first question in place' }));++ expect(onDispute).toHaveBeenCalledWith('first question in place');+ expect(screen.getByText('no skeleton')).toBeTruthy();+ });+});diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsxnew file mode 100644index 00000000000..808f93e117e--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoChrome.tsx@@ -0,0 +1,264 @@+'use client';++import type { VerifyEvidenceChapter } from '@lobechat/types';+import { Center, Flexbox, Icon } from '@lobehub/ui';+import { Button, DropdownMenu } from '@lobehub/ui/base-ui';+import { cx } from 'antd-style';+import {+ AlertTriangle,+ Captions,+ Check,+ ChevronLeft,+ ChevronRight,+ Download,+ Maximize,+ Pause,+ Play,+ RefreshCw,+} from 'lucide-react';+import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { ClaimLabel } from './ClaimLabel';+import { styles } from './styles';+import type { VideoClock } from './useVideoClock';+import { claimsOf, formatVideoTime, frameOf, isOnFrame, PLAYBACK_RATES, stepAt } from './videoTime';++type Rect = { height: number; width: number; x: number; y: number };++const percent = (rect: Rect) => ({+ height: `${rect.height * 100}%`,+ left: `${rect.x * 100}%`,+ top: `${rect.y * 100}%`,+ width: `${rect.width * 100}%`,+});++/** A region drawn on a frame, shown only while that frame is on screen. */+export interface FrameRegion {+ comment?: string;+ key: number | string;+ rect: Rect;+ start: number;+}++export const FrameRegions = ({+ paused,+ regions,+ time,+}: {+ paused: boolean;+ regions: FrameRegion[];+ time: number;+}) =>+ 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>+ ));++export const DraftRegion = ({ rect }: { rect: Rect }) => (+ <div className={styles.draft} style={percent(rect)} />+);++/**+ * The agent's claim at this moment, captioned over the frame it is about.+ * `action` is where the review stage puts its "I disagree" button.+ */+export const ClaimCaption = ({+ action,+ claims,+}: {+ action?: (claim: VerifyEvidenceChapter) => ReactNode;+ claims: VerifyEvidenceChapter[];+}) => (+ <div className={styles.caption} onPointerDown={(event) => event.stopPropagation()}>+ {claims.map((claim, index) => (+ <div key={`${claim.kind}-${index}`} style={{ marginBlockStart: index > 0 ? 8 : 0 }}>+ <div className={styles.captionTitle}>+ <ClaimLabel kind={claim.kind} />+ {action?.(claim)}+ </div>+ <div>{claim.note}</div>+ </div>+ ))}+ </div>+);++/**+ * A video that failed to load — usually a signed link that expired while the+ * page stayed open. Reload re-signs nothing but retries a transient failure;+ * the download link opens the file directly as the way out.+ */+export const VideoLoadError = ({ onReload, src }: { onReload: () => void; src: string }) => {+ const { t } = useTranslation('verify');++ return (+ <Center className={styles.overlay} gap={10} style={{ color: '#ccc' }}>+ <Icon icon={AlertTriangle} size={22} />+ <span style={{ fontSize: 13 }}>{t('acceptance.video.loadFailed')}</span>+ <Flexbox horizontal gap={8}>+ <Button icon={RefreshCw} size={'small'} onClick={onReload}>+ {t('acceptance.video.reload')}+ </Button>+ <Button href={src} icon={Download} size={'small'} target={'_blank'}>+ {t('acceptance.video.download')}+ </Button>+ </Flexbox>+ </Center>+ );+};++interface VideoControlBarProps {+ captions?: boolean;+ chapters: VerifyEvidenceChapter[];+ clock: VideoClock;+ onFullscreen?: () => void;+ /** Absent where captions are always on (the review stage needs them to dispute). */+ onToggleCaptions?: () => void;+}++/** Play, frame step, the frame readout, captions, speed — below the timeline. */+export const VideoControlBar = ({+ captions,+ chapters,+ clock,+ onFullscreen,+ onToggleCaptions,+}: VideoControlBarProps) => {+ const { t } = useTranslation('verify');+ const { controls, duration, paused, rate, time } = clock;+ const step = stepAt(chapters, time);++ return (+ <Flexbox horizontal align={'center'} gap={2}>+ <button+ aria-label={paused ? t('acceptance.video.play') : t('acceptance.video.pause')}+ className={styles.barButton}+ title={`${paused ? t('acceptance.video.play') : t('acceptance.video.pause')} (Space)`}+ type={'button'}+ onClick={controls.toggle}+ >+ <Icon icon={paused ? Play : Pause} size={16} />+ </button>+ <button+ aria-label={t('acceptance.video.previousFrame')}+ className={styles.barButton}+ title={`${t('acceptance.video.previousFrame')} (,)`}+ type={'button'}+ onClick={() => controls.step(-1)}+ >+ <Icon icon={ChevronLeft} size={16} />+ </button>+ <button+ aria-label={t('acceptance.video.nextFrame')}+ className={styles.barButton}+ title={`${t('acceptance.video.nextFrame')} (.)`}+ type={'button'}+ onClick={() => controls.step(1)}+ >+ <Icon icon={ChevronRight} size={16} />+ </button>+ <span className={styles.time}>+ {formatVideoTime(time)} / {formatVideoTime(duration)}+ </span>+ <span className={styles.frameNo}>+ {t('acceptance.video.frame', { frame: frameOf(time) })}+ {step?.label ? ` · ${step.label}` : ''}+ </span>+ <div style={{ flex: 1 }} />+ {onToggleCaptions && claimsOf(chapters).length > 0 && (+ <button+ aria-pressed={captions}+ className={cx(styles.barButton, captions && styles.barButtonActive)}+ title={captions ? t('acceptance.video.captionsHide') : t('acceptance.video.captionsShow')}+ type={'button'}+ onClick={onToggleCaptions}+ >+ <Icon icon={Captions} size={16} />+ </button>+ )}+ <DropdownMenu+ items={PLAYBACK_RATES.map((value) => ({+ extra: value === rate ? <Icon icon={Check} /> : undefined,+ key: String(value),+ label: `${value}×`,+ onClick: () => controls.setRate(value),+ }))}+ >+ <button+ className={cx(styles.barButton, rate !== 1 && styles.barButtonActive)}+ title={`${t('acceptance.video.speed')} (J / L)`}+ type={'button'}+ >+ {rate}×+ </button>+ </DropdownMenu>+ {onFullscreen && (+ <button+ aria-label={t('acceptance.video.fullscreen')}+ className={styles.barButton}+ title={t('acceptance.video.fullscreen')}+ type={'button'}+ onClick={onFullscreen}+ >+ <Icon icon={Maximize} size={15} />+ </button>+ )}+ </Flexbox>+ );+};++/**+ * Keys shared by both players. Returns true when the key was handled so the+ * caller can stop the page from also scrolling on Space or the arrows.+ */+export const handlePlaybackKey = (event: KeyboardEvent | ReactKeyboardEvent, clock: VideoClock) => {+ // A focused button owns Space and Enter — they must activate it, not play.+ if (event.target instanceof HTMLButtonElement && (event.key === ' ' || event.key === 'Enter'))+ return false;+ const { controls, rate, time } = clock;+ const nextRate = (direction: 1 | -1) => {+ const index = PLAYBACK_RATES.indexOf(rate as (typeof PLAYBACK_RATES)[number]);+ const next =+ PLAYBACK_RATES[+ Math.min(Math.max((index === -1 ? 1 : index) + direction, 0), PLAYBACK_RATES.length - 1)+ ];+ controls.setRate(next);+ };+ switch (event.key.toLowerCase()) {+ case ' ':+ case 'k': {+ controls.toggle();+ return true;+ }+ case ',': {+ controls.step(-1);+ return true;+ }+ case '.': {+ controls.step(1);+ return true;+ }+ case 'arrowleft': {+ controls.seek(time - (event.shiftKey ? 5 : 1));+ return true;+ }+ case 'arrowright': {+ controls.seek(time + (event.shiftKey ? 5 : 1));+ return true;+ }+ case 'j': {+ nextRate(-1);+ return true;+ }+ case 'l': {+ nextRate(1);+ return true;+ }+ default: {+ return false;+ }+ }+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoClaimList.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoClaimList.tsxnew file mode 100644index 00000000000..edfcec4be17--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoClaimList.tsx@@ -0,0 +1,153 @@+'use client';++import type { VerifyEvidenceChapter } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ChevronDown, ChevronRight } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { ClaimDot } from './ClaimLabel';+import { claimsOf, formatVideoClock, formatVideoTime, stepsOf } from './videoTime';++const styles = createStaticStyles(({ css }) => ({+ step: css`+ cursor: pointer;++ display: inline-flex;+ gap: 6px;+ align-items: center;++ height: 24px;+ padding-inline: 8px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: transparent;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillTertiary};+ }+ `,+ toggle: css`+ cursor: pointer;++ display: inline-flex;+ gap: 4px;+ align-items: center;+ align-self: flex-start;++ padding: 0;+ border: none;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ background: none;++ &:hover {+ color: ${cssVar.colorTextSecondary};+ }+ `,+ claim: css`+ cursor: pointer;++ display: flex;+ gap: 8px;+ align-items: baseline;++ padding-block: 3px;+ padding-inline: 6px;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ font-size: 13px;+ color: ${cssVar.colorText};+ text-align: start;++ background: transparent;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ time: css`+ flex: none;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextTertiary};+ `,+}));++interface VideoClaimListProps {+ chapters: VerifyEvidenceChapter[];+ onSeek: (seconds: number) => void;+}++/**+ * The agent's steps as jump chips, and its claims folded into one line. The+ * timeline dots and captions already surface each claim in place; the list is+ * for reading them all at once, so it waits to be opened.+ */+export const VideoClaimList = ({ chapters, onSeek }: VideoClaimListProps) => {+ const { t } = useTranslation('verify');+ const [open, setOpen] = useState(false);+ const steps = stepsOf(chapters);+ const claims = claimsOf(chapters);+ if (steps.length === 0 && claims.length === 0) return null;++ const checks = claims.filter((claim) => claim.kind === 'check').length;+ const flags = claims.length - checks;++ return (+ <Flexbox gap={6}>+ {steps.length > 0 && (+ <Flexbox horizontal gap={6} style={{ flexWrap: 'wrap' }}>+ {steps.map((step) => (+ <button+ className={styles.step}+ key={`${step.t}-${step.label}`}+ type={'button'}+ onClick={() => onSeek(step.t)}+ >+ <span className={styles.time}>{formatVideoClock(step.t)}</span>+ {step.label}+ </button>+ ))}+ </Flexbox>+ )}+ {claims.length > 0 && (+ <button+ aria-expanded={open}+ className={styles.toggle}+ type={'button'}+ onClick={() => setOpen((value) => !value)}+ >+ <Icon icon={open ? ChevronDown : ChevronRight} size={12} />+ {t('acceptance.video.claimsSummary', { checks, flags })}+ </button>+ )}+ {open &&+ claims.map((claim, index) => (+ <button+ className={styles.claim}+ key={`${claim.kind}-${claim.t}-${index}`}+ type={'button'}+ onClick={() => onSeek(claim.t)}+ >+ <span style={{ alignSelf: 'center', display: 'inline-flex' }}>+ <ClaimDot kind={claim.kind} />+ </span>+ <span className={styles.time}>{formatVideoTime(claim.t)}</span>+ <span>{claim.note}</span>+ </button>+ ))}+ </Flexbox>+ );+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.test.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.test.tsxnew file mode 100644index 00000000000..8a94f533114--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.test.tsx@@ -0,0 +1,26 @@+import { act, fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { VideoEvidencePlayer } from './VideoEvidencePlayer';++describe('VideoEvidencePlayer load failure', () => {+ // Signed links expire; retrying the same one never recovers the video.+ it('asks for a freshly signed link before retrying', async () => {+ const onRefreshSource = vi.fn(async () => 'https://s3/clip.mp4?sig=new');+ const load = vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {});+ const { container } = render(+ <VideoEvidencePlayer src={'https://s3/clip.mp4?sig=old'} onRefreshSource={onRefreshSource} />,+ );++ act(() => {+ container.querySelector('video')!.dispatchEvent(new Event('error'));+ });+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: /reload|重新加载/i }));+ });++ expect(onRefreshSource).toHaveBeenCalledTimes(1);+ expect(load).toHaveBeenCalled();+ load.mockRestore();+ });+});diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsxnew file mode 100644index 00000000000..e84fd9c947a--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoEvidencePlayer.tsx@@ -0,0 +1,154 @@+'use client';++import { isFullFrameRect } from '@lobechat/const/verify';+import type { AcceptanceReviewAnnotation, VerifyEvidenceChapter } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Play } from 'lucide-react';+import type { ReactNode } from 'react';+import { memo, useRef, useState } from 'react';++import { styles } from './styles';+import { useVideoClock } from './useVideoClock';+import {+ ClaimCaption,+ FrameRegions,+ handlePlaybackKey,+ VideoControlBar,+ VideoLoadError,+} from './VideoChrome';+import { VideoClaimList } from './VideoClaimList';+import { claimsAt } from './videoTime';+import { VideoTimeline } from './VideoTimeline';++/** Matches the plain `<video>` this replaces, so rows keep their rhythm. */+const MAX_HEIGHT = 360;++interface VideoEvidencePlayerProps {+ /** The evidence description — laid out under the player, at the player's width. */+ 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. */+ onRefreshSource?: () => Promise<unknown>;+ src: string;+}++/**+ * A video evidence as a reviewer needs it: speed, frame stepping, the agent's+ * steps and claims on the timeline and captioned over the frame, and earlier+ * notes pinned where they were made. Keys work once the player has focus, so+ * Space never hijacks the page scroll.+ */+export const VideoEvidencePlayer = memo<VideoEvidencePlayerProps>(+ ({ caption, chapters = [], notes = [], onRefreshSource, src }) => {+ const rootRef = useRef<HTMLDivElement>(null);+ const videoRef = useRef<HTMLVideoElement>(null);+ const clock = useVideoClock(videoRef, { src });+ const { controls, duration, paused, size, status, time } = clock;+ const [captions, setCaptions] = useState(true);++ const timed = notes.flatMap((note) => (note.time ? [{ ...note, time: note.time }] : []));+ const claims = captions ? claimsAt(chapters, time) : [];+ const aspect = size ? size.width / size.height : 16 / 9;++ return (+ <Flexbox gap={8} style={{ maxWidth: `min(100%, ${Math.round(MAX_HEIGHT * aspect)}px)` }}>+ <div+ className={styles.player}+ ref={rootRef}+ tabIndex={0}+ onKeyDown={(event) => {+ if (status === 'ready' && handlePlaybackKey(event, clock)) event.preventDefault();+ }}+ >+ <div className={styles.frame} style={{ aspectRatio: `${aspect}` }}>+ <video playsInline preload={'metadata'} ref={videoRef} src={src} />+ {status === 'ready' && (+ <div+ className={styles.overlay}+ onClick={controls.toggle}+ onDoubleClick={() => void rootRef.current?.requestFullscreen?.()}+ >+ <FrameRegions+ paused={paused}+ time={time}+ regions={timed+ .filter((note) => !isFullFrameRect(note.rect))+ .map((note, index) => ({+ comment: note.comment,+ key: index,+ rect: note.rect,+ start: note.time.start,+ }))}+ />+ {paused && time < 0.05 && (+ <div className={styles.centerPlay}>+ <Icon icon={Play} size={24} />+ </div>+ )}+ {claims.length > 0 && <ClaimCaption claims={claims} />}+ </div>+ )}+ {status === 'error' && (+ <VideoLoadError+ src={src}+ onReload={async () => {+ // A new link re-renders with a new src and loads itself;+ // the explicit load covers a transient failure on the same one.+ await onRefreshSource?.();+ controls.reload();+ }}+ />+ )}+ </div>+ <div+ className={styles.bar}+ style={status === 'ready' ? undefined : { opacity: 0.4, pointerEvents: 'none' }}+ >+ <VideoTimeline+ chapters={chapters}+ duration={duration}+ src={src}+ time={time}+ notes={timed.map((note, index) => ({+ comment: note.comment,+ end: note.time.end,+ key: index,+ start: note.time.start,+ }))}+ onSeek={controls.seek}+ onClaimClick={(item) => {+ controls.pause();+ controls.seek(item.t);+ setCaptions(true);+ }}+ onNoteClick={(note) => {+ controls.pause();+ controls.seek(note.start);+ }}+ />+ <VideoControlBar+ captions={captions}+ chapters={chapters}+ clock={clock}+ onFullscreen={() => void rootRef.current?.requestFullscreen?.()}+ onToggleCaptions={() => setCaptions((value) => !value)}+ />+ </div>+ </div>+ {caption}+ <VideoClaimList+ chapters={chapters}+ onSeek={(seconds) => {+ controls.pause();+ controls.seek(seconds);+ setCaptions(true);+ }}+ />+ </Flexbox>+ );+ },+);++VideoEvidencePlayer.displayName = 'AcceptanceVideoEvidencePlayer';diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoFeedbackNotes.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoFeedbackNotes.tsxnew file mode 100644index 00000000000..673cd459824--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoFeedbackNotes.tsx@@ -0,0 +1,58 @@+'use client';++import type { AcceptanceReviewAnnotation } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { Flag, Repeat } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { ClaimLabel } from './ClaimLabel';+import { formatVideoTime } from './videoTime';++/**+ * A submitted reject's notes on one video, read back as text in time order.+ * The frames themselves are one click away on the player above; repeating a+ * still here would show a frame without the motion the note is about.+ */+export const VideoFeedbackNotes = ({ notes }: { notes: AcceptanceReviewAnnotation[] }) => {+ const { t } = useTranslation('verify');++ return (+ <Flexbox gap={4}>+ {[...notes]+ .sort((a, b) => (a.time?.start ?? 0) - (b.time?.start ?? 0))+ .map((note, index) => (+ <Flexbox horizontal align={'baseline'} gap={8} key={index}>+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ style={{+ color: cssVar.colorErrorText,+ flex: 'none',+ fontFamily: cssVar.fontFamilyCode,+ fontSize: 11,+ }}+ >+ <Icon icon={note.time?.end === undefined ? Flag : Repeat} size={11} />+ {note.time+ ? note.time.end === undefined+ ? formatVideoTime(note.time.start)+ : `${formatVideoTime(note.time.start)} – ${formatVideoTime(note.time.end)}`+ : '—'}+ </Flexbox>+ <Flexbox gap={2}>+ {note.disputes?.note && (+ <Text fontSize={12} type={'secondary'}>+ <ClaimLabel kind={note.disputes.kind} style={{ marginInlineEnd: 6 }} />+ {note.disputes.note}+ </Text>+ )}+ <Text fontSize={12}>{note.comment || t('acceptance.video.noteEmpty')}</Text>+ </Flexbox>+ </Flexbox>+ ))}+ </Flexbox>+ );+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoNotes.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoNotes.tsxnew file mode 100644index 00000000000..d41d6d26cae--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoNotes.tsx@@ -0,0 +1,126 @@+'use client';++import { isFullFrameRect } from '@lobechat/const/verify';+import { Flexbox, Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Flag, Repeat } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { DraftAnnotationEntry } from '../../Review/rejectDraft';+import { RegionNoteRow } from '../RegionNotes';+import { ClaimLabel } from './ClaimLabel';+import { formatVideoTime, frameOf } from './videoTime';++const styles = createStaticStyles(({ css }) => ({+ stamp: css`+ cursor: pointer;++ display: inline-flex;+ gap: 4px;+ align-items: center;++ padding-block: 1px;+ padding-inline: 6px;+ border: none;+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorErrorText};++ background: ${cssVar.colorErrorBg};++ &:hover {+ background: ${cssVar.colorErrorBgHover};+ }+ `,+ active: css`+ box-shadow: 0 0 0 1px ${cssVar.colorError};+ `,+ quote: css`+ display: flex;+ flex-direction: column;+ gap: 2px;++ padding-block: 6px;+ padding-inline: 10px;+ border-radius: 6px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillQuaternary};+ `,+}));++interface VideoNotesProps {+ activeNoteKey?: number;+ notes: DraftAnnotationEntry[];+ onChange: (key: number, comment: string) => void;+ onFocusNote: (note: DraftAnnotationEntry) => void;+ onRemove: (key: number) => void;+}++/**+ * The notes on the video on screen, in the order they occur. Each names its+ * frame or span — clicking it seeks there — and a dispute quotes the agent's+ * claim it answers, so the note reads on its own in the next round.+ */+export const VideoNotes = ({+ activeNoteKey,+ notes,+ onChange,+ onFocusNote,+ onRemove,+}: VideoNotesProps) => {+ const { t } = useTranslation('verify');+ const sorted = notes.filter((note) => note.time).sort((a, b) => a.time!.start - b.time!.start);++ return sorted.map((note, index) => {+ const time = note.time!;+ const span = time.end !== undefined;+ let placeholder = t('acceptance.video.notePlaceholderFrame');+ if (note.disputes) placeholder = t('acceptance.video.notePlaceholderDispute');+ else if (span) placeholder = t('acceptance.video.notePlaceholderRange');+ let detail = t('acceptance.video.frame', { frame: frameOf(time.start) });+ if (span)+ detail = t('acceptance.video.rangeSeconds', { seconds: (time.end! - time.start).toFixed(1) });+ else if (!isFullFrameRect(note.rect)) detail += ` · ${t('acceptance.video.circled')}`;++ return (+ <RegionNoteRow+ autoFocus={note.key === activeNoteKey && !note.comment}+ index={index + 1}+ key={note.key}+ placeholder={placeholder}+ value={note.comment}+ caption={+ <Flexbox gap={6}>+ <Flexbox horizontal align={'center'} gap={6}>+ <button+ className={cx(styles.stamp, note.key === activeNoteKey && styles.active)}+ type={'button'}+ onClick={() => onFocusNote(note)}+ >+ <Icon icon={span ? Repeat : Flag} size={11} />+ {span+ ? `${formatVideoTime(time.start)} – ${formatVideoTime(time.end!)}`+ : formatVideoTime(time.start)}+ </button>+ <span style={{ color: cssVar.colorTextTertiary, fontSize: 11 }}>{detail}</span>+ </Flexbox>+ {note.disputes && (+ <div className={styles.quote}>+ <ClaimLabel kind={note.disputes.kind} />+ <div>{note.disputes.note}</div>+ </div>+ )}+ </Flexbox>+ }+ onChange={(comment) => onChange(note.key, comment)}+ onRemove={() => onRemove(note.key)}+ />+ );+ });+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoReviewStage.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoReviewStage.tsxnew file mode 100644index 00000000000..3ec9106d536--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoReviewStage.tsx@@ -0,0 +1,423 @@+'use client';++import { isFullFrameRect } from '@lobechat/const/verify';+import type { AcceptanceReviewAnnotation, VerifyEvidenceChapter } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Flag, MessageSquareText, Repeat, X } from 'lucide-react';+import type { PointerEvent as ReactPointerEvent, RefObject } from 'react';+import { memo, useEffect, useImperativeHandle, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { DraftAnnotationEntry } from '../../Review/rejectDraft';+import { styles } from './styles';+import type { VideoLoop } from './useVideoClock';+import { useVideoClock } from './useVideoClock';+import {+ ClaimCaption,+ DraftRegion,+ FrameRegions,+ handlePlaybackKey,+ VideoControlBar,+ VideoLoadError,+} from './VideoChrome';+import { claimsAt, disputesClaim, formatVideoTime, frameOf } from './videoTime';+import { VideoTimeline } from './VideoTimeline';++type Rect = AcceptanceReviewAnnotation['rect'];++const local = createStaticStyles(({ css }) => ({+ column: css`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 10px;++ min-width: 0;+ min-height: 0;+ `,+ /** The frame shrinks to the room left by the timeline and the tools. */+ fit: css`+ display: flex;+ flex: 1;+ align-items: center;+ justify-content: center;++ min-height: 0;+ `,+ tools: css`+ flex: none;++ min-height: 40px;+ padding-block: 6px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadiusLG};++ font-size: 12px;++ background: ${cssVar.colorFillQuaternary};+ `,+ kbd: css`+ display: inline-block;++ min-width: 16px;+ margin-inline: 1px;+ padding-inline: 4px;+ border: 1px solid ${cssVar.colorBorder};+ border-radius: 4px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 10px;+ line-height: 16px;+ color: ${cssVar.colorTextSecondary};+ text-align: center;+ `,+ mono: css`+ font-family: ${cssVar.fontFamilyCode};+ font-variant-numeric: tabular-nums;+ `,+}));++export interface VideoReviewStageHandle {+ /** Pause on a note's frame (and select its span) — the notes panel's "go there". */+ focusNote: (note: DraftAnnotationEntry) => void;+}++interface VideoReviewStageProps {+ activeNoteKey?: number;+ chapters: VerifyEvidenceChapter[];+ handleRef?: RefObject<VideoReviewStageHandle | null>;+ notes: DraftAnnotationEntry[];+ onAddNote: (note: {+ disputes?: AcceptanceReviewAnnotation['disputes'];+ rect?: Rect;+ time: NonNullable<AcceptanceReviewAnnotation['time']>;+ }) => void;+ /** Re-sign the file link; resolves to the fresh URL, if the evidence still exists. */+ onRefreshSource?: () => Promise<string | undefined>;+ onSelectNote: (key: number) => void;+ src: string;+}++const isTyping = (target: EventTarget | null) =>+ target instanceof HTMLElement &&+ (target.isContentEditable || ['INPUT', 'SELECT', 'TEXTAREA'].includes(target.tagName));++/**+ * Where a video is rejected. Pressing on the picture pauses on the frame being+ * shown and draws a region on it; M marks the frame without a region; the lane+ * under the timeline (or I / O) selects a span that loops while it is judged;+ * and an agent claim captioned on screen can be disputed in one click.+ */+export const VideoReviewStage = memo<VideoReviewStageProps>(+ ({+ activeNoteKey,+ chapters,+ handleRef,+ notes,+ onAddNote,+ onRefreshSource,+ onSelectNote,+ src: initialSrc,+ }) => {+ const { t } = useTranslation('verify');+ const videoRef = useRef<HTMLVideoElement>(null);+ // The modal holds the link it opened with; a re-signed one replaces it here.+ const [src, setSrc] = useState(initialSrc);+ const [range, setRange] = useState<VideoLoop | null>(null);+ const [loop, setLoop] = useState(true);+ const clock = useVideoClock(videoRef, { loop: loop ? range : null, src });+ const { controls, duration, paused, size, status, time } = clock;+ const [draft, setDraft] = useState<Rect | null>(null);+ const [flash, setFlash] = useState<string | null>(null);+ const flashTimer = useRef<ReturnType<typeof setTimeout>>(undefined);++ const showFlash = (text: string) => {+ setFlash(text);+ clearTimeout(flashTimer.current);+ flashTimer.current = setTimeout(() => setFlash(null), 1400);+ };+ useEffect(() => () => clearTimeout(flashTimer.current), []);++ const focusNote = (note: DraftAnnotationEntry) => {+ if (!note.time) return;+ controls.pause();+ controls.seek(note.time.start);+ setRange(note.time.end === undefined ? null : { end: note.time.end, start: note.time.start });+ onSelectNote(note.key);+ };+ useImperativeHandle(handleRef, () => ({ focusNote }));++ const markFrame = () => {+ const start = controls.frameTime();+ controls.pause();+ onAddNote({ time: { start } });+ };++ const commentRange = () => {+ if (!range) return;+ onAddNote({ time: { end: range.end, start: range.start } });+ setRange(null);+ };++ // The modal is the review: keys act whenever the reviewer is not typing.+ const keyState = { clock, markFrame, range };+ const keyStateRef = useRef(keyState);+ keyStateRef.current = keyState;+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (isTyping(event.target) || event.metaKey || event.ctrlKey || event.altKey) return;+ const state = keyStateRef.current;+ if (state.clock.status !== 'ready') return;+ const now = state.clock.time;+ let handled = true;+ switch (event.key.toLowerCase()) {+ case 'm': {+ state.markFrame();+ break;+ }+ case 'i': {+ // Open-ended until O: a provisional end would loop playback short+ // of the moment the reviewer is waiting for.+ const end =+ state.range && state.range.end > now ? state.range.end : state.clock.duration;+ setRange({ end, start: now });+ showFlash(t('acceptance.video.inPoint', { time: formatVideoTime(now) }));+ break;+ }+ case 'o': {+ const start = state.range?.start ?? Math.max(0, now - 1);+ if (now > start) {+ setRange({ end: now, start });+ showFlash(t('acceptance.video.outPoint', { time: formatVideoTime(now) }));+ }+ break;+ }+ case 'escape': {+ if (!state.range) return;+ setRange(null);+ break;+ }+ default: {+ handled = handlePlaybackKey(event, state.clock);+ }+ }+ if (handled) {+ event.preventDefault();+ event.stopPropagation();+ }+ };+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ }, [t]);++ /** Press pauses on the frame on screen; a drag circles a region on it; a click plays. */+ const onStageDown = (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 = !paused;+ // The frame on screen at the press is the one being circled.+ const start = controls.frameTime();+ controls.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 up = () => {+ element.removeEventListener('pointermove', move);+ element.removeEventListener('pointerup', up);+ setDraft(null);+ const rect = current as Rect | null;+ if (rect && rect.width > 0.02 && rect.height > 0.02) {+ onAddNote({ rect, time: { start } });+ } else if (!wasPlaying) {+ controls.toggle();+ }+ };+ element.addEventListener('pointermove', move);+ element.addEventListener('pointerup', up);+ };++ const claims = claimsAt(chapters, time);+ const timed = notes.filter((note) => note.time);+ const aspect = size ? size.width / size.height : 16 / 9;++ let hint: string | null = flash;+ if (!hint && !draft)+ hint = paused+ ? t('acceptance.video.hintPaused', { frame: frameOf(time) })+ : t('acceptance.video.hintPlaying');++ return (+ <div className={local.column}>+ <div className={local.fit}>+ <div+ className={styles.player}+ style={{+ aspectRatio: `${aspect}`,+ maxHeight: '100%',+ width: 'auto',+ height: '100%',+ maxWidth: '100%',+ }}+ >+ <div className={styles.frame} style={{ height: '100%' }}>+ <video playsInline preload={'auto'} ref={videoRef} src={src} />+ {status === 'ready' && (+ <div className={cx(styles.overlay, styles.drawable)} onPointerDown={onStageDown}>+ <FrameRegions+ paused={paused}+ time={time}+ regions={timed+ .filter((note) => !isFullFrameRect(note.rect))+ .map((note) => ({+ comment: note.comment,+ key: note.key,+ rect: note.rect,+ start: note.time!.start,+ }))}+ />+ {draft && <DraftRegion rect={draft} />}+ {hint && <div className={styles.hint}>{hint}</div>}+ {claims.length > 0 && !draft && (+ <ClaimCaption+ claims={claims}+ action={(claim) => {+ const disputed = notes.some((note) => disputesClaim(note.disputes, claim));+ return (+ <button+ className={styles.dispute}+ disabled={disputed}+ type={'button'}+ onClick={() => {+ controls.pause();+ controls.seek(claim.t);+ onAddNote({+ disputes: { kind: claim.kind, note: claim.note, t: claim.t },+ time: { start: claim.t },+ });+ }}+ >+ {disputed+ ? t('acceptance.video.disputed')+ : t('acceptance.video.dispute')}+ </button>+ );+ }}+ />+ )}+ </div>+ )}+ {status === 'error' && (+ <VideoLoadError+ src={src}+ onReload={async () => {+ const fresh = await onRefreshSource?.();+ if (fresh && fresh !== src) setSrc(fresh);+ else controls.reload();+ }}+ />+ )}+ </div>+ </div>+ </div>+ {/* Not clipped like the frame: the hover preview rises above the bar. */}+ <div className={styles.player} style={{ flex: 'none', overflow: 'visible' }}>+ <div className={styles.bar} style={{ borderRadius: 'inherit' }}>+ <VideoTimeline+ activeNoteKey={activeNoteKey}+ chapters={chapters}+ duration={duration}+ range={range}+ src={src}+ time={time}+ notes={timed.map((note) => ({+ comment: note.comment,+ end: note.time!.end,+ key: note.key,+ start: note.time!.start,+ }))}+ onRange={setRange}+ onSeek={controls.seek}+ onClaimClick={(item) => {+ controls.pause();+ controls.seek(item.t);+ }}+ onNoteClick={(note) => {+ const entry = notes.find((item) => item.key === note.key);+ if (entry) focusNote(entry);+ }}+ />+ <VideoControlBar chapters={chapters} clock={clock} />+ </div>+ </div>+ <Flexbox horizontal align={'center'} className={local.tools} gap={8}>+ {range ? (+ <>+ <Icon icon={Repeat} size={14} />+ <span className={local.mono}>+ {formatVideoTime(range.start)} – {formatVideoTime(range.end)}+ </span>+ <Text fontSize={12} type={'secondary'}>+ {t('acceptance.video.rangeSeconds', {+ seconds: (range.end - range.start).toFixed(1),+ })}+ </Text>+ <div style={{ flex: 1 }} />+ <Button+ size={'small'}+ type={loop ? 'primary' : 'default'}+ onClick={() => setLoop((value) => !value)}+ >+ {t('acceptance.video.loop')}+ </Button>+ <Button icon={MessageSquareText} size={'small'} onClick={commentRange}>+ {t('acceptance.video.commentRange')}+ </Button>+ <ActionIcon+ icon={X}+ size={'small'}+ title={t('acceptance.video.clearRange')}+ onClick={() => setRange(null)}+ />+ </>+ ) : (+ <>+ <Text fontSize={12} type={'secondary'}>+ <span className={local.kbd}>Space</span> {t('acceptance.video.play')} ·{' '}+ <span className={local.kbd}>,</span>+ <span className={local.kbd}>.</span> {t('acceptance.video.keysFrame')} ·{' '}+ <span className={local.kbd}>J</span>+ <span className={local.kbd}>L</span> {t('acceptance.video.speed')} ·{' '}+ <span className={local.kbd}>M</span> {t('acceptance.video.markFrame')} ·{' '}+ <span className={local.kbd}>I</span>+ <span className={local.kbd}>O</span> {t('acceptance.video.keysRange')}+ </Text>+ <div style={{ flex: 1 }} />+ <Button disabled={status !== 'ready'} icon={Flag} size={'small'} onClick={markFrame}>+ {t('acceptance.video.markFrame')}+ </Button>+ </>+ )}+ </Flexbox>+ </div>+ );+ },+);++VideoReviewStage.displayName = 'AcceptanceVideoReviewStage';diff --git a/src/features/Acceptance/Viewer/Evidence/Video/VideoTimeline.tsx b/src/features/Acceptance/Viewer/Evidence/Video/VideoTimeline.tsxnew file mode 100644index 00000000000..a4c66311e24--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/VideoTimeline.tsx@@ -0,0 +1,265 @@+'use client';++import type { VerifyEvidenceChapter } from '@lobechat/types';+import { cx } from 'antd-style';+import type { PointerEvent as ReactPointerEvent } from 'react';+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { ClaimLabel } from './ClaimLabel';+import { CLAIM_COLOR, styles } from './styles';+import type { VideoLoop } from './useVideoClock';+import { claimsOf, formatVideoTime, stepAt, stepsOf } from './videoTime';++/** A reviewer note as the timeline sees it: a moment, or a span. */+export interface TimelineNote {+ comment?: string;+ end?: number;+ key: number | string;+ start: number;+}++/** Hovering within this share of the track snaps to a marker's own frame. */+const SNAP_RATIO = 0.012;++interface HoverState {+ claim?: VerifyEvidenceChapter;+ comment?: string;+ step?: string;+ time: number;+ x: number;+}++/**+ * The frame under the pointer, painted from a hidden second `<video>`: seeking+ * the one on screen would move the playhead the reviewer is holding. Seeks+ * queue behind each other so a fast sweep never stalls on stale frames.+ */+const HoverPreview = ({ claim, comment, src, step, time, x }: HoverState & { src: string }) => {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const probeRef = useRef<HTMLVideoElement>(null);+ const pending = useRef<number | null>(null);+ const busy = useRef(false);++ useEffect(() => {+ const probe = probeRef.current;+ if (!probe) return;+ const paint = () => {+ const canvas = canvasRef.current;+ canvas?.getContext('2d')?.drawImage(probe, 0, 0, canvas.width, canvas.height);+ busy.current = false;+ if (pending.current === null) return;+ busy.current = true;+ probe.currentTime = pending.current;+ pending.current = null;+ };+ probe.addEventListener('seeked', paint);+ return () => probe.removeEventListener('seeked', paint);+ }, []);++ useEffect(() => {+ const probe = probeRef.current;+ if (!probe) return;+ if (busy.current) {+ pending.current = time;+ return;+ }+ busy.current = true;+ probe.currentTime = time;+ }, [time]);++ return (+ <div className={styles.preview} style={{ left: x }}>+ <video muted preload={'auto'} ref={probeRef} src={src} style={{ display: 'none' }} />+ <canvas height={99} ref={canvasRef} width={176} />+ <div className={styles.previewMeta}>+ <span className={styles.mono}>{formatVideoTime(time)}</span>+ {step && <span style={{ color: '#999' }}> · {step}</span>}+ {claim && (+ <div>+ <ClaimLabel kind={claim.kind} style={{ marginInlineEnd: 6 }} />+ {claim.note}+ </div>+ )}+ {comment && <div style={{ color: '#ffb4ab' }}>{comment}</div>}+ </div>+ </div>+ );+};++interface VideoTimelineProps {+ activeNoteKey?: number | string;+ chapters: VerifyEvidenceChapter[];+ duration: number;+ notes: TimelineNote[];+ onClaimClick: (claim: VerifyEvidenceChapter) => void;+ onNoteClick: (note: TimelineNote) => void;+ /** Present in review: the lane below the track selects a span. */+ onRange?: (range: VideoLoop | null) => void;+ onSeek: (seconds: number) => void;+ range?: VideoLoop | null;+ src: string;+ time: number;+}++/**+ * The scrubber and everything pinned to it: the agent's steps as ticks, its+ * claims as dots (check) and diamonds (flag) above the rail, and reviewer notes+ * as red marks on it. In review a lane below the rail selects a span.+ */+export const VideoTimeline = ({+ activeNoteKey,+ chapters,+ duration,+ notes,+ onClaimClick,+ onNoteClick,+ onRange,+ onSeek,+ range,+ src,+ time,+}: VideoTimelineProps) => {+ const { t } = useTranslation('verify');+ const trackRef = useRef<HTMLDivElement>(null);+ const [hover, setHover] = useState<HoverState | null>(null);+ const pct = (seconds: number) => `${(duration ? seconds / duration : 0) * 100}%`;++ const timeAt = (element: HTMLElement, clientX: number) => {+ const box = element.getBoundingClientRect();+ return Math.min(Math.max((clientX - box.left) / box.width, 0), 1) * duration;+ };++ /** Pointer-captured drag: the gesture keeps tracking outside the element. */+ const drag = (+ event: ReactPointerEvent<HTMLDivElement>,+ onMove: (seconds: number) => void,+ onEnd?: (seconds: number) => void,+ ) => {+ const element = event.currentTarget;+ element.setPointerCapture(event.pointerId);+ const move = (next: PointerEvent) => onMove(timeAt(element, next.clientX));+ const up = (next: PointerEvent) => {+ element.removeEventListener('pointermove', move);+ element.removeEventListener('pointerup', up);+ onEnd?.(timeAt(element, next.clientX));+ };+ element.addEventListener('pointermove', move);+ element.addEventListener('pointerup', up);+ };++ const onTrackDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ onSeek(timeAt(event.currentTarget, event.clientX));+ drag(event, onSeek);+ };++ const onLaneDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!onRange) return;+ const anchor = timeAt(event.currentTarget, event.clientX);+ onRange({ end: anchor, start: anchor });+ drag(+ event,+ (seconds) => onRange({ end: Math.max(anchor, seconds), start: Math.min(anchor, seconds) }),+ (seconds) => {+ // A click, not a drag, clears the span rather than leaving a sliver.+ if (Math.abs(seconds - anchor) < 0.15) onRange(null);+ else onSeek(Math.min(anchor, seconds));+ },+ );+ };++ const onHover = (event: ReactPointerEvent<HTMLDivElement>) => {+ const track = trackRef.current;+ if (!track || !duration) return;+ const box = track.getBoundingClientRect();+ const seconds = timeAt(track, event.clientX);+ const snap = duration * SNAP_RATIO;+ const note = notes.find((item) => Math.abs(item.start - seconds) < snap);+ const claim = note+ ? undefined+ : claimsOf(chapters).find((item) => Math.abs(item.t - seconds) < snap);+ setHover({+ claim,+ comment: note?.comment,+ step: stepAt(chapters, seconds)?.label,+ time: note?.start ?? claim?.t ?? seconds,+ x: Math.min(Math.max(event.clientX - box.left, 88), box.width - 88),+ });+ };++ const span = range && (+ <div+ className={styles.rangeBand}+ style={{ left: pct(range.start), width: pct(range.end - range.start) }}+ />+ );++ return (+ <div className={styles.timeline}>+ {hover && <HoverPreview {...hover} src={src} />}+ <div+ aria-label={t('acceptance.video.seek')}+ aria-valuemax={Math.round(duration)}+ aria-valuemin={0}+ aria-valuenow={Math.round(time)}+ className={styles.track}+ ref={trackRef}+ role={'slider'}+ onPointerDown={onTrackDown}+ onPointerLeave={() => setHover(null)}+ onPointerMove={onHover}+ >+ <div className={styles.rail} />+ <div className={styles.played} style={{ width: pct(time) }} />+ {stepsOf(chapters).map((step) =>+ step.t > 0 ? (+ <div className={styles.stepTick} key={`step-${step.t}`} style={{ left: pct(step.t) }} />+ ) : null,+ )}+ {span}+ {notes+ .filter((note) => note.end !== undefined)+ .map((note) => (+ <div+ className={styles.noteSpan}+ key={`span-${note.key}`}+ style={{ left: pct(note.start), width: pct(note.end! - note.start) }}+ />+ ))}+ <div className={styles.head} style={{ left: pct(time) }} />+ {claimsOf(chapters).map((claim, index) => (+ <button+ aria-label={`${t(`acceptance.video.claim.${claim.kind}`)} ${formatVideoTime(claim.t)}: ${claim.note}`}+ className={styles.claimMark}+ key={`claim-${claim.kind}-${claim.t}-${index}`}+ style={{ background: CLAIM_COLOR[claim.kind], left: pct(claim.t) }}+ type={'button'}+ // The press must not also scrub the track; the click (pointer, Enter+ // or Space) is what seeks, so the marker works from the keyboard.+ onClick={() => onClaimClick(claim)}+ onPointerDown={(event) => event.stopPropagation()}+ />+ ))}+ {notes.map((note) => (+ <button+ aria-label={`${formatVideoTime(note.start)} ${note.comment ?? ''}`}+ className={cx(styles.noteMark, activeNoteKey === note.key && styles.noteMarkActive)}+ key={`note-${note.key}`}+ style={{ left: pct(note.start) }}+ type={'button'}+ // The press must not also scrub the track; the click (pointer, Enter+ // or Space) is what seeks, so the marker works from the keyboard.+ onClick={() => onNoteClick(note)}+ onPointerDown={(event) => event.stopPropagation()}+ />+ ))}+ </div>+ {onRange && (+ <div className={styles.lane} onPointerDown={onLaneDown}>+ {!range && <span className={styles.laneLabel}>{t('acceptance.video.rangeLane')}</span>}+ {span}+ </div>+ )}+ </div>+ );+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/styles.ts b/src/features/Acceptance/Viewer/Evidence/Video/styles.tsnew file mode 100644index 00000000000..b5cee367964--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/styles.ts@@ -0,0 +1,424 @@+import type { VerifyEvidenceChapterKind } from '@lobechat/types';+import { createStaticStyles, cssVar } from 'antd-style';++/**+ * The player chrome is dark in both themes, as video chrome is everywhere: it+ * sits on the black letterbox and must not flash white around a dark recording.+ */+export const styles = createStaticStyles(({ css }) => ({+ player: css`+ position: relative;++ overflow: hidden;++ width: 100%;+ border-radius: ${cssVar.borderRadiusLG};++ background: #000;+ outline: none;++ &:focus-visible {+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBorder};+ }+ `,+ frame: css`+ position: relative;+ width: 100%;+ background: #000;++ video {+ display: block;+ width: 100%;+ height: 100%;+ }+ `,+ overlay: css`+ position: absolute;+ inset: 0;+ `,+ drawable: css`+ touch-action: none;+ cursor: crosshair;+ `,+ region: css`+ pointer-events: none;++ position: absolute;++ border: 2px solid ${cssVar.colorError};+ border-radius: 4px;++ box-shadow: 0 0 0 9999px rgb(0 0 0 / 20%);+ `,+ regionLabel: css`+ position: absolute;+ inset-block-start: -22px;+ inset-inline-start: -2px;++ overflow: hidden;++ max-width: 240px;+ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-size: 11px;+ line-height: 18px;+ color: #fff;+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorError};+ `,+ draft: css`+ pointer-events: none;+ position: absolute;+ border: 2px dashed ${cssVar.colorWarning};+ border-radius: 4px;+ `,+ centerPlay: css`+ pointer-events: none;++ position: absolute;+ inset-block-start: 50%;+ inset-inline-start: 50%;+ transform: translate(-50%, -50%);++ display: flex;+ align-items: center;+ justify-content: center;++ width: 56px;+ height: 56px;+ border-radius: 50%;++ color: #fff;++ background: rgb(0 0 0 / 55%);+ `,+ hint: css`+ pointer-events: none;++ position: absolute;+ inset-block-start: 12px;+ inset-inline-start: 50%;+ transform: translateX(-50%);++ padding-block: 4px;+ padding-inline: 10px;+ border-radius: 999px;++ font-size: 12px;+ color: #fff;+ white-space: nowrap;++ background: rgb(0 0 0 / 65%);+ `,+ caption: css`+ position: absolute;+ inset-block-end: 14px;+ inset-inline-start: 50%;+ transform: translateX(-50%);++ display: flex;+ flex-direction: column;+ gap: 2px;++ max-width: 80%;+ padding-block: 6px 8px;+ padding-inline: 12px;+ border-radius: 8px;++ font-size: 13px;+ line-height: 1.5;+ color: #fff;++ background: rgb(0 0 0 / 78%);+ `,+ captionTitle: css`+ display: flex;+ gap: 12px;+ align-items: center;+ justify-content: space-between;++ font-size: 12px;+ color: rgb(255 255 255 / 85%);+ `,+ dispute: css`+ cursor: pointer;++ flex: none;++ padding-block: 1px;+ padding-inline: 8px;+ border: 1px solid rgb(255 255 255 / 30%);+ border-radius: 4px;++ font-size: 12px;+ color: #fff;++ background: transparent;++ &:disabled {+ cursor: default;+ opacity: 0.5;+ }++ &:hover:not(:disabled) {+ background: rgb(255 255 255 / 12%);+ }+ `,+ bar: css`+ padding-block: 6px 8px;+ padding-inline: 12px;+ color: #eee;+ background: #151515;+ `,+ time: css`+ margin-inline-start: 6px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: #ddd;+ white-space: nowrap;+ `,+ frameNo: css`+ overflow: hidden;++ margin-inline-start: 8px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ color: #888;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ barButton: css`+ cursor: pointer;++ display: inline-flex;+ flex: none;+ align-items: center;+ justify-content: center;++ min-width: 28px;+ height: 28px;+ padding-inline: 6px;+ border: none;+ border-radius: 6px;++ font-size: 12px;+ color: #ddd;++ background: transparent;++ &:hover {+ background: rgb(255 255 255 / 10%);+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimaryBorder};+ }+ `,+ barButtonActive: css`+ color: #fff;+ background: rgb(255 255 255 / 12%);+ `,+ /* ---------------- timeline ---------------- */+ timeline: css`+ user-select: none;+ position: relative;+ padding-block: 14px 4px;+ `,+ track: css`+ touch-action: none;+ cursor: pointer;+ position: relative;+ height: 20px;+ `,+ rail: css`+ position: absolute;+ inset-block-start: 8px;+ inset-inline: 0;++ height: 4px;+ border-radius: 2px;++ background: rgb(255 255 255 / 18%);+ `,+ played: css`+ position: absolute;+ inset-block-start: 8px;+ inset-inline-start: 0;++ height: 4px;+ border-radius: 2px;++ background: #fff;+ `,+ head: css`+ pointer-events: none;++ position: absolute;+ inset-block-start: 4px;+ transform: translateX(-50%);++ width: 12px;+ height: 12px;+ border-radius: 50%;++ background: #fff;+ box-shadow: 0 0 0 3px rgb(0 0 0 / 40%);+ `,+ stepTick: css`+ pointer-events: none;++ position: absolute;+ inset-block-start: 7px;+ transform: translateX(-50%);++ width: 2px;+ height: 6px;++ background: #151515;+ `,+ claimMark: css`+ cursor: pointer;++ position: absolute;+ z-index: 3;+ inset-block-start: -9px;+ transform: translateX(-50%);++ width: 8px;+ height: 8px;+ padding: 0;+ border: 1.5px solid #151515;+ border-radius: 50%;++ &:hover {+ transform: translateX(-50%) scale(1.4);+ }+ `,+ noteMark: css`+ cursor: pointer;++ position: absolute;+ z-index: 2;+ inset-block-start: -2px;+ transform: translateX(-50%);++ width: 10px;+ height: 10px;+ padding: 0;+ border: 2px solid #151515;+ border-radius: 50%;++ background: ${cssVar.colorError};++ &:hover {+ transform: translateX(-50%) scale(1.3);+ }+ `,+ noteMarkActive: css`+ box-shadow: 0 0 0 2px ${cssVar.colorErrorBorder};+ `,+ noteSpan: css`+ pointer-events: none;++ position: absolute;+ inset-block-start: 6px;++ height: 8px;+ border-radius: 2px;++ opacity: 0.6;+ background: ${cssVar.colorError};+ `,+ rangeBand: css`+ pointer-events: none;++ position: absolute;+ inset-block: 2px;++ border-radius: 3px;++ background: color-mix(in srgb, ${cssVar.colorWarning} 25%, transparent);+ box-shadow: inset 0 0 0 1px ${cssVar.colorWarning};+ `,+ lane: css`+ touch-action: none;+ cursor: text;++ position: relative;++ height: 16px;+ margin-block-start: 4px;+ border-radius: 4px;++ background: repeating-linear-gradient(+ 90deg,+ rgb(255 255 255 / 6%) 0,+ rgb(255 255 255 / 6%) 1px,+ transparent 1px,+ transparent 12px+ );+ `,+ laneLabel: css`+ pointer-events: none;++ position: absolute;+ inset-block-start: 0;+ inset-inline-start: 6px;++ font-size: 10px;+ line-height: 16px;+ color: #777;+ `,+ preview: css`+ pointer-events: none;++ position: absolute;+ z-index: 5;+ inset-block-end: 34px;+ transform: translateX(-50%);++ overflow: hidden;++ width: 176px;+ border: 1px solid #333;+ border-radius: 8px;++ background: #000;+ box-shadow: 0 6px 20px rgb(0 0 0 / 50%);++ canvas {+ display: block;+ width: 176px;+ height: 99px;+ }+ `,+ previewMeta: css`+ padding-block: 4px;+ padding-inline: 8px;++ font-size: 11px;+ line-height: 1.5;+ color: #ddd;++ background: #1b1b1b;+ `,+ mono: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ `,+}));++/** Marker colours, shared by the timeline marks, the caption and the claim list. */+export const CLAIM_COLOR: Record<VerifyEvidenceChapterKind, string> = {+ check: cssVar.colorSuccess,+ flag: cssVar.colorWarning,+ step: cssVar.colorTextTertiary,+};diff --git a/src/features/Acceptance/Viewer/Evidence/Video/useVideoClock.test.ts b/src/features/Acceptance/Viewer/Evidence/Video/useVideoClock.test.tsnew file mode 100644index 00000000000..38b0921e1d2--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/useVideoClock.test.ts@@ -0,0 +1,98 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useVideoClock } from './useVideoClock';++type FrameCallback = (now: number, frame: { mediaTime: number }) => void;++/**+ * Just enough of a `<video>` for the clock: the media clock (`currentTime`)+ * and the painted frame are separate, and `pause` is delivered as an event+ * after the call returns — exactly the two facts the clock has to reconcile.+ */+class FakeVideo extends EventTarget {+ currentTime = 0;+ duration = 15;+ paused = false;+ playbackRate = 1;+ readyState = 1;+ videoHeight = 720;+ videoWidth = 1280;+ private frameCallback?: FrameCallback;++ requestVideoFrameCallback(callback: FrameCallback) {+ this.frameCallback = callback;+ return 1;+ }++ cancelVideoFrameCallback() {}++ /** The browser paints a frame, then its media clock keeps running a little. */+ paint(mediaTime: number, clockRunsTo: number) {+ this.currentTime = mediaTime;+ this.frameCallback?.(0, { mediaTime });+ this.currentTime = clockRunsTo;+ }++ pause() {+ this.paused = true;+ queueMicrotask(() => this.dispatchEvent(new Event('pause')));+ }+}++const setup = () => {+ const video = new FakeVideo();+ const ref = { current: video as unknown as HTMLVideoElement };+ const hook = renderHook(() => useVideoClock(ref, { src: 'clip.mp4' }));+ return { hook, video };+};++describe('useVideoClock', () => {+ it('pauses on the frame that was on screen, not where the media clock ran to', async () => {+ const { hook, video } = setup();+ act(() => video.paint(7.42, 7.44));++ // A note made at the press names the painted frame...+ expect(hook.result.current.controls.frameTime()).toBe(7.42);+ await act(async () => hook.result.current.controls.pause());++ // ...and after the pause the clock and the readout agree with it, so a+ // region drawn now is shown on the frame it was drawn on.+ expect(video.currentTime).toBe(7.42);+ expect(hook.result.current.time).toBe(7.42);+ });++ it('never lets the late pause event drag a seek back to the old frame', async () => {+ const { hook, video } = setup();+ act(() => video.paint(7.42, 7.44));++ await act(async () => {+ hook.result.current.controls.pause();+ hook.result.current.controls.seek(3);+ });++ expect(video.currentTime).toBe(3);+ });++ it('keeps stepping one frame at a time when a stale frame is reported after a paused seek', async () => {+ const { hook, video } = setup();+ video.paused = true;+ video.currentTime = 163.5 / 30;+ // The browser reports the frame that was up before the seek landed.+ act(() => video.paint(162 / 30, 163.5 / 30));++ await act(async () => hook.result.current.controls.step(1));++ expect(video.currentTime).toBeCloseTo(164.5 / 30, 5);+ });++ it('steps from the painted frame while playing', async () => {+ const { hook, video } = setup();+ act(() => video.paint(7.42, 7.48));++ await act(async () => hook.result.current.controls.step(1));++ // 7.42s is frame 222; one step lands in the middle of frame 223.+ expect(video.currentTime).toBeCloseTo(223.5 / 30, 5);+ });+});diff --git a/src/features/Acceptance/Viewer/Evidence/Video/useVideoClock.ts b/src/features/Acceptance/Viewer/Evidence/Video/useVideoClock.tsnew file mode 100644index 00000000000..201d8fb3002--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/useVideoClock.ts@@ -0,0 +1,170 @@+'use client';++import type { RefObject } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';++import { steppedTime } from './videoTime';++export interface VideoLoop {+ end: number;+ start: number;+}++const RATE_STORAGE_KEY = 'acceptance-video-rate';++const readStoredRate = () => {+ try {+ const value = Number(localStorage.getItem(RATE_STORAGE_KEY));+ return Number.isFinite(value) && value > 0 ? value : 1;+ } catch {+ return 1;+ }+};++/**+ * The state of one `<video>`, frame-accurate while playing.+ *+ * `timeupdate` fires a few times a second, which is too coarse to put a region+ * on the frame it was drawn on; `requestVideoFrameCallback` reports every+ * painted frame, with `requestAnimationFrame` as the fallback. The chosen+ * playback rate is remembered across videos: a reviewer who watches at 1.5×+ * wants the next recording at 1.5× too.+ */+export const useVideoClock = (+ videoRef: RefObject<HTMLVideoElement | null>,+ { loop, src }: { loop?: VideoLoop | null; src: string },+) => {+ const [time, setTime] = useState(0);+ const [duration, setDuration] = useState(0);+ const [paused, setPaused] = useState(true);+ const [rate, setRateState] = useState(1);+ const [size, setSize] = useState<{ height: number; width: number } | null>(null);+ const [status, setStatus] = useState<'error' | 'loading' | 'ready'>('loading');+ const loopRef = useRef(loop);+ loopRef.current = loop;+ /**+ * The time of the frame actually on screen. `currentTime` runs ahead of it:+ * pausing lands a frame or so past what was painted, and a region drawn on+ * the picture belongs to the picture, not to the media clock. Only tracked+ * while playing — once paused, `currentTime` is exact, and a frame reported+ * after a paused seek may still be the one from before it. Cleared by every+ * deliberate seek, so the (asynchronous) pause event never drags a seek back+ * to the frame that was showing before it.+ */+ const paintedRef = useRef<number | undefined>(undefined);++ useEffect(() => {+ const video = videoRef.current;+ if (!video) return;+ setStatus('loading');+ video.playbackRate = readStoredRate();++ let handle = 0;+ const schedule = () => {+ handle = video.requestVideoFrameCallback+ ? video.requestVideoFrameCallback(tick)+ : requestAnimationFrame(tick);+ };+ const tick = (_now?: number, frame?: { mediaTime: number }) => {+ const span = loopRef.current;+ if (span && !video.paused && video.currentTime >= span.end) video.currentTime = span.start;+ if (!video.paused) paintedRef.current = frame?.mediaTime;+ setTime(video.paused ? video.currentTime : (paintedRef.current ?? video.currentTime));+ schedule();+ };+ const onMeta = () => {+ setDuration(video.duration);+ setSize({ height: video.videoHeight, width: video.videoWidth });+ setStatus('ready');+ };+ const onPlay = () => setPaused(false);+ const onPause = () => {+ setPaused(true);+ // Hold the clock on the painted frame, so the readout, a region drawn+ // now and a later seek back all name the frame the reviewer is looking at.+ const painted = paintedRef.current;+ paintedRef.current = undefined;+ if (painted !== undefined && Math.abs(video.currentTime - painted) > 1e-3)+ video.currentTime = painted;+ };+ const onSeeked = () => {+ paintedRef.current = undefined;+ setTime(video.currentTime);+ };+ const onRate = () => setRateState(video.playbackRate);+ const onError = () => setStatus('error');++ if (video.readyState >= 1) onMeta();+ video.addEventListener('loadedmetadata', onMeta);+ video.addEventListener('play', onPlay);+ video.addEventListener('pause', onPause);+ video.addEventListener('seeked', onSeeked);+ video.addEventListener('ratechange', onRate);+ video.addEventListener('error', onError);+ schedule();++ return () => {+ video.removeEventListener('loadedmetadata', onMeta);+ video.removeEventListener('play', onPlay);+ video.removeEventListener('pause', onPause);+ video.removeEventListener('seeked', onSeeked);+ video.removeEventListener('ratechange', onRate);+ video.removeEventListener('error', onError);+ if (video.cancelVideoFrameCallback) video.cancelVideoFrameCallback(handle);+ else cancelAnimationFrame(handle);+ };+ }, [videoRef, src]);++ const controls = useMemo(+ () => ({+ /** The time of the frame on screen — what a note made right now is about. */+ frameTime: () => {+ const video = videoRef.current;+ if (!video) return 0;+ return video.paused ? video.currentTime : (paintedRef.current ?? video.currentTime);+ },+ pause: () => videoRef.current?.pause(),+ reload: () => {+ setStatus('loading');+ videoRef.current?.load();+ },+ seek: (seconds: number) => {+ const video = videoRef.current;+ if (!video) return;+ paintedRef.current = undefined;+ video.currentTime = Math.min(Math.max(seconds, 0), video.duration || 0);+ setTime(video.currentTime);+ },+ setRate: (value: number) => {+ if (videoRef.current) videoRef.current.playbackRate = value;+ try {+ localStorage.setItem(RATE_STORAGE_KEY, String(value));+ } catch {+ /* private mode — the rate simply resets next time */+ }+ },+ step: (frames: number) => {+ const video = videoRef.current;+ if (!video) return;+ const from = video.paused ? video.currentTime : (paintedRef.current ?? video.currentTime);+ paintedRef.current = undefined;+ video.pause();+ video.currentTime = steppedTime(from, frames, video.duration || 0);+ },+ toggle: () => {+ const video = videoRef.current;+ if (!video) return;+ if (!video.paused) return video.pause();+ const span = loopRef.current;+ if (video.ended || (span && video.currentTime >= span.end))+ video.currentTime = span?.start ?? 0;+ void video.play();+ },+ }),+ [videoRef],+ );++ return { controls, duration, paused, rate, size, status, time };+};++export type VideoClock = ReturnType<typeof useVideoClock>;diff --git a/src/features/Acceptance/Viewer/Evidence/Video/videoTime.test.ts b/src/features/Acceptance/Viewer/Evidence/Video/videoTime.test.tsnew file mode 100644index 00000000000..622f5f47729--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/videoTime.test.ts@@ -0,0 +1,87 @@+import type { VerifyEvidenceChapter } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ claimAt,+ claimsAt,+ disputesClaim,+ formatVideoClock,+ formatVideoTime,+ frameOf,+ isOnFrame,+ stepAt,+ steppedTime,+} from './videoTime';++const chapters: VerifyEvidenceChapter[] = [+ { kind: 'step', label: 'Open', t: 0 },+ { kind: 'step', label: 'Scroll #3', t: 6 },+ { kind: 'flag', note: 'request count 0 → 1', t: 7 },+ { kind: 'check', note: 'no skeleton', t: 7.9 },+];++describe('video time', () => {+ it('formats to the hundredth, and chapter chips to the second', () => {+ expect(formatVideoTime(7.2)).toBe('0:07.20');+ expect(formatVideoTime(66.75)).toBe('1:06.75');+ expect(formatVideoTime(Number.NaN)).toBe('0:00.00');+ expect(formatVideoClock(12.5)).toBe('0:12');+ });++ it('steps exactly one frame at a time without drifting', () => {+ let time = 0;+ for (let i = 0; i < 90; i += 1) time = steppedTime(time, 1, 15);+ expect(frameOf(time)).toBe(90);+ expect(frameOf(steppedTime(time, -1, 15))).toBe(89);+ expect(steppedTime(14.99, 5, 15)).toBe(15);+ expect(steppedTime(0, -1, 15)).toBe(0);+ });++ it('names the step the playhead is in', () => {+ expect(stepAt(chapters, 6.5)?.label).toBe('Scroll #3');+ expect(stepAt(chapters, 5.9)?.label).toBe('Open');+ });++ it('captions a claim from its frame for two seconds, the newest one winning', () => {+ expect(claimAt(chapters, 6.9)).toBeUndefined();+ expect(claimAt(chapters, 7)?.kind).toBe('flag');+ expect(claimAt(chapters, 8)?.kind).toBe('check');+ expect(claimAt(chapters, 9.95)).toBeUndefined();+ });++ it('keeps a paused region on its own frame only', () => {+ expect(isOnFrame(7.2, 7.2, true)).toBe(true);+ expect(isOnFrame(7.2, 7.2 + 1 / 30, true)).toBe(false);+ expect(isOnFrame(7.2, 7.4, false)).toBe(true);+ });+});++describe('disputesClaim', () => {+ // Two self-checks can share a frame; disputing one must not settle the other.+ it('tells apart two claims of the same kind on the same frame', () => {+ const first = { kind: 'check' as const, note: 'no skeleton', t: 7.9 };+ const second = { kind: 'check' as const, note: 'first question in place', t: 7.9 };++ expect(disputesClaim(first, first)).toBe(true);+ expect(disputesClaim(first, second)).toBe(false);+ expect(disputesClaim(undefined, first)).toBe(false);+ });+});++describe('claimsAt', () => {+ // The caption is where claims are disputed; one hiding another could never be.+ it('captions every claim that shares the frame, not just the last one', () => {+ const sameFrame = [+ { kind: 'check' as const, note: 'no skeleton', t: 7.9 },+ { kind: 'check' as const, note: 'first question in place', t: 7.9 },+ { kind: 'flag' as const, note: 'count 0 → 1', t: 7 },+ ];++ expect(claimsAt(sameFrame, 8).map((claim) => claim.note)).toEqual([+ 'no skeleton',+ 'first question in place',+ ]);+ expect(claimsAt(sameFrame, 7.2).map((claim) => claim.note)).toEqual(['count 0 → 1']);+ expect(claimsAt(sameFrame, 12)).toEqual([]);+ });+});diff --git a/src/features/Acceptance/Viewer/Evidence/Video/videoTime.ts b/src/features/Acceptance/Viewer/Evidence/Video/videoTime.tsnew file mode 100644index 00000000000..992750b054d--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/Video/videoTime.ts@@ -0,0 +1,88 @@+import type { VerifyEvidenceChapter } from '@lobechat/types';++/**+ * Frame rate assumed for stepping. Recordings are assembled at a fixed rate+ * (the acceptance skill uses 30), and the browser exposes no frame rate, so a+ * step moves one 1/30 s tick — close enough to land on each captured frame.+ */+export const VIDEO_FPS = 30;++export const PLAYBACK_RATES = [0.5, 1, 1.5, 2] as const;++/** How long a claim stays on screen after its frame, like a subtitle. */+export const CLAIM_CAPTION_SECONDS = 2;++export { formatVideoTimestamp as formatVideoTime } from '@lobechat/const/verify';++/**+ * Whether a note disputes this exact claim. Two claims can share a frame and a+ * kind, so the quoted text is part of the identity.+ */+export const disputesClaim = (+ disputes: Pick<VerifyEvidenceChapter, 'kind' | 'note' | 't'> | undefined,+ claim: VerifyEvidenceChapter,+) =>+ Boolean(disputes) &&+ disputes!.t === claim.t &&+ disputes!.kind === claim.kind &&+ disputes!.note === claim.note;++/** `m:ss` for chapter chips, where hundredths are noise. */+export const formatVideoClock = (seconds: number) => {+ const minutes = Math.floor(seconds / 60);+ return `${minutes}:${String(Math.floor(seconds - minutes * 60)).padStart(2, '0')}`;+};++/**+ * The frame on screen at a time: frame n shows from n/fps until (n+1)/fps.+ * The epsilon absorbs float error at exact frame boundaries.+ */+export const frameOf = (seconds: number) => Math.floor(seconds * VIDEO_FPS + 1e-6);++/**+ * The time to seek to for a frame step. It lands on frame centres, so+ * repeated steps never skip a frame or show the same one twice.+ */+export const steppedTime = (current: number, frames: number, duration: number) =>+ Math.min(Math.max((frameOf(current) + frames + 0.5) / VIDEO_FPS, 0), duration);++export const stepsOf = (chapters: VerifyEvidenceChapter[]) =>+ chapters.filter((chapter) => chapter.kind === 'step');++/** What the agent claims (`check`) or disclosed (`flag`) — the parts a reviewer audits. */+export const claimsOf = (chapters: VerifyEvidenceChapter[]) =>+ chapters.filter((chapter) => chapter.kind !== 'step');++/** The step the playhead is in, for the "frame 210 · Scroll #3" readout. */+export const stepAt = (chapters: VerifyEvidenceChapter[], time: number) =>+ stepsOf(chapters).findLast((chapter) => chapter.t <= time + 0.01);++/** The claim to caption at this time: from its frame until it has been read. */+export const claimAt = (chapters: VerifyEvidenceChapter[], time: number) =>+ claimsOf(chapters)+ .filter(+ (chapter) => time >= chapter.t - 0.5 / VIDEO_FPS && time < chapter.t + CLAIM_CAPTION_SECONDS,+ )+ // The most recent claim wins, whatever order the chapters arrived in.+ .reduce<VerifyEvidenceChapter | undefined>(+ (latest, chapter) => (!latest || chapter.t >= latest.t ? chapter : latest),+ undefined,+ );++/**+ * Every claim on the frame being captioned. Two claims can share a frame; the+ * caption is where each one is read and disputed, so none may hide behind+ * another.+ */+export const claimsAt = (chapters: VerifyEvidenceChapter[], time: number) => {+ const latest = claimAt(chapters, time);+ return latest ? claimsOf(chapters).filter((chapter) => chapter.t === latest.t) : [];+};++/**+ * Whether a region drawn on the frame at `start` belongs on screen. Paused, it+ * shows only on its own frame, so a region never lands on a frame it was not+ * drawn on; playing, it lingers long enough to be seen at all.+ */+export const isOnFrame = (start: number, time: number, paused: boolean) =>+ Math.abs(start - time) <= (paused ? 0.5 / VIDEO_FPS : 0.35);diff --git a/src/features/Acceptance/Viewer/Evidence/canMarkEvidence.test.ts b/src/features/Acceptance/Viewer/Evidence/canMarkEvidence.test.tsnew file mode 100644index 00000000000..788e00378d7--- /dev/null+++ b/src/features/Acceptance/Viewer/Evidence/canMarkEvidence.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import type { AcceptanceCheck } from '../Checks/types';+import { canMarkEvidence } from './evidence';++const check = (...types: string[]) =>+ ({+ evidence: types.map((type, index) => ({ fileUrl: `f${index}`, id: `e${index}`, type })),+ }) as unknown as AcceptanceCheck;++describe('canMarkEvidence', () => {+ it('offers marking on a video-only check on desktop, where the video stage exists', () => {+ expect(canMarkEvidence(check('video'), true)).toBe(true);+ });++ // The phone reject modal drops videos, so the entry would open an empty stage.+ it('hides marking on a video-only check on a phone', () => {+ expect(canMarkEvidence(check('video'), false)).toBe(false);+ expect(canMarkEvidence(check('video', 'screenshot'), false)).toBe(true);+ });+});diff --git a/src/features/Acceptance/Viewer/Evidence/evidence.ts b/src/features/Acceptance/Viewer/Evidence/evidence.tsindex 6e8d88f5677..18c8be6d1ee 100644--- a/src/features/Acceptance/Viewer/Evidence/evidence.ts+++ b/src/features/Acceptance/Viewer/Evidence/evidence.ts@@ -18,6 +18,24 @@ export const isAnnotatable = (item: AcceptanceEvidence) =>export const hasAnnotatableEvidence = (check: AcceptanceCheck) =>check.evidence.some(isAnnotatable);+/**+ * 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.+ */+export const isRejectable = (item: AcceptanceEvidence) =>+ isAnnotatable(item) || (Boolean(item.fileUrl) && item.type === 'video');++export const hasRejectableEvidence = (check: AcceptanceCheck) => check.evidence.some(isRejectable);++/**+ * Whether the reject modal has anything to mark on this device: phones review+ * images only (the frame-anchored video stage is desktop-only), so a+ * video-only check offers no marking entry there.+ */+export const canMarkEvidence = (check: AcceptanceCheck, desktop: boolean) =>+ desktop ? hasRejectableEvidence(check) : hasAnnotatableEvidence(check);+export const evidenceCounts = (evidence: AcceptanceEvidence[]) => {const counts = { audio: 0, file: 0, image: 0, video: 0 };for (const item of evidence) {diff --git a/src/features/Acceptance/Viewer/ReadOnly/Checks.tsx b/src/features/Acceptance/Viewer/ReadOnly/Checks.tsxindex 1f29871ef16..fc8ac59e375 100644--- a/src/features/Acceptance/Viewer/ReadOnly/Checks.tsx+++ b/src/features/Acceptance/Viewer/ReadOnly/Checks.tsx@@ -24,7 +24,7 @@ import { groupCommentThreads, threadsForCheck } from '../Comments/threads';import { useAcceptanceCommentList } from '../Comments/useAcceptanceCommentList';import { EvidenceList } from '../Evidence/EvidenceList';import type { EvidenceOverlayMap } from '../Evidence/overlay';-import { useAcceptanceBundle } from '../useAcceptanceBundle';+import { useAcceptanceBundle, useEvidenceUrlRefresh } from '../useAcceptanceBundle';import { ReadComment } from './Discussion';const styles = createStaticStyles(({ css }) => ({@@ -70,6 +70,7 @@ const ReadCheck = ({const { t } = useTranslation('verify');const { acceptanceId } = useAcceptanceScope();const { data: discussion } = useAcceptanceCommentList(acceptanceId);+ const refreshEvidenceUrl = useEvidenceUrlRefresh(acceptanceId);const meta = checkHeadMeta(check);const threads = threadsForCheck(groupCommentThreads(discussion?.items ?? []), check.id);const comments = threads.flatMap(({ root, replies }) => [root, ...replies]);@@ -104,7 +105,12 @@ const ReadCheck = ({<Text style={{ whiteSpace: 'pre-wrap' }}>{check.result.toulmin.evidence}</Text>)}{visualization && <VisualizationRenderer manifest={visualization} />}- <EvidenceList evidence={check.evidence} overlays={overlays} />+ <EvidenceList+ evidence={check.evidence}+ overlays={overlays}+ reviewNotes={activeReview?.action === 'reject' ? activeReview.annotations : undefined}+ onRefreshEvidenceUrl={refreshEvidenceUrl}+ />{check.state === 'not_executed' ? (<Text fontSize={12} type={'secondary'}>{t('acceptance.focus.verifierDescription.notExecuted')}diff --git a/src/features/Acceptance/Viewer/Review/CheckRejectModal.tsx b/src/features/Acceptance/Viewer/Review/CheckRejectModal.tsxindex 23df460f7a0..8d7381b1bfa 100644--- a/src/features/Acceptance/Viewer/Review/CheckRejectModal.tsx+++ b/src/features/Acceptance/Viewer/Review/CheckRejectModal.tsx@@ -28,7 +28,17 @@ interface CheckRejectModalProps extends RejectReviewInput {export const CheckRejectModalContent = memo<CheckRejectModalProps>(({ checkDescription: _checkDescription, checkTitle: _checkTitle, ...input }) => {const { md = true } = useResponsive();- const model = useRejectReview(input);+ // Frame-anchored notes need the desktop stage (keys, a timeline wide+ // enough to scrub); on a phone the video still plays inline in the row.+ const model = useRejectReview(+ md+ ? input+ : {+ ...input,+ evidence: input.evidence.filter((item) => item.type !== 'video'),+ keptEvidence: input.evidence.filter((item) => item.type === 'video'),+ },+ );return md ? <DesktopEvidenceReview model={model} /> : <MobileEvidenceReview model={model} />;},diff --git a/src/features/Acceptance/Viewer/Review/rejectDraft.test.ts b/src/features/Acceptance/Viewer/Review/rejectDraft.test.tsindex b8c870231e1..cf08d6b8b1c 100644--- a/src/features/Acceptance/Viewer/Review/rejectDraft.test.ts+++ b/src/features/Acceptance/Viewer/Review/rejectDraft.test.ts@@ -1,27 +1,50 @@import { describe, expect, it } from 'vitest';-import { clampZoom, nextZoom, ZOOM_STEPS } from './rejectDraft';+import { restoreDraftAnnotations, serializeReviewAnnotations } from './rejectDraft';-describe('nextZoom', () => {- it('steps one notch from a notch and stops at both ends', () => {- expect(nextZoom(1, 1)).toBe(1.5);- expect(nextZoom(1, -1)).toBe(0.75);- expect(nextZoom(ZOOM_STEPS.at(-1)!, 1)).toBe(ZOOM_STEPS.at(-1));- expect(nextZoom(ZOOM_STEPS[0], -1)).toBe(ZOOM_STEPS[0]);- });+const rect = { height: 0.2, width: 0.3, x: 0.1, y: 0.1 };+const whole = { height: 1, width: 1, x: 0, y: 0 };++describe('reject draft annotations', () => {+ it('keeps the frame, the span and the disputed claim of a video note through a round trip', () => {+ const evidence = [{ fileUrl: 'clip.mp4', id: 'video', type: 'video' }];+ const disputes = { kind: 'check' as const, note: 'no skeleton', t: 7.9 };+ const restored = restoreDraftAnnotations(+ [+ { comment: 'skeleton', evidenceId: 'video', rect, time: { start: 7.2 } },+ { evidenceId: 'video', rect: whole, time: { end: 7.6, start: 6.8 } },+ {+ comment: 'flashed earlier',+ disputes,+ evidenceId: 'video',+ rect: whole,+ time: { start: 7.9 },+ },+ ],+ evidence,+ );- it('lands on the next notch in that direction from between two notches (after a pinch)', () => {- expect(nextZoom(1.23, 1)).toBe(1.5);- expect(nextZoom(1.23, -1)).toBe(1);- expect(nextZoom(2.7, 1)).toBe(3);- expect(nextZoom(2.7, -1)).toBe(2);+ expect(serializeReviewAnnotations(restored)).toEqual([+ { comment: 'skeleton', evidenceId: 'video', rect, time: { start: 7.2 } },+ { comment: undefined, evidenceId: 'video', rect: whole, time: { end: 7.6, start: 6.8 } },+ {+ comment: 'flashed earlier',+ disputes,+ evidenceId: 'video',+ rect: whole,+ time: { start: 7.9 },+ },+ ]);});-});-describe('clampZoom', () => {- it('keeps a pinched value inside the range the buttons can reach', () => {- expect(clampZoom(0.1)).toBe(ZOOM_STEPS[0]);- expect(clampZoom(9)).toBe(ZOOM_STEPS.at(-1));- expect(clampZoom(1.7)).toBe(1.7);+ it('leaves an image note without a time key', () => {+ const [serialized] = serializeReviewAnnotations(+ restoreDraftAnnotations(+ [{ comment: ' faint ', evidenceId: 'shot', rect }],+ [{ fileUrl: 'a.png', id: 'shot' }],+ ),+ );+ expect(serialized).toEqual({ comment: 'faint', evidenceId: 'shot', rect });+ expect('time' in serialized).toBe(false);});});diff --git a/src/features/Acceptance/Viewer/Review/rejectDraft.ts b/src/features/Acceptance/Viewer/Review/rejectDraft.tsindex 2e3cda4b296..6386d7d003c 100644--- a/src/features/Acceptance/Viewer/Review/rejectDraft.ts+++ b/src/features/Acceptance/Viewer/Review/rejectDraft.ts@@ -1,20 +1,26 @@-import type { AcceptanceReviewAnnotation } from '@lobechat/types';+import type { AcceptanceReviewAnnotation, VerifyEvidenceChapter } from '@lobechat/types';import type { PendingAttachment } from '../Evidence/attachments';-/** One annotatable evidence image (already filtered to visual, file-backed). */+/** One annotatable evidence image or video (already filtered to visual, file-backed). */export interface RejectableEvidence {+ /** Video only: the agent's markers, so the reviewer can dispute a claim in place. */+ chapters?: VerifyEvidenceChapter[];fileUrl: string;id: string;+ /** `video` switches the stage to the player; anything else is an image. */+ type?: string;}export interface DraftAnnotationEntry {comment: string;+ disputes?: AcceptanceReviewAnnotation['disputes'];evidenceId: string;/** Stable identity — rapid move/resize updates must never key off objectidentity, which a stale render closure invalidates mid-gesture. */key: number;rect: AcceptanceReviewAnnotation['rect'];+ time?: AcceptanceReviewAnnotation['time'];}/** What survives a refresh — typed feedback is too costly to lose to one F5. */@@ -31,10 +37,12 @@ export const nextAnnotationKey = () => ++draftAnnotationSeq;export const serializeReviewAnnotations = (annotations: DraftAnnotationEntry[],): AcceptanceReviewAnnotation[] =>- annotations.map(({ comment, evidenceId, rect }) => ({+ annotations.map(({ comment, disputes, evidenceId, rect, time }) => ({comment: comment.trim() || undefined,+ ...(disputes ? { disputes } : {}),evidenceId,rect,+ ...(time ? { time } : {}),}));/**@@ -52,9 +60,11 @@ export const restoreDraftAnnotations = (.filter((entry) => evidence.some((item) => item.id === entry.evidenceId)).map((entry) => ({comment: entry.comment ?? '',+ disputes: entry.disputes,evidenceId: entry.evidenceId,key: nextAnnotationKey(),rect: entry.rect,+ time: entry.time,}));const draftStorageKey = (key: string) => `acceptance-reject-draft:${key}`;diff --git a/src/features/Acceptance/Viewer/Review/useRejectReview.test.ts b/src/features/Acceptance/Viewer/Review/useRejectReview.test.tsnew file mode 100644index 00000000000..7bdaac207f9--- /dev/null+++ b/src/features/Acceptance/Viewer/Review/useRejectReview.test.ts@@ -0,0 +1,57 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useRejectReview } from './useRejectReview';++vi.mock('@lobehub/ui/base-ui', () => ({+ useModalContext: () => ({ close: vi.fn(), setCanDismissByClickOutside: vi.fn() }),+}));++vi.mock('../Evidence/attachments', () => ({+ useFeedbackAttachments: () => ({+ attachments: [],+ fileIds: [],+ handlePaste: vi.fn(),+ remove: vi.fn(),+ uploadFiles: vi.fn(),+ uploading: false,+ }),+}));++const rect = { height: 0.2, width: 0.3, x: 0.1, y: 0.1 };+const image = { fileUrl: 'shot.png', id: 'shot' };+const video = { fileUrl: 'clip.mp4', id: 'clip', type: 'video' };+const imageNote = { comment: 'faint', evidenceId: 'shot', rect };+const videoNote = { comment: 'skeleton', evidenceId: 'clip', rect, time: { start: 7.2 } };++describe('useRejectReview', () => {+ // A reject replaces the whole decision detail: a layout that cannot edit+ // videos (the phone) must still send their notes back, or they are deleted.+ it('submits notes on evidence it cannot edit, and shows only the editable ones', async () => {+ const onConfirm = vi.fn(async () => true);+ const { result } = renderHook(() =>+ useRejectReview({+ evidence: [image],+ keptEvidence: [video],+ onConfirm,+ previousAnnotations: [imageNote, videoNote],+ previousComment: 'see notes',+ }),+ );++ expect(result.current.editableAnnotations.map((note) => note.evidenceId)).toEqual(['shot']);++ await act(async () => {+ await result.current.submitReject();+ });++ expect(onConfirm).toHaveBeenCalledWith(+ expect.objectContaining({+ annotations: [+ { comment: 'faint', evidenceId: 'shot', rect },+ { comment: 'skeleton', evidenceId: 'clip', rect, time: { start: 7.2 } },+ ],+ }),+ );+ });+});diff --git a/src/features/Acceptance/Viewer/Review/useRejectReview.ts b/src/features/Acceptance/Viewer/Review/useRejectReview.tsindex 96fedea03c8..d5a3f0c992d 100644--- a/src/features/Acceptance/Viewer/Review/useRejectReview.ts+++ b/src/features/Acceptance/Viewer/Review/useRejectReview.ts@@ -1,5 +1,6 @@'use client';+import { FULL_FRAME_RECT } from '@lobechat/const/verify';import type { AcceptanceReviewAnnotation } from '@lobechat/types';import { useModalContext } from '@lobehub/ui/base-ui';import { useEffect, useState } from 'react';@@ -38,6 +39,12 @@ export interface RejectReviewInput {/** Feedback already typed in the focused detail before opening annotation. */initialComment?: string;initialEvidenceId?: string;+ /**+ * Evidence this layout cannot edit (videos on a phone). Its annotations are+ * restored and submitted untouched — a reject replaces the whole decision+ * detail, so dropping them here would silently delete that feedback.+ */+ keptEvidence?: RejectableEvidence[];/** Perform the reject; resolve true to close, false to stay open. */onConfirm: (value: {annotations: AcceptanceReviewAnnotation[];@@ -47,6 +54,8 @@ export interface RejectReviewInput {previousAnnotations?: AcceptanceReviewAnnotation[];previousAttachments?: PendingAttachment[];previousComment?: string;+ /** A freshly signed URL for one evidence, for recovering an expired video. */+ refreshEvidenceUrl?: (evidenceId: string) => Promise<string | undefined>;}/**@@ -63,10 +72,12 @@ export const useRejectReview = ({initialAnnotations,initialComment,initialEvidenceId,+ keptEvidence = [],onConfirm,previousAnnotations,previousAttachments,previousComment,+ refreshEvidenceUrl,}: RejectReviewInput) => {const { close, setCanDismissByClickOutside } = useModalContext();const [draft] = useState(() => readDraft(draftKey));@@ -91,10 +102,12 @@ export const useRejectReview = ({initialAnnotations?.length? initialAnnotations: (draft?.annotations ?? previousAnnotations ?? []),- evidence,+ [...evidence, ...keptEvidence],),);const [zoom, setZoom] = useState(1);+ /** The video note being written — its frame is highlighted on the timeline. */+ const [activeNoteKey, setActiveNoteKey] = useState<number>();// Your own screenshots (paste or upload) — attached to the reject alongside// the note and any circled regions.@@ -112,6 +125,10 @@ export const useRejectReview = ({const activeIndex = evidence.findIndex((item) => item.id === activeEvidenceId);const activeEvidence = evidence.find((item) => item.id === activeEvidenceId);const activeAnnotations = annotations.filter((item) => item.evidenceId === activeEvidenceId);+ /** The notes this layout can show and edit; kept ones ride along unseen. */+ const editableAnnotations = annotations.filter((item) =>+ evidence.some((entry) => entry.id === item.evidenceId),+ );const selectEvidence = (index: number) => {if (!evidence[index]) return;@@ -137,6 +154,8 @@ export const useRejectReview = ({close,comment,drawing: step === 'draw',+ editableAnnotations,+ refreshEvidenceUrl,evidence,failed,hasEvidence: evidence.length > 0,@@ -167,6 +186,32 @@ export const useRejectReview = ({},},+ activeNoteKey,+ /**+ * A note on the active video: a region on one frame, a whole frame, or a+ * span. A note without a region covers the whole frame. Returns its key so+ * the stage can focus the note that was just made.+ */+ addVideoNote: (note: {+ disputes?: AcceptanceReviewAnnotation['disputes'];+ rect?: AcceptanceReviewAnnotation['rect'];+ time: NonNullable<AcceptanceReviewAnnotation['time']>;+ }) => {+ const key = nextAnnotationKey();+ setAnnotations((previous) => [+ ...previous,+ {+ comment: '',+ disputes: note.disputes,+ evidenceId: activeEvidence!.id,+ key,+ rect: note.rect ?? { ...FULL_FRAME_RECT },+ time: note.time,+ },+ ]);+ setActiveNoteKey(key);+ return key;+ },editAnnotation: (key: number, value: string) =>setAnnotations((previous) =>previous.map((item) => (item.key === key ? { ...item, comment: value } : item)),@@ -176,6 +221,7 @@ export const useRejectReview = ({selectEvidence(evidence.findIndex((item) => item.id === evidenceId));advance('edit-region');},+ setActiveNoteKey,removeAnnotation: (key: number) =>setAnnotations((previous) => previous.filter((item) => item.key !== key)),removeAttachment: remove,diff --git a/src/features/Acceptance/Viewer/evidenceUrlRefresh.test.ts b/src/features/Acceptance/Viewer/evidenceUrlRefresh.test.tsnew file mode 100644index 00000000000..8ff4902dacf--- /dev/null+++ b/src/features/Acceptance/Viewer/evidenceUrlRefresh.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { findEvidenceFileUrl } from './useAcceptanceBundle';++const bundle = {+ checks: [+ {+ evidence: [{ fileUrl: 'https://s3/current.mp4?sig=new', id: 'current' }],+ timeline: [{ evidence: [{ fileUrl: 'https://s3/older.mp4?sig=new', id: 'older' }] }],+ },+ ],+} as unknown as Parameters<typeof findEvidenceFileUrl>[0];++describe('findEvidenceFileUrl', () => {+ it('finds the re-signed link of an evidence in the check or its history', () => {+ expect(findEvidenceFileUrl(bundle, 'current')).toBe('https://s3/current.mp4?sig=new');+ expect(findEvidenceFileUrl(bundle, 'older')).toBe('https://s3/older.mp4?sig=new');+ });++ it('has nothing to offer for evidence that is gone', () => {+ expect(findEvidenceFileUrl(bundle, 'deleted')).toBeUndefined();+ expect(findEvidenceFileUrl(undefined, 'current')).toBeUndefined();+ });+});diff --git a/src/features/Acceptance/Viewer/useAcceptanceBundle.ts b/src/features/Acceptance/Viewer/useAcceptanceBundle.tsindex d8ff2c1adea..1d5289c16a3 100644--- a/src/features/Acceptance/Viewer/useAcceptanceBundle.ts+++ b/src/features/Acceptance/Viewer/useAcceptanceBundle.ts@@ -27,3 +27,30 @@ export const useAcceptanceBundle = (acceptanceId: string | null) => {return swr;};++type AcceptanceBundleData = Awaited<ReturnType<typeof verifyService.getAcceptanceBundle>>;++/** An evidence's current file URL, wherever in the bundle (a check or its history) it sits. */+export const findEvidenceFileUrl = (+ bundle: AcceptanceBundleData | undefined,+ evidenceId: string,+) => {+ for (const check of bundle?.checks ?? []) {+ const item =+ check.evidence.find((entry) => entry.id === evidenceId) ??+ check.timeline.flatMap((step) => step.evidence).find((entry) => entry.id === evidenceId);+ if (item) return item.fileUrl ?? undefined;+ }+ return undefined;+};++/**+ * Re-read the bundle to get a freshly signed URL for one evidence. Stored files+ * are served through signed links that expire; a page left open past that+ * cannot recover a failed video by retrying the same link.+ */+export const useEvidenceUrlRefresh = (acceptanceId: string | null | undefined) => {+ const { mutate } = useAcceptanceBundle(acceptanceId ?? null);+ if (!acceptanceId) return undefined;+ return async (evidenceId: string) => findEvidenceFileUrl(await mutate(), evidenceId);+};