🤯 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): add review API v2 for the embeddable review toolbar (#20900)
Inneid4602590d766
diff --git a/.agents/skills/acceptance/SKILL.md b/.agents/skills/acceptance/SKILL.mdindex 2c635df718b..5f25f6be24b 100644--- a/.agents/skills/acceptance/SKILL.md+++ b/.agents/skills/acceptance/SKILL.md@@ -443,6 +443,15 @@ or a `storage_block:` error. Do not stop at "upload failed" or "noted in the PR"verdicts; read back coverage and do not claim the delivery is complete whilerequired evidence is missing.+**Record the deployed preview.** When the delivery is deployed somewhere a+reviewer can open (a pull-request preview, a staging URL, a dev server on this+machine), run `lh acceptance preview <acceptanceId> <url>` after the round is+published. The URL must be https, or http on `localhost`/`127.0.0.1`. The+acceptance page then offers "Review on preview", where reviewers comment on the+live page; `lh acceptance feedback` lists those comments with the page URL and+the `file:line` they were pinned to. Skip this when nothing is deployed — never+invent a URL.+The final response for a completed handoff MUST include the published acceptanceURL together with the coverage result — never only a check-result id or a proseclaim. Obtain the links from the path you actually executed:diff --git a/apps/cli/src/commands/acceptanceCommentFeedback.ts b/apps/cli/src/commands/acceptanceCommentFeedback.tsindex 28dbef8b259..e658299aaf3 100644--- a/apps/cli/src/commands/acceptanceCommentFeedback.ts+++ b/apps/cli/src/commands/acceptanceCommentFeedback.ts@@ -28,6 +28,14 @@ export const collectCommentFeedback = (root.evidenceId && root.rect? { comment: item.content, evidenceId: root.evidenceId, rect: root.rect }: undefined;+ const page = root.source+ ? {+ locations: root.source.targets.flatMap((target) =>+ target.code ? [`${target.code.file}:${target.code.line}`] : [],+ ),+ url: root.source.url,+ }+ : undefined;return [{@@ -44,6 +52,7 @@ export const collectCommentFeedback = (createdAt: item.createdAt.toISOString(),fileIds: item.attachments.map((attachment) => attachment.id),kind: 'comment' as const,+ page,parentCommentId: item.parentCommentId ?? undefined,roundIndex: item.contextRoundIndex ?? root.contextRoundIndex ?? 0,threadId: root.id,diff --git a/apps/cli/src/commands/acceptanceFeedback.test.ts b/apps/cli/src/commands/acceptanceFeedback.test.tsindex 7b3a28e9400..f78ac12846e 100644--- a/apps/cli/src/commands/acceptanceFeedback.test.ts+++ b/apps/cli/src/commands/acceptanceFeedback.test.ts@@ -5,14 +5,15 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';import type * as Format from '../utils/format';import { registerAcceptanceCommands } from './verifyAcceptance';-const { getBundle, listComments, outputJson } = vi.hoisted(() => ({+const { getBundle, listComments, outputJson, setPreviewUrl } = vi.hoisted(() => ({getBundle: vi.fn(),listComments: vi.fn(),outputJson: vi.fn(),+ setPreviewUrl: vi.fn(),}));vi.mock('../api/client', () => ({getTrpcClient: async () => ({- acceptance: { getBundle: { query: getBundle } },+ acceptance: { getBundle: { query: getBundle }, setPreviewUrl: { mutate: setPreviewUrl } },acceptanceComment: { list: { query: listComments } },}),}));@@ -56,6 +57,7 @@ const comment = (rect,resolvedAt: null,resolvedByUserId: null,+ source: null,updatedAt: new Date('2026-09-22T14:09:00Z'),...overrides,});@@ -264,3 +266,71 @@ it('retains historical rejection notes without treating them or approval notes aexpect.objectContaining({ kind: 'decision', comment: 'Read my comments', actionable: false }),]);});++const pageSource = {+ intent: 'change' as const,+ scroll: { x: 0, y: 0 },+ targets: [+ {+ code: { chain: [], column: 7, file: 'src/Pay.tsx', line: 42 },+ label: 'Pay',+ rect: { height: 40, width: 120, x: 10, y: 20 },+ selector: '#pay',+ },+ { label: 'Total', rect: { height: 20, width: 80, x: 0, y: 0 }, selector: '.total' },+ ],+ url: 'https://pr-12.preview.example.com/checkout',+ v: 1 as const,+ viewport: { dpr: 2, height: 800, width: 1280 },+};+const pageComment = (id: string, overrides: Partial<AcceptanceCommentItem> = {}) =>+ comment(id, {+ anchorType: 'acceptance',+ checkItemId: null,+ evidenceId: null,+ rect: null,+ ...overrides,+ });++it('points product-page comments and their replies at the page and source location', async () => {+ listComments.mockResolvedValue({+ items: [+ pageComment('root', { source: pageSource }),+ pageComment('reply', { parentCommentId: 'root' }),+ ],+ });+ const { entries } = await feedback('--json');+ const page = { locations: ['src/Pay.tsx:42'], url: pageSource.url };+ expect(entries.filter((entry: { kind: string }) => entry.kind === 'comment')).toEqual([+ expect.objectContaining({ commentId: 'root', page }),+ expect.objectContaining({ commentId: 'reply', page }),+ ]);+});++it('prints the page and source location of a product-page comment', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ listComments.mockResolvedValue({ items: [pageComment('root', { source: pageSource })] });+ await feedback();+ const printed = log.mock.calls.map((call) => String(call[0])).join('\n');+ expect(printed).toContain(pageSource.url);+ expect(printed).toContain('src/Pay.tsx:42');+});++it('records where the delivery is deployed for preview review', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ setPreviewUrl.mockResolvedValue({ previewUrl: 'https://pr-12.example.com/', roundIndex: 3 });+ const program = new Command().exitOverride();+ registerAcceptanceCommands(program);+ await program.parseAsync([+ 'node',+ 'lh',+ 'acceptance',+ 'preview',+ 'acceptance-id',+ 'https://pr-12.example.com/',+ ]);+ expect(setPreviewUrl).toHaveBeenCalledWith({+ id: 'acceptance-id',+ url: 'https://pr-12.example.com/',+ });+});diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/verifyAcceptance.tsindex bb4516f6d75..cd79fa6bbf7 100644--- a/apps/cli/src/commands/verifyAcceptance.ts+++ b/apps/cli/src/commands/verifyAcceptance.ts@@ -358,6 +358,7 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecatcreatedAt?: string;fileIds?: string[];kind: 'check' | 'group' | 'flow' | 'comment' | 'decision';+ page?: { locations: string[]; url: string };roundIndex: number;title?: string;}@@ -507,6 +508,11 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat: `group · ${entry.category || 'overall'}`;console.log(`${marker} ${label} ${pc.dim(`(r${entry.roundIndex})`)}`);if (entry.comment) console.log(` ${entry.comment}`);+ if (entry.page) {+ console.log(` ${pc.dim('page:')} ${entry.page.url}`);+ for (const location of entry.page.locations)+ console.log(` ${pc.dim(`└ ${location}`)}`);+ }for (const annotation of entry.annotations ?? []) {if (annotation.comment && annotation.comment !== entry.comment)console.log(` ${pc.dim('region:')} ${annotation.comment}`);@@ -524,6 +530,23 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat},);+ acceptance+ .command('preview <idOrSubject> <url>')+ .description(+ 'Record where the latest round is deployed, so reviewers can comment on the live page (https or a loopback dev server)',+ )+ .option('--json [fields]', 'Output JSON')+ .action(async (idOrSubject: string, url: string, options: { json?: boolean | string }) => {+ const id = await resolveAcceptanceId(idOrSubject);+ const client = await getTrpcClient();+ const result = await client.acceptance.setPreviewUrl.mutate({ id, url });+ if (options.json !== undefined) {+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);+ return;+ }+ console.log(`${pc.green('✓')} r${result.roundIndex} preview: ${result.previewUrl}`);+ });+acceptance.command('link-pr <idOrSubject> <url>').description(diff --git a/apps/server/src/router-hono/acceptance-review/__tests__/app.test.ts b/apps/server/src/router-hono/acceptance-review/__tests__/app.test.tsnew file mode 100644index 00000000000..d5e2903833d--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/__tests__/app.test.ts@@ -0,0 +1,413 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import type { LobeChatDatabase } from '@lobechat/database';+import {+ acceptanceComments,+ acceptances,+ files,+ users,+ verifyRuns,+} from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as ResourceEvents from '@/server/services/resourceEvents';++let serverDB: LobeChatDatabase;++const mocks = vi.hoisted(() => ({+ dispatch: vi.fn(),+ signals: [] as AbortSignal[],+ upload: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: async () => serverDB }));+vi.mock('@/libs/oidc-provider/jwt', () => ({+ verifyAcceptanceReviewJWT: async (token: string) => {+ const [userId, acceptanceId] = token.split('|');+ if (!acceptanceId) throw new Error('invalid');+ return { acceptanceId, expiresAt: 2_000_000_000, userId };+ },+}));+vi.mock('@/server/services/file', () => ({+ FileService: class {+ getFullFileUrl = async (url: string) => `https://cdn.example.com/${url}`;+ uploadFromBuffer = mocks.upload;+ },+}));+vi.mock('@/server/routers/lambda/_helpers/acceptanceRepairDispatch', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ dispatchAcceptanceRepair: mocks.dispatch,+}));+vi.mock('@/server/services/resourceEvents', async (importOriginal) => {+ const actual = await importOriginal<typeof ResourceEvents>();+ return {+ ...actual,+ subscribeResourceEvents: (...args: Parameters<typeof actual.subscribeResourceEvents>) => {+ mocks.signals.push(args[2]);+ return actual.subscribeResourceEvents(...args);+ },+ };+});+vi.mock('@/server/workflows/expertiseRejection', () => ({+ ExpertiseRejectionWorkflow: { trigger: vi.fn() },+}));++const { default: app } = await import('../index');++const BASE = 'http://localhost/api/acceptance-review/v1';+const JPEG = `data:image/jpeg;base64,${Buffer.from('jpeg-bytes').toString('base64')}`;++const anchor = {+ env: { consoleErrors: ['TypeError: x is undefined'], userAgent: 'Chrome' },+ intent: 'comment',+ scroll: { x: 0, y: 0 },+ targets: [{ label: 'Pay', rect: { height: 40, width: 120, x: 10, y: 20 }, selector: '#pay' }],+ url: 'https://preview.example.com/checkout',+ v: 1,+ viewport: { dpr: 2, height: 800, width: 1280 },+};++let ownerId: string;+let visitorId: string;+let acceptanceId: string;+let privateId: string;++const call = (+ userId: string,+ path: string,+ init: RequestInit & { json?: unknown; target?: string } = {},+) => {+ const { json, target = acceptanceId, ...rest } = init;+ return app.request(`${BASE}${path}`, {+ ...rest,+ body: json === undefined ? rest.body : JSON.stringify(json),+ headers: {+ 'authorization': `Bearer ${userId}|${target}`,+ 'content-type': 'application/json',+ 'origin': 'https://preview.example.com',+ ...(rest.headers as Record<string, string>),+ },+ });+};++const post = (userId: string, json: Record<string, unknown>) =>+ call(userId, '/comments', { json: { clientId: randomUUID(), ...json }, method: 'POST' });++beforeEach(async () => {+ serverDB = await getTestDB();+ ownerId = randomUUID();+ visitorId = randomUUID();+ await serverDB.insert(users).values([+ { fullName: 'Olivia Owner', id: ownerId },+ { id: visitorId, username: 'vic' },+ ]);+ const [shared, hidden] = await serverDB+ .insert(acceptances)+ .values([+ {+ metadata: { title: 'Billing redesign' },+ requirement: 'Pay button works',+ status: 'delivered',+ subjectId: randomUUID(),+ subjectType: 'standalone',+ userId: ownerId,+ visibility: 'public',+ },+ {+ subjectId: randomUUID(),+ subjectType: 'standalone',+ userId: ownerId,+ visibility: 'private',+ },+ ])+ .returning();+ acceptanceId = shared.id;+ privateId = hidden.id;+ await serverDB.insert(verifyRuns).values([+ { acceptanceId, roundIndex: 1, userId: ownerId },+ {+ acceptanceId,+ metadata: { previewUrl: 'https://preview.example.com/' },+ roundIndex: 2,+ userId: ownerId,+ },+ ]);+ mocks.upload.mockImplementation(async (buffer: Buffer, mimeType: string, pathname: string) => {+ const [file] = await serverDB+ .insert(files)+ .values({+ fileType: mimeType,+ name: 'shot',+ size: buffer.length,+ url: pathname,+ userId: visitorId,+ })+ .returning();+ return { fileId: file.id, key: pathname, url: pathname };+ });+ mocks.dispatch.mockResolvedValue({ dispatched: false, reason: 'no_origin' });+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, ownerId));+ await serverDB.delete(users).where(eq(users.id, visitorId));+ vi.clearAllMocks();+});++describe('auth', () => {+ it('refuses a request without a review token', async () => {+ const res = await app.request(`${BASE}/session`);+ expect(res.status).toBe(401);+ expect(await res.json()).toMatchObject({ error: { code: 'UNAUTHORIZED' } });+ });++ it('refuses a token that does not verify', async () => {+ const res = await app.request(`${BASE}/session`, { headers: { authorization: 'Bearer junk' } });+ expect(res.status).toBe(401);+ });++ it('hides an acceptance the user can no longer read', async () => {+ const res = await call(visitorId, '/session', { target: privateId });+ expect(res.status).toBe(404);+ });++ it('answers a preflight from any preview origin', async () => {+ const res = await app.request(`${BASE}/comments`, {+ headers: {+ 'access-control-request-method': 'POST',+ 'origin': 'https://preview.example.com',+ },+ method: 'OPTIONS',+ });+ expect(res.headers.get('access-control-allow-origin')).toBe('https://preview.example.com');+ });+});++describe('GET /session', () => {+ it('describes the acceptance, the latest round and what the owner may do', async () => {+ const res = await call(ownerId, '/session');+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body).toMatchObject({+ acceptance: {+ id: acceptanceId,+ previewUrl: 'https://preview.example.com/',+ requirement: 'Pay button works',+ round: 2,+ status: 'delivered',+ title: 'Billing redesign',+ },+ can: { comment: true, decide: true, moderate: true },+ expiresAt: new Date(2_000_000_000 * 1000).toISOString(),+ user: { id: ownerId, name: 'Olivia Owner' },+ });+ expect(body.acceptance.url).toMatch(new RegExp(`/acceptance/${acceptanceId}$`));+ });++ it('lets a public-link visitor comment but not decide', async () => {+ const body = await (await call(visitorId, '/session')).json();+ expect(body.can).toEqual({ comment: true, decide: false, moderate: false });+ expect(body.user).toMatchObject({ id: visitorId, name: 'vic' });+ });+});++describe('comments', () => {+ it('creates a pinned remark and lists it with its replies nested', async () => {+ const created = await post(visitorId, { anchor, content: 'overlaps the total' });+ expect(created.status).toBe(201);+ const root = await created.json();+ expect(root).toMatchObject({+ anchor,+ author: { id: visitorId, name: 'vic' },+ content: 'overlaps the total',+ mine: true,+ parentId: null,+ replies: [],+ resolvedAt: null,+ round: 2,+ screenshot: null,+ });++ await post(ownerId, { content: 'on it', parentId: root.id });+ const { items: list } = await (await call(visitorId, '/comments')).json();+ expect(list).toHaveLength(1);+ expect(list[0].replies).toMatchObject([{ content: 'on it', mine: false, parentId: root.id }]);+ });++ it('answers a retried clientId with the remark that already landed', async () => {+ const clientId = randomUUID();+ const first = await (await post(visitorId, { clientId, content: 'once' })).json();+ const again = await (await post(visitorId, { clientId, content: 'once' })).json();+ expect(again.id).toBe(first.id);+ });++ it('keeps the reporter environment from readers who are not moderators', async () => {+ await post(visitorId, { anchor, content: 'with env' });+ const stranger = randomUUID();+ await serverDB.insert(users).values({ id: stranger });+ const {+ items: [forStranger],+ } = await (await call(stranger, '/comments')).json();+ const {+ items: [forOwner],+ } = await (await call(ownerId, '/comments')).json();+ await serverDB.delete(users).where(eq(users.id, stranger));+ expect(forStranger.anchor.env).toBeUndefined();+ expect(forOwner.anchor.env).toEqual(anchor.env);+ });++ it('stores a screenshot as an acceptance file', async () => {+ const res = await post(visitorId, { anchor, content: 'see', screenshot: { dataUrl: JPEG } });+ const body = await res.json();+ expect(mocks.upload).toHaveBeenCalledWith(+ Buffer.from('jpeg-bytes'),+ 'image/jpeg',+ expect.stringMatching(/\.jpg$/),+ expect.any(Function),+ expect.objectContaining({ source: 'acceptance' }),+ );+ expect(body.screenshot).toEqual({+ url: expect.stringMatching(/^https:\/\/cdn\.example\.com\//),+ });+ });++ it('keeps the remark when the screenshot cannot be stored', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.upload.mockRejectedValueOnce(new Error('storage down'));+ const res = await post(visitorId, { anchor, content: 'see', screenshot: { dataUrl: JPEG } });+ expect(res.status).toBe(201);+ expect(await res.json()).toMatchObject({ content: 'see', screenshot: null });+ });++ it('rejects malformed input with INVALID_INPUT', async () => {+ const res = await post(visitorId, { content: '' });+ expect(res.status).toBe(400);+ expect(await res.json()).toMatchObject({ error: { code: 'INVALID_INPUT' } });+ });++ it('rejects a body over 2MB with TOO_LARGE', async () => {+ const res = await post(visitorId, { content: 'x'.repeat(2 * 1024 * 1024 + 1) });+ expect(res.status).toBe(413);+ expect(await res.json()).toMatchObject({ error: { code: 'TOO_LARGE' } });+ });++ it('resolves a thread and reports when', async () => {+ const root = await (await post(visitorId, { content: 'fix me' })).json();+ const res = await call(visitorId, `/comments/${root.id}`, {+ json: { resolved: true },+ method: 'PATCH',+ });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ id: root.id, resolvedAt: expect.any(String) });+ });++ it('treats a comment of another acceptance as missing', async () => {+ const [foreign] = await serverDB+ .insert(acceptanceComments)+ .values({ acceptanceId: privateId, authorUserId: ownerId, clientId: 'x', content: 'secret' })+ .returning();+ const res = await call(ownerId, `/comments/${foreign.id}`, {+ json: { resolved: true },+ method: 'PATCH',+ });+ expect(res.status).toBe(404);+ expect((await call(ownerId, `/comments/${foreign.id}`, { method: 'DELETE' })).status).toBe(404);+ });++ it('deletes a remark so it leaves the list', async () => {+ const root = await (await post(visitorId, { content: 'oops' })).json();+ const res = await call(visitorId, `/comments/${root.id}`, { method: 'DELETE' });+ expect(res.status).toBe(204);+ expect(await (await call(visitorId, '/comments')).json()).toEqual({ items: [] });+ });++ it('forbids another reader from deleting a remark', async () => {+ const root = await (await post(ownerId, { content: 'mine' })).json();+ const res = await call(visitorId, `/comments/${root.id}`, { method: 'DELETE' });+ expect(res.status).toBe(403);+ });+});++describe('POST /decision', () => {+ it('forbids a reader who cannot manage the acceptance', async () => {+ const res = await call(visitorId, '/decision', { json: { verdict: 'accept' }, method: 'POST' });+ expect(res.status).toBe(403);+ expect(await res.json()).toMatchObject({ error: { code: 'FORBIDDEN' } });+ });++ it('refuses a verdict while the round is still being verified', async () => {+ await serverDB+ .update(acceptances)+ .set({ status: 'verifying' })+ .where(eq(acceptances.id, acceptanceId));+ const res = await call(ownerId, '/decision', { json: { verdict: 'accept' }, method: 'POST' });+ expect(res.status).toBe(409);+ expect(await res.json()).toMatchObject({ error: { code: 'INVALID_STATE' } });+ });++ it('accepts a delivered round', async () => {+ const res = await call(ownerId, '/decision', {+ json: { note: 'ship it', verdict: 'accept' },+ method: 'POST',+ });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ status: 'accepted' });+ });++ it('sends a round back and says whether the agent was started', async () => {+ const res = await call(ownerId, '/decision', {+ json: { note: 'pay button overlaps', verdict: 'send_back' },+ method: 'POST',+ });+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ dispatched: false, status: 'rejected' });+ });+});++describe('GET /events', () => {+ const open = async (userId: string) => {+ const res = await call(userId, '/events');+ const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();+ let buffer = '';+ const until = async (pattern: RegExp) => {+ while (!pattern.test(buffer)) {+ const { done, value } = await reader.read();+ if (done) throw new Error(`stream closed before ${pattern}`);+ buffer += value;+ }+ };+ return { close: () => reader.cancel(), res, until };+ };++ it('signals comment changes made through the API', async () => {+ const events = await open(visitorId);+ expect(events.res.headers.get('content-type')).toMatch(/text\/event-stream/);+ await events.until(/event: ready/);+ await post(visitorId, { content: 'live' });+ await events.until(/event: acceptance\.commentsChanged/);+ await events.close();+ });++ it('signals a decision as a session change', async () => {+ const events = await open(ownerId);+ await events.until(/event: ready/);+ await call(ownerId, '/decision', { json: { verdict: 'accept' }, method: 'POST' });+ await events.until(/event: acceptance\.sessionChanged/);+ await events.close();+ });++ it('drops the subscription when the reader disconnects', async () => {+ const events = await open(visitorId);+ await events.until(/event: ready/);+ await events.close();+ await vi.waitFor(() => expect(mocks.signals.at(-1)?.aborted).toBe(true));+ });++ it('refuses a reader without access before streaming', async () => {+ const res = await call(visitorId, '/events', { target: privateId });+ expect(res.status).toBe(404);+ });+});diff --git a/apps/server/src/router-hono/acceptance-review/auth.ts b/apps/server/src/router-hono/acceptance-review/auth.tsnew file mode 100644index 00000000000..00a784630b9--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/auth.ts@@ -0,0 +1,42 @@+import type { MiddlewareHandler } from 'hono';++import { getServerDB } from '@/database/core/db-adaptor';+import type { LobeChatDatabase } from '@/database/type';+import { verifyAcceptanceReviewJWT } from '@/libs/oidc-provider/jwt';+import type { ReviewAccess } from '@/server/services/acceptanceReview/access';+import { resolveReviewAccess } from '@/server/services/acceptanceReview/access';++import { reviewError } from './errors';++export interface ReviewEnv {+ Variables: {+ access: ReviewAccess;+ db: LobeChatDatabase;+ expiresAt: number;+ userId: string;+ };+}++export const reviewAuth: MiddlewareHandler<ReviewEnv> = async (c, next) => {+ const token = c.req.header('authorization')?.match(/^Bearer (.+)$/)?.[1];+ if (!token) return reviewError(c, 401, 'UNAUTHORIZED', 'Missing token');++ let claims: Awaited<ReturnType<typeof verifyAcceptanceReviewJWT>>;+ try {+ claims = await verifyAcceptanceReviewJWT(token);+ } catch {+ return reviewError(c, 401, 'UNAUTHORIZED', 'Invalid token');+ }++ // The token outlives a visibility change, so read access is re-checked on+ // every request rather than trusted from consent time.+ const db = await getServerDB();+ const access = await resolveReviewAccess(db, claims.userId, claims.acceptanceId);+ if (!access) return reviewError(c, 404, 'NOT_FOUND', 'Acceptance not found');++ c.set('access', access);+ c.set('db', db);+ c.set('expiresAt', claims.expiresAt ?? 0);+ c.set('userId', claims.userId);+ await next();+};diff --git a/apps/server/src/router-hono/acceptance-review/data.ts b/apps/server/src/router-hono/acceptance-review/data.tsnew file mode 100644index 00000000000..35667364909--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/data.ts@@ -0,0 +1,73 @@+import { randomUUID } from 'node:crypto';++import { FileSource } from '@lobechat/types';+import { desc, eq } from 'drizzle-orm';++import { businessFileUploadCheck } from '@/business/server/lambda-routers/file';+import { AcceptanceCommentModel } from '@/database/models/acceptanceComment';+import { users, verifyRuns } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { FileService } from '@/server/services/file';++export const latestRound = async (db: LobeChatDatabase, acceptanceId: string) => {+ const [run] = await db+ .select({ id: verifyRuns.id, metadata: verifyRuns.metadata, roundIndex: verifyRuns.roundIndex })+ .from(verifyRuns)+ .where(eq(verifyRuns.acceptanceId, acceptanceId))+ .orderBy(desc(verifyRuns.roundIndex))+ .limit(1);+ if (!run) return { previewUrl: undefined, round: 0, runId: undefined };+ const previewUrl = run.metadata?.previewUrl;+ return {+ previewUrl: typeof previewUrl === 'string' ? previewUrl : undefined,+ round: run.roundIndex ?? 0,+ runId: run.id,+ };+};++export const findProfile = async (db: LobeChatDatabase, userId: string) => {+ const [profile] = await db+ .select({ avatar: users.avatar, fullName: users.fullName, username: users.username })+ .from(users)+ .where(eq(users.id, userId))+ .limit(1);+ return profile;+};++export const commentBelongsTo = async (+ db: LobeChatDatabase,+ commentId: string,+ acceptanceId: string,+) => {+ const comment = await new AcceptanceCommentModel(db).findById(commentId);+ return comment?.acceptanceId === acceptanceId;+};++const SCREENSHOT = /^data:image\/(jpeg|webp);base64,(.+)$/;++export const uploadScreenshot = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | null,+ dataUrl: string,+) => {+ const [, format, base64] = dataUrl.match(SCREENSHOT) ?? [];+ const buffer = Buffer.from(base64 ?? '', 'base64');+ const pathname = `acceptance-review/${userId}/${randomUUID()}.${format === 'webp' ? 'webp' : 'jpg'}`;+ const { fileId } = await new FileService(db, userId, workspaceId ?? undefined).uploadFromBuffer(+ buffer,+ `image/${format}`,+ pathname,+ (transaction) =>+ businessFileUploadCheck({+ actualSize: buffer.length,+ inputSize: buffer.length,+ transaction,+ url: pathname,+ userId,+ workspaceId: workspaceId ?? undefined,+ }),+ { source: FileSource.Acceptance, visibility: 'private' },+ );+ return fileId;+};diff --git a/apps/server/src/router-hono/acceptance-review/errors.ts b/apps/server/src/router-hono/acceptance-review/errors.tsnew file mode 100644index 00000000000..8bffb535d38--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/errors.ts@@ -0,0 +1,38 @@+import { TRPCError } from '@trpc/server';+import type { Context } from 'hono';+import type { ContentfulStatusCode } from 'hono/utils/http-status';++export type ReviewErrorCode =+ | 'FORBIDDEN'+ | 'INTERNAL'+ | 'INVALID_INPUT'+ | 'INVALID_STATE'+ | 'NOT_FOUND'+ | 'RATE_LIMITED'+ | 'TOO_LARGE'+ | 'UNAUTHORIZED';++export const reviewError = (+ c: Context,+ status: ContentfulStatusCode,+ code: ReviewErrorCode,+ message: string,+) => c.json({ error: { code, message } }, status);++const TRPC_CODES: Partial<Record<TRPCError['code'], [ContentfulStatusCode, ReviewErrorCode]>> = {+ BAD_REQUEST: [400, 'INVALID_INPUT'],+ CONFLICT: [409, 'INVALID_STATE'],+ FORBIDDEN: [403, 'FORBIDDEN'],+ NOT_FOUND: [404, 'NOT_FOUND'],+ PAYLOAD_TOO_LARGE: [413, 'TOO_LARGE'],+ PRECONDITION_FAILED: [409, 'INVALID_STATE'],+ TOO_MANY_REQUESTS: [429, 'RATE_LIMITED'],+ UNAUTHORIZED: [401, 'UNAUTHORIZED'],+};++export const handleReviewError = (error: Error, c: Context) => {+ const mapped = error instanceof TRPCError ? TRPC_CODES[error.code] : undefined;+ if (mapped) return reviewError(c, mapped[0], mapped[1], error.message);+ console.error('[acceptance-review]', error);+ return reviewError(c, 500, 'INTERNAL', 'Something went wrong');+};diff --git a/apps/server/src/router-hono/acceptance-review/events.ts b/apps/server/src/router-hono/acceptance-review/events.tsnew file mode 100644index 00000000000..ccf8c0f9e55--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/events.ts@@ -0,0 +1,47 @@+import type { Context } from 'hono';+import { streamSSE } from 'hono/streaming';++import { resolveReviewAccess } from '@/server/services/acceptanceReview/access';+import { subscribeResourceEvents } from '@/server/services/resourceEvents';++import type { ReviewEnv } from './auth';++const PING_MS = 25_000;+// Vercel kills the function at 300s; ending first turns that into an ordinary+// reconnect, and the client refetches on every connect anyway.+const MAX_STREAM_MS = 280_000;++export const streamEvents = (c: Context<ReviewEnv>) => {+ const acceptanceId = c.get('access').acceptance.id;+ const db = c.get('db');+ const userId = c.get('userId');++ return streamSSE(c, async (stream) => {+ const ac = new AbortController();+ stream.onAbort(() => ac.abort());+ const send = (event: string) => stream.writeSSE({ data: '{}', event }).catch(() => ac.abort());++ const ping = setInterval(() => {+ resolveReviewAccess(db, userId, acceptanceId).then(+ (access) => (access ? send('ping') : ac.abort()),+ () => ac.abort(),+ );+ }, PING_MS);+ const deadline = setTimeout(() => ac.abort(), MAX_STREAM_MS);++ const subscription = subscribeResourceEvents(+ { id: acceptanceId, type: 'acceptance' },+ (event) => void send(event.type),+ ac.signal,+ ).catch(() => ac.abort());+ await send('ready');++ await new Promise<void>((resolve) => {+ if (ac.signal.aborted) resolve();+ else ac.signal.addEventListener('abort', () => resolve(), { once: true });+ });+ clearInterval(ping);+ clearTimeout(deadline);+ await subscription;+ });+};diff --git a/apps/server/src/router-hono/acceptance-review/handlers.ts b/apps/server/src/router-hono/acceptance-review/handlers.tsnew file mode 100644index 00000000000..e4cc6338496--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/handlers.ts@@ -0,0 +1,148 @@+import { createReviewCommentSchema, reviewDecisionSchema } from '@lobechat/types';+import type { Context } from 'hono';+import { z } from 'zod';++import { appEnv } from '@/envs/app';+import { acceptanceRouter } from '@/server/routers/lambda/acceptance';+import { acceptanceCommentRouter } from '@/server/routers/lambda/acceptanceComment';++import type { ReviewEnv } from './auth';+import { commentBelongsTo, findProfile, latestRound, uploadScreenshot } from './data';+import { reviewError } from './errors';+import { toReviewComment, toReviewThreads } from './mapping';++type ReviewContext = Context<ReviewEnv>;++const callerContext = (c: ReviewContext) => ({ userId: c.get('userId') }) as never;+const commentCaller = (c: ReviewContext) => acceptanceCommentRouter.createCaller(callerContext(c));+const acceptanceCaller = (c: ReviewContext) => acceptanceRouter.createCaller(callerContext(c));++const viewer = (c: ReviewContext) => ({ userId: c.get('userId') });++interface BodySchema<T> {+ safeParse: (+ value: unknown,+ ) => { data: T; success: true } | { error: { issues: { message: string }[] }; success: false };+}++const parseBody = async <T>(+ c: ReviewContext,+ schema: BodySchema<T>,+): Promise<{ data: T; error?: undefined } | { data?: undefined; error: Response }> => {+ const parsed = schema.safeParse(await c.req.json().catch(() => undefined));+ if (parsed.success) return { data: parsed.data };+ return {+ error: reviewError(c, 400, 'INVALID_INPUT', parsed.error.issues[0]?.message ?? 'Invalid input'),+ };+};++export const getSession = async (c: ReviewContext) => {+ const { acceptance, can } = c.get('access');+ const db = c.get('db');+ const userId = c.get('userId');+ const [round, profile] = await Promise.all([+ latestRound(db, acceptance.id),+ findProfile(db, userId),+ ]);+ return c.json({+ acceptance: {+ id: acceptance.id,+ previewUrl: round.previewUrl,+ requirement: acceptance.requirement ?? undefined,+ round: round.round,+ status: acceptance.status,+ title: acceptance.metadata?.title || acceptance.requirement || '',+ url: `${(appEnv.APP_URL ?? '').replace(/\/$/, '')}/acceptance/${acceptance.id}`,+ },+ can,+ expiresAt: new Date(c.get('expiresAt') * 1000).toISOString(),+ user: {+ avatar: profile?.avatar ?? undefined,+ id: userId,+ name: profile?.fullName || profile?.username || '',+ },+ });+};++export const listComments = async (c: ReviewContext) => {+ const { items } = await commentCaller(c).list({ acceptanceId: c.get('access').acceptance.id });+ return c.json({ items: toReviewThreads(items, viewer(c)) });+};++export const createComment = async (c: ReviewContext) => {+ const body = await parseBody(c, createReviewCommentSchema);+ if (body.error) return body.error;+ const input = body.data;+ const { acceptance, can } = c.get('access');+ if (!can.comment) return reviewError(c, 403, 'FORBIDDEN', 'Read-only access');++ const db = c.get('db');+ const { runId } = await latestRound(db, acceptance.id);+ // The remark is what the reviewer came to say; a storage outage or a full+ // quota drops only the picture, and the toolbar tells them so.+ const fileId = input.screenshot+ ? await uploadScreenshot(+ db,+ c.get('userId'),+ acceptance.workspaceId,+ input.screenshot.dataUrl,+ ).catch((error) => {+ console.error('[acceptance-review] screenshot upload failed', error);+ return undefined;+ })+ : undefined;+ const { data } = await commentCaller(c).create({+ acceptanceId: acceptance.id,+ attachments: fileId ? [{ fileId }] : undefined,+ clientId: input.clientId,+ content: input.content,+ contextRunId: runId,+ parentCommentId: input.parentId,+ source: input.anchor,+ });+ return c.json(toReviewComment(data, viewer(c)), 201);+};++const ownComment = async (c: ReviewContext) => {+ const id = c.req.param('id') ?? '';+ const found = await commentBelongsTo(c.get('db'), id, c.get('access').acceptance.id);+ return found ? id : undefined;+};++export const setResolved = async (c: ReviewContext) => {+ const body = await parseBody(c, z.object({ resolved: z.boolean() }));+ if (body.error) return body.error;+ const id = await ownComment(c);+ if (!id) return reviewError(c, 404, 'NOT_FOUND', 'Comment not found');+ const { data } = await commentCaller(c).setResolved({ id, resolved: body.data.resolved });+ return c.json({+ id,+ resolvedAt: data.resolvedAt ? new Date(data.resolvedAt).toISOString() : null,+ });+};++export const deleteComment = async (c: ReviewContext) => {+ const id = await ownComment(c);+ if (!id) return reviewError(c, 404, 'NOT_FOUND', 'Comment not found');+ await commentCaller(c).delete({ id });+ return c.body(null, 204);+};++export const decide = async (c: ReviewContext) => {+ const body = await parseBody(c, reviewDecisionSchema);+ if (body.error) return body.error;+ const { note, verdict } = body.data;+ const { acceptance, can } = c.get('access');+ if (!can.decide) return reviewError(c, 403, 'FORBIDDEN', 'Not allowed to decide this acceptance');++ const open = verdict === 'accept' ? ['delivered'] : ['delivered', 'errored'];+ if (!open.includes(acceptance.status))+ return reviewError(c, 409, 'INVALID_STATE', `The acceptance is ${acceptance.status}`);++ if (verdict === 'accept') {+ const accepted = await acceptanceCaller(c).accept({ comment: note, id: acceptance.id });+ return c.json({ status: accepted.status });+ }+ const rejected = await acceptanceCaller(c).reject({ comment: note, id: acceptance.id });+ return c.json({ dispatched: rejected.repairDispatch.dispatched, status: rejected.status });+};diff --git a/apps/server/src/router-hono/acceptance-review/index.ts b/apps/server/src/router-hono/acceptance-review/index.tsnew file mode 100644index 00000000000..89b01495904--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/index.ts@@ -0,0 +1,52 @@+import { Hono } from 'hono';+import { bodyLimit } from 'hono/body-limit';+import { cors } from 'hono/cors';++import type { ReviewEnv } from './auth';+import { reviewAuth } from './auth';+import { handleReviewError, reviewError } from './errors';+import { streamEvents } from './events';+import {+ createComment,+ decide,+ deleteComment,+ getSession,+ listComments,+ setResolved,+} from './handlers';++const MAX_BODY_BYTES = 2 * 1024 * 1024;++const app = new Hono<ReviewEnv>().basePath('/api/acceptance-review/v1');++// The toolbar runs on arbitrary preview origins and authenticates with a+// bearer token, never cookies, so echoing the origin grants nothing extra.+app.use(+ '*',+ cors({+ allowHeaders: ['Authorization', 'Content-Type'],+ allowMethods: ['GET', 'POST', 'PATCH', 'DELETE'],+ maxAge: 600,+ origin: (origin) => origin,+ }),+);+app.use(+ '*',+ bodyLimit({+ maxSize: MAX_BODY_BYTES,+ onError: (c) => reviewError(c, 413, 'TOO_LARGE', 'Request body is too large'),+ }),+);+app.use('*', reviewAuth);+app.onError(handleReviewError);+app.notFound((c) => reviewError(c, 404, 'NOT_FOUND', 'Not found'));++app.get('/session', getSession);+app.get('/comments', listComments);+app.post('/comments', createComment);+app.patch('/comments/:id', setResolved);+app.delete('/comments/:id', deleteComment);+app.post('/decision', decide);+app.get('/events', streamEvents);++export default app;diff --git a/apps/server/src/router-hono/acceptance-review/mapping.ts b/apps/server/src/router-hono/acceptance-review/mapping.tsnew file mode 100644index 00000000000..c84272656e0--- /dev/null+++ b/apps/server/src/router-hono/acceptance-review/mapping.ts@@ -0,0 +1,46 @@+import type { AcceptanceCommentItem, ReviewComment } from '@lobechat/types';++const MAX_THREADS = 200;++interface Viewer {+ userId: string;+}++export const toReviewComment = (item: AcceptanceCommentItem, viewer: Viewer): ReviewComment => {+ const mine = item.authorUserId === viewer.userId;+ const screenshot = item.attachments[0]?.url;+ return {+ anchor: item.source,+ author: {+ avatar: item.author.avatar ?? undefined,+ id: item.author.id ?? '',+ name: item.author.fullName || item.author.username || '',+ },+ clientId: item.clientId,+ content: item.content,+ createdAt: item.createdAt.toISOString(),+ id: item.id,+ mine,+ parentId: item.parentCommentId,+ replies: [],+ resolvedAt: item.resolvedAt?.toISOString() ?? null,+ round: item.contextRoundIndex,+ screenshot: screenshot ? { url: screenshot } : null,+ };+};++export const toReviewThreads = (items: AcceptanceCommentItem[], viewer: Viewer) => {+ const visible = items.filter((item) => item.kind === 'comment' && !item.deletedAt);+ const replies = new Map<string, ReviewComment[]>();+ for (const item of visible) {+ if (!item.parentCommentId) continue;+ const thread = replies.get(item.parentCommentId) ?? [];+ thread.push(toReviewComment(item, viewer));+ replies.set(item.parentCommentId, thread);+ }+ return visible+ .filter((item) => !item.parentCommentId)+ .slice(-MAX_THREADS)+ .reverse()+ .map((root) => ({ ...toReviewComment(root, viewer), replies: replies.get(root.id) ?? [] }));+};diff --git a/apps/server/src/router-hono/index.ts b/apps/server/src/router-hono/index.tsindex 69b1dfef1a9..3f123619e73 100644--- a/apps/server/src/router-hono/index.ts+++ b/apps/server/src/router-hono/index.ts@@ -1,6 +1,8 @@import type { Context } from 'hono';import { Hono } from 'hono';+import acceptanceReview from './acceptance-review';+const app = new Hono();const fetchWith = async (@@ -19,6 +21,7 @@ app.get('/health', (c) =>app.all('/api/agent', (c) => fetchWith(c, () => import('./agent')));app.all('/api/agent/*', (c) => fetchWith(c, () => import('./agent')));+app.all('/api/acceptance-review/*', (c) => acceptanceReview.fetch(c.req.raw));app.all('/api/workflows', (c) => fetchWith(c, () => import('./workflows')));app.all('/api/workflows/*', (c) => fetchWith(c, () => import('./workflows')));diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.previewUrl.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.previewUrl.test.tsnew file mode 100644index 00000000000..2f7b7f0b77e--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/acceptance.previewUrl.test.ts@@ -0,0 +1,93 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import { acceptances, verifyRuns } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { acceptanceRouter } from '../acceptance';+import { createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++describe('acceptanceRouter.setPreviewUrl', () => {+ let ownerId: string;+ let acceptanceId: string;+ let latestRunId: string;+ let firstRunId: string;++ beforeEach(async () => {+ testDB = await getTestDB();+ ownerId = await createTestUser(testDB);+ const [row] = await testDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: ownerId })+ .returning();+ acceptanceId = row.id;+ const [first, latest] = await testDB+ .insert(verifyRuns)+ .values([+ { acceptanceId, roundIndex: 1, userId: ownerId },+ { acceptanceId, metadata: { note: 'kept' }, roundIndex: 2, userId: ownerId },+ ])+ .returning();+ firstRunId = first.id;+ latestRunId = latest.id;+ });++ const caller = (userId = ownerId) =>+ acceptanceRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ const metadataOf = async (id: string) =>+ (await testDB.query.verifyRuns.findFirst({ where: eq(verifyRuns.id, id) }))?.metadata;++ it('records the preview on the latest round and keeps its other metadata', async () => {+ await caller().setPreviewUrl({ id: acceptanceId, url: 'https://pr-12.preview.example.com/' });++ expect(await metadataOf(latestRunId)).toEqual({+ note: 'kept',+ previewUrl: 'https://pr-12.preview.example.com/',+ });+ expect(await metadataOf(firstRunId)).toBeNull();+ });++ it('accepts a loopback dev server', async () => {+ await caller().setPreviewUrl({ id: acceptanceId, url: 'http://localhost:5173/app' });+ await caller().setPreviewUrl({ id: acceptanceId, url: 'http://127.0.0.1:3000/' });++ expect((await metadataOf(latestRunId))?.previewUrl).toBe('http://127.0.0.1:3000/');+ });++ it('refuses plain http on a public host and non-web schemes', async () => {+ for (const url of [+ 'http://preview.example.com/',+ 'javascript:alert(1)',+ 'ftp://x.example.com/',+ ])+ await expect(caller().setPreviewUrl({ id: acceptanceId, url })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it('hides the acceptance from someone who cannot manage it', async () => {+ const stranger = await createTestUser(testDB);+ await expect(+ caller(stranger).setPreviewUrl({ id: acceptanceId, url: 'https://x.example.com/' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('needs a round to attach the preview to', async () => {+ const [empty] = await testDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: ownerId })+ .returning();+ await expect(+ caller().setPreviewUrl({ id: empty.id, url: 'https://x.example.com/' }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/acceptanceComment.source.test.ts b/apps/server/src/routers/lambda/__tests__/acceptanceComment.source.test.tsnew file mode 100644index 00000000000..9c99690bf54--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/acceptanceComment.source.test.ts@@ -0,0 +1,100 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import { acceptances } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { acceptanceCommentRouter } from '../acceptanceComment';+import { cleanupTestUser, createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));++const source = {+ intent: 'comment' as const,+ scroll: { x: 0, y: 120 },+ targets: [{ label: 'Pay', rect: { height: 40, width: 120, x: 10, y: 20 }, selector: '#pay' }],+ url: 'https://preview.example.com/checkout',+ v: 1 as const,+ viewport: { dpr: 2, height: 800, width: 1280 },+};++describe('acceptanceCommentRouter product-page source', () => {+ let serverDB: LobeChatDatabase;+ let ownerId: string;+ let acceptanceId: string;++ beforeEach(async () => {+ serverDB = await getTestDB();+ testDB = serverDB;+ ownerId = await createTestUser(serverDB);+ const [row] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: ownerId })+ .returning();+ acceptanceId = row.id;+ });++ afterEach(async () => {+ await cleanupTestUser(serverDB, ownerId);+ vi.clearAllMocks();+ });++ const caller = (userId = ownerId) =>+ acceptanceCommentRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ it('stores the page anchor on a thread root and returns it on list', async () => {+ const { data } = await caller().create({+ acceptanceId,+ clientId: `c-${randomUUID()}`,+ content: 'button overlaps the total',+ source,+ });+ expect(data.source).toEqual(source);++ const { items } = await caller().list({ acceptanceId });+ expect(items.find((item) => item.id === data.id)?.source).toEqual(source);+ });++ it('refuses a source on a reply', async () => {+ const { data: root } = await caller().create({+ acceptanceId,+ clientId: `c-${randomUUID()}`,+ content: 'root',+ });+ await expect(+ caller().create({+ acceptanceId,+ clientId: `c-${randomUUID()}`,+ content: 'reply',+ parentCommentId: root.id,+ source,+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('shows the reporter environment only to its author and moderators', async () => {+ const env = { consoleErrors: ['GET /api?token=secret 500'], userAgent: 'Chrome' };+ const reader = await createTestUser(serverDB);+ await caller(reader).create({+ acceptanceId,+ clientId: `c-${randomUUID()}`,+ content: 'diagnostics attached',+ source: { ...source, env },+ });++ const anonymous = acceptanceCommentRouter.createCaller({ userId: null } as any);+ const [forAnonymous] = (await anonymous.list({ acceptanceId })).items;+ const [forOwner] = (await caller().list({ acceptanceId })).items;+ const [forAuthor] = (await caller(reader).list({ acceptanceId })).items;+ await cleanupTestUser(serverDB, reader);++ expect(forAnonymous.source?.env).toBeUndefined();+ expect(forOwner.source?.env).toEqual(env);+ expect(forAuthor.source?.env).toEqual(env);+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/acceptancePreviewUrl.ts b/apps/server/src/routers/lambda/_helpers/acceptancePreviewUrl.tsnew file mode 100644index 00000000000..56106735ce1--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/acceptancePreviewUrl.ts@@ -0,0 +1,40 @@+import { desc, eq, sql } from 'drizzle-orm';+import { z } from 'zod';++import { verifyRuns } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++const LOOPBACK_HOSTS = new Set(['127.0.0.1', '[::1]', 'localhost']);++const isPreviewUrl = (value: string) => {+ try {+ const url = new URL(value);+ return (+ url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))+ );+ } catch {+ return false;+ }+};++export const previewUrlSchema = z+ .string()+ .max(2000)+ .refine(isPreviewUrl, 'Preview URL must be https, or http on a loopback address');++export const recordPreviewUrl = async (db: LobeChatDatabase, acceptanceId: string, url: string) => {+ const [run] = await db+ .select({ id: verifyRuns.id, roundIndex: verifyRuns.roundIndex })+ .from(verifyRuns)+ .where(eq(verifyRuns.acceptanceId, acceptanceId))+ .orderBy(desc(verifyRuns.roundIndex))+ .limit(1);+ if (!run) return null;+ await db+ .update(verifyRuns)+ .set({+ metadata: sql`coalesce(${verifyRuns.metadata}, '{}'::jsonb) || ${JSON.stringify({ previewUrl: url })}::jsonb`,+ })+ .where(eq(verifyRuns.id, run.id));+ return run;+};diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.ts b/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.tsindex ab2782efdc7..495fd015e17 100644--- a/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.ts+++ b/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.ts@@ -6,6 +6,7 @@ import { GoalModel } from '@/database/models/goal';import { TopicModel } from '@/database/models/topic';import type { AcceptanceItem } from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';import { GoalService } from '@/server/services/goal';import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';import type { AcceptanceService } from '@/server/services/verify';@@ -130,6 +131,7 @@ export const dispatchAcceptanceRepair = async (// aggregate converges when the repair round lands.try {await service.acceptanceModel.updateStatus(acceptance.id, 'repairing');+ notifyAcceptance(acceptance.id, 'session');} catch (error) {console.error('[acceptance] marking %s repairing failed: %O', acceptance.id, error);}diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex cb25a9dc5d9..50573a0a6e5 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -31,6 +31,7 @@ import type { LobeChatDatabase } from '@/database/type';import { isUuid } from '@/database/utils/uuid';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';import { FileService } from '@/server/services/file';import { GoalBriefService } from '@/server/services/goal/goalBriefs';import { parseChangeRequestUrl } from '@/server/services/scm/changeRequestUrl';@@ -56,6 +57,7 @@ import {} from '@/server/services/verify/acceptancePullRequests';import { after } from '@/server/utils/scheduleAfterResponse';+import { previewUrlSchema, recordPreviewUrl } from './_helpers/acceptancePreviewUrl';import {type AcceptanceRepairDispatch,dispatchAcceptanceRepair,@@ -287,6 +289,7 @@ const applyAcceptanceStatus = async (if (status === 'closed') {await service.acceptanceModel.updateStatus(acceptance.id, 'closed');+ notifyAcceptance(acceptance.id, 'session');await settleGoalSignOff(db, acceptance, 'closed');return;}@@ -311,6 +314,7 @@ const applyAcceptanceStatus = async (}await service.acceptanceModel.updateStatus(acceptance.id, 'delivered');+ notifyAcceptance(acceptance.id, 'session');};export const acceptanceRouter = router({@@ -1336,7 +1340,8 @@ export const acceptanceRouter = router({message: `Only a settled acceptance can be sent back (status: ${acceptance.status})`,});}- return service.acceptanceModel.updateStatus(acceptance.id, 'repairing');+ await service.acceptanceModel.updateStatus(acceptance.id, 'repairing');+ notifyAcceptance(acceptance.id, 'session', ctx.userId);}),/**@@ -1415,6 +1420,20 @@ export const acceptanceRouter = router({* project the caller can see — the same set the list already groups by — so* a workspace member is not blocked from filing under a teammate's project.*/+ setPreviewUrl: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), url: previewUrlSchema }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ const run = await recordPreviewUrl(ctx.serverDB, acceptance.id, input.url);+ if (run) notifyAcceptance(acceptance.id, 'session', ctx.userId);+ if (!run)+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'The acceptance has no round to attach a preview to yet',+ });+ return { previewUrl: input.url, roundIndex: run.roundIndex };+ }),+setProject: acceptanceWriteProcedure.input(z.object({ id: z.string(), projectId: z.string().nullable() })).mutation(async ({ ctx, input }) => {diff --git a/apps/server/src/routers/lambda/acceptanceComment.ts b/apps/server/src/routers/lambda/acceptanceComment.tsindex db6d876e5da..06ba43413e6 100644--- a/apps/server/src/routers/lambda/acceptanceComment.ts+++ b/apps/server/src/routers/lambda/acceptanceComment.ts@@ -5,6 +5,7 @@ import type {AcceptanceCommentList,AcceptanceCommentReaction,} from '@lobechat/types';+import { reviewAnchorSchema } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { and, eq, inArray, isNull } from 'drizzle-orm';import { z } from 'zod';@@ -29,6 +30,7 @@ import type { LobeChatDatabase } from '@/database/type';import { assertAgentUsableBy } from '@/database/utils/agent-access';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';import { createEvidenceFileResolver } from '@/server/services/verify/evidenceFiles';import { resolveAcceptanceCommentAccess } from './_helpers/acceptanceCommentAccess';@@ -62,6 +64,7 @@ const createSchema = zeditorData: z.unknown().optional(),kind: z.enum(['approval', 'comment', 'proposal']).optional(),parentCommentId: z.string().trim().min(1).max(64).optional(),+ source: reviewAnchorSchema.optional(),}).refine((value) =>@@ -73,6 +76,10 @@ const createSchema = zmessage: 'A reply cannot carry its own anchor',path: ['anchor'],})+ .refine((value) => !(value.parentCommentId && value.source), {+ message: 'A reply cannot carry its own page anchor',+ path: ['source'],+ }).refine((value) => !(value.parentCommentId && value.kind === 'approval'), {message: 'An approval is a thread root',path: ['kind'],@@ -252,6 +259,16 @@ const enrich = async (reactionsByComment.set(row.parentCommentId, byEmoji);}+ // The reporter's console errors and user agent are diagnostics for whoever+ // fixes the page, not something every link holder should read.+ const sourceOf = (row: AcceptanceCommentRow) => {+ if (!row.source) return null;+ const own = Boolean(scope.userId) && row.authorUserId === scope.userId;+ if (own || scope.canModerate) return row.source;+ const { env: _env, ...rest } = row.source;+ return rest;+ };+return rows.filter((row) => row.kind !== 'reaction').map((row) => ({@@ -284,6 +301,7 @@ const enrich = async (rect: row.anchorRect,resolvedAt: row.resolvedAt,resolvedByUserId: row.resolvedByUserId,+ source: sourceOf(row),updatedAt: row.updatedAt,}));};@@ -420,6 +438,7 @@ export const acceptanceCommentRouter = router({editorData: input.editorData as never,kind: input.kind,parentCommentId: input.parentCommentId,+ source: input.source,/** The ceiling travels INTO the write so it is counted and charged in* one transaction: checked out here it would be advisory only, and a@@ -442,6 +461,7 @@ export const acceptanceCommentRouter = router({visibility: access.acceptance.visibility,workspaceId: access.acceptance.workspaceId,});+ notifyAcceptance(access.acceptance.id, 'comments', ctx.userId);return { data: item, success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -481,6 +501,7 @@ export const acceptanceCommentRouter = router({comment.id,own ? { authorUserId: ctx.userId } : { moderator: true },);+ notifyAcceptance(comment.acceptanceId, 'comments', ctx.userId);return { data: { deleted: result !== false }, success: true };}),@@ -558,6 +579,7 @@ export const acceptanceCommentRouter = router({input.resolved,ctx.userId,);+ notifyAcceptance(comment.acceptanceId, 'comments', ctx.userId);return { data: { resolvedAt: row?.resolvedAt ?? null }, success: true };}),});diff --git a/apps/server/src/services/acceptanceReview/access.test.ts b/apps/server/src/services/acceptanceReview/access.test.tsnew file mode 100644index 00000000000..180d5a12660--- /dev/null+++ b/apps/server/src/services/acceptanceReview/access.test.ts@@ -0,0 +1,60 @@+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';++const commentAccess = vi.fn();+const canManage = vi.fn();++vi.mock('@/server/routers/lambda/_helpers/acceptanceCommentAccess', () => ({+ resolveAcceptanceCommentAccess: (...args: unknown[]) => commentAccess(...args),+}));+vi.mock('@/server/routers/lambda/_helpers/acceptanceWriteScope', () => ({+ canManageAcceptance: (...args: unknown[]) => canManage(...args),+}));++const db = {} as LobeChatDatabase;+const acceptance = { id: 'acc-1', userId: 'owner', workspaceId: null };++describe('resolveReviewAccess', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('maps the existing acceptance rules onto the review capabilities', async () => {+ commentAccess.mockResolvedValueOnce({ acceptance, canApprove: false, canComment: true });+ canManage.mockResolvedValueOnce(false);+ const { resolveReviewAccess } = await import('./access');++ await expect(resolveReviewAccess(db, 'user-1', 'acc-1')).resolves.toEqual({+ acceptance,+ can: { comment: true, decide: false, moderate: false },+ });+ expect(commentAccess).toHaveBeenCalledWith(db, 'user-1', 'acc-1');+ expect(canManage).toHaveBeenCalledWith({ serverDB: db, userId: 'user-1' }, acceptance);+ });++ it('lets a manager decide and moderate', async () => {+ commentAccess.mockResolvedValueOnce({ acceptance, canApprove: true, canComment: true });+ canManage.mockResolvedValueOnce(true);+ const { resolveReviewAccess } = await import('./access');++ await expect(resolveReviewAccess(db, 'owner', 'acc-1')).resolves.toMatchObject({+ can: { comment: true, decide: true, moderate: true },+ });+ });++ it('reads an unreadable acceptance as none at all', async () => {+ commentAccess.mockRejectedValueOnce(new TRPCError({ code: 'NOT_FOUND' }));+ const { resolveReviewAccess } = await import('./access');++ await expect(resolveReviewAccess(db, 'stranger', 'acc-1')).resolves.toBeNull();+ });++ it('lets unexpected failures through', async () => {+ commentAccess.mockRejectedValueOnce(new Error('db down'));+ const { resolveReviewAccess } = await import('./access');++ await expect(resolveReviewAccess(db, 'user-1', 'acc-1')).rejects.toThrow('db down');+ });+});diff --git a/apps/server/src/services/acceptanceReview/access.ts b/apps/server/src/services/acceptanceReview/access.tsnew file mode 100644index 00000000000..c236a66cfd5--- /dev/null+++ b/apps/server/src/services/acceptanceReview/access.ts@@ -0,0 +1,29 @@+import { TRPCError } from '@trpc/server';++import type { AcceptanceItem } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';+import { resolveAcceptanceCommentAccess } from '@/server/routers/lambda/_helpers/acceptanceCommentAccess';+import { canManageAcceptance } from '@/server/routers/lambda/_helpers/acceptanceWriteScope';++export interface ReviewAccess {+ acceptance: AcceptanceItem;+ can: { comment: boolean; decide: boolean; moderate: boolean };+}++export async function resolveReviewAccess(+ db: LobeChatDatabase,+ userId: string,+ acceptanceId: string,+): Promise<ReviewAccess | null> {+ try {+ const access = await resolveAcceptanceCommentAccess(db, userId, acceptanceId);+ const decide = await canManageAcceptance({ serverDB: db, userId }, access.acceptance);+ return {+ acceptance: access.acceptance,+ can: { comment: access.canComment, decide, moderate: access.canApprove },+ };+ } catch (error) {+ if (error instanceof TRPCError && error.code === 'NOT_FOUND') return null;+ throw error;+ }+}diff --git a/apps/server/src/services/acceptanceReview/events.ts b/apps/server/src/services/acceptanceReview/events.tsnew file mode 100644index 00000000000..1721ee80e73--- /dev/null+++ b/apps/server/src/services/acceptanceReview/events.ts@@ -0,0 +1,15 @@+import { publishResourceEvent } from '@/server/services/resourceEvents';+import { after } from '@/server/utils/scheduleAfterResponse';++export type AcceptanceChange = 'comments' | 'session';++export const notifyAcceptance = (acceptanceId: string, change: AcceptanceChange, actorId = '') =>+ after(() =>+ publishResourceEvent(+ { id: acceptanceId, type: 'acceptance' },+ {+ actorId,+ type: change === 'comments' ? 'acceptance.commentsChanged' : 'acceptance.sessionChanged',+ },+ ),+ );diff --git a/apps/server/src/services/resourceEvents/types.ts b/apps/server/src/services/resourceEvents/types.tsindex cb7d33d02f9..8e6a934cb2c 100644--- a/apps/server/src/services/resourceEvents/types.ts+++ b/apps/server/src/services/resourceEvents/types.ts@@ -1,5 +1,5 @@/** Resource families that can broadcast realtime invalidation or collaboration events. */-export type ResourceType = 'agent' | 'chatGroup' | 'document' | 'task' | 'topic';+export type ResourceType = 'acceptance' | 'agent' | 'chatGroup' | 'document' | 'task' | 'topic';export interface ResourceRef {id: string;@@ -7,6 +7,8 @@ export interface ResourceRef {}export type ResourceEventType =+ | 'acceptance.commentsChanged'+ | 'acceptance.sessionChanged'| 'doc.updated'| 'document.commentsChanged'| 'document.likesChanged'diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex 17ef052931f..01431c061d3 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -43,6 +43,7 @@ import type {} from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';import { notTrashed } from '@/database/utils/softDelete';+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';import { ExpertiseRejectionWorkflow } from '@/server/workflows/expertiseRejection';import {@@ -826,6 +827,7 @@ export class AcceptanceService {// Rounds inherit the aggregate's visibility so a private acceptance's new// round never leaks through its own report URL.const run = await this.runModel.attachToAcceptance(runId, acceptanceId, acceptance.visibility);+ notifyAcceptance(acceptanceId, 'session');await this.recomputeStatus(acceptanceId);log('run %s attached to acceptance %s as round %d', runId, acceptanceId, run.roundIndex);@@ -938,6 +940,7 @@ export class AcceptanceService {const status = statusFromRound(current, Boolean(report));if (status !== acceptance.status) {await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);+ notifyAcceptance(acceptanceId, 'session');log('acceptance %s → %s (from round %d)', acceptanceId, status, current.roundIndex);}@@ -1028,6 +1031,7 @@ export class AcceptanceService {const settled = await this.stampDecision(acceptanceId, 'accept', comment);await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');+ notifyAcceptance(acceptanceId, 'session', this.actorUserId);// A terminal decision settles the current round as surely as a new round landing does — and it// is the ONLY thing that settles the last one, which no later round will ever follow. Without@@ -1073,6 +1077,7 @@ export class AcceptanceService {}await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');+ notifyAcceptance(acceptanceId, 'session', this.actorUserId);if (current) this.distilSettledRound(acceptanceId, current.id);if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);@@ -1102,6 +1107,7 @@ export class AcceptanceService {const settled = await this.stampDecision(acceptanceId, 'reject', comment);await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');+ notifyAcceptance(acceptanceId, 'session', this.actorUserId);this.distilSettledRound(acceptanceId, settled);diff --git a/locales/en-US/oauth.json b/locales/en-US/oauth.jsonindex fad2dabee74..51f0e42c0fc 100644--- a/locales/en-US/oauth.json+++ b/locales/en-US/oauth.json@@ -10,6 +10,8 @@"authorizeError.reason.unauthorized_client": "This app is not allowed to use this sign-in method.","authorizeError.reason.unknown": "The authorization request could not be completed.","authorizeError.title": "Authorization Can't Continue",+ "consent.acceptanceReview.denied": "You do not have access to this acceptance, so it cannot be reviewed from this page.",+ "consent.acceptanceReview.target": "Review the acceptance: {{title}}","consent.buttons.accept": "Authorize","consent.buttons.deny": "Deny","consent.description": "The application {{clientName}} is requesting authorization for your account",@@ -22,6 +24,7 @@"consent.permissionsTitle": "Requesting the following permissions:","consent.redirectUri": "You will be redirected to after successful authorization","consent.redirecting": "Authorization successful, redirecting...",+ "consent.scope.acceptance-review": "Comment on this acceptance and accept or send it back from its preview page","consent.scope.email": "Access your email address","consent.scope.offline_access": "Allow the client to access your data","consent.scope.openid": "Authenticate using your LobeHub account",diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 961cace798c..5177f8a6e6a 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -228,6 +228,8 @@"acceptance.predict.nonePending": "Nothing left to review — every check already has a verdict.","acceptance.predict.proposals": "AI review finished: {{count}} check(s) flagged for you.","acceptance.predict.stillRunning": "AI review is still running — refresh in a moment to see the results.",+ "acceptance.preview.review": "Review on preview",+ "acceptance.preview.reviewHint": "Open the deployed preview with the review toolbar to comment on the live page","acceptance.proposal.confirm": "Confirm and send back","acceptance.proposal.misidentified": "Real problem, wrong spot","acceptance.proposal.notAnIssue": "Not a problem",diff --git a/locales/zh-CN/oauth.json b/locales/zh-CN/oauth.jsonindex f89ac5241fa..6a429f319db 100644--- a/locales/zh-CN/oauth.json+++ b/locales/zh-CN/oauth.json@@ -10,6 +10,8 @@"authorizeError.reason.unauthorized_client": "这个应用不被允许使用这种登录方式。","authorizeError.reason.unknown": "授权请求未能完成。","authorizeError.title": "无法继续授权",+ "consent.acceptanceReview.denied": "你没有这张验收单的访问权限,无法在此页面评审。",+ "consent.acceptanceReview.target": "评审验收单:{{title}}","consent.buttons.accept": "授权","consent.buttons.deny": "拒绝","consent.description": "应用 {{clientName}} 申请你的账户授权",@@ -22,6 +24,7 @@"consent.permissionsTitle": "请求以下权限:","consent.redirectUri": "授权成功后将重定向到","consent.redirecting": "授权成功,跳转中…",+ "consent.scope.acceptance-review": "在预览页上评论这张验收单,并通过或打回","consent.scope.email": "访问你的电子邮件地址","consent.scope.offline_access": "允许客户端访问你的数据","consent.scope.openid": "使用你的 LobeHub 账户进行身份验证",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 0509e01a996..1b6662b01c0 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -228,6 +228,8 @@"acceptance.predict.nonePending": "没有待复核的检查项,所有检查都已有判定","acceptance.predict.proposals": "AI 复核完成:{{count}} 项检查提出异议,请查看卡片","acceptance.predict.stillRunning": "AI 复核仍在进行中,稍后刷新即可查看结果",+ "acceptance.preview.review": "在预览中评审",+ "acceptance.preview.reviewHint": "打开已部署的预览页,用评审工具栏直接在页面上提意见","acceptance.proposal.confirm": "确认并打回","acceptance.proposal.misidentified": "确有问题,但位置不对","acceptance.proposal.notAnIssue": "这不是问题",diff --git a/packages/const/src/acceptanceReview.ts b/packages/const/src/acceptanceReview.tsnew file mode 100644index 00000000000..6b354de64a6--- /dev/null+++ b/packages/const/src/acceptanceReview.ts@@ -0,0 +1,14 @@+export const ACCEPTANCE_REVIEW_CLIENT_ID = 'lobehub-review';++export const ACCEPTANCE_REVIEW_SCOPE = 'acceptance:review';++export const ACCEPTANCE_REVIEW_RESOURCE_PREFIX = 'urn:lobehub:acceptance:';++export const ACCEPTANCE_REVIEW_TOKEN_TTL_SECONDS = 8 * 60 * 60;++const RESOURCE_PATTERN = /^urn:lobehub:acceptance:([\w-]{1,64})$/;++export const acceptanceIdFromReviewResource = (resource: unknown): string | undefined => {+ if (typeof resource !== 'string') return undefined;+ return RESOURCE_PATTERN.exec(resource)?.[1];+};diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex 21089f574bb..54320f01513 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -1,3 +1,4 @@+export * from './acceptanceReview';export * from './agentDocument';export * from './agentName';export * from './agentShare';diff --git a/packages/database/src/models/__tests__/acceptanceComment.test.ts b/packages/database/src/models/__tests__/acceptanceComment.test.tsindex e300b1e31b3..38037f2bfc5 100644--- a/packages/database/src/models/__tests__/acceptanceComment.test.ts+++ b/packages/database/src/models/__tests__/acceptanceComment.test.ts@@ -147,9 +147,18 @@ describe('AcceptanceCommentModel', () => {it('keeps the product page and metadata on a thread root, never on a reply', async () => {const source = {- kind: 'product-page' as const,- selector: '#run-status',+ intent: 'comment' as const,+ scroll: { x: 0, y: 0 },+ targets: [+ {+ label: 'Status',+ rect: { height: 20, width: 80, x: 0, y: 0 },+ selector: '#run-status',+ },+ ],url: 'https://product.example.com/experiments',+ v: 1 as const,+ viewport: { dpr: 1, height: 800, width: 1280 },};const { comment: root } = await model.create({acceptanceId,diff --git a/packages/locales/src/default/oauth.ts b/packages/locales/src/default/oauth.tsindex 376f86d7edb..6a22a93ef57 100644--- a/packages/locales/src/default/oauth.ts+++ b/packages/locales/src/default/oauth.ts@@ -25,9 +25,14 @@ export default {'consent.error.unknown.message': 'An unknown error occurred while loading authorization details.','consent.error.unsupportedInteraction.message': 'Unsupported interaction type: {{promptName}}','consent.error.unsupportedInteraction.title': 'Unsupported Interaction Type',+ 'consent.acceptanceReview.denied':+ 'You do not have access to this acceptance, so it cannot be reviewed from this page.',+ 'consent.acceptanceReview.target': 'Review the acceptance: {{title}}','consent.permissionsTitle': 'Requesting the following permissions:','consent.redirectUri': 'You will be redirected to after successful authorization','consent.redirecting': 'Authorization successful, redirecting...',+ 'consent.scope.acceptance-review':+ 'Comment on this acceptance and accept or send it back from its preview page','consent.scope.email': 'Access your email address','consent.scope.offline_access': 'Allow the client to access your data','consent.scope.openid': 'Authenticate using your LobeHub account',diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex d32c973f8e7..54470d82e25 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -401,6 +401,9 @@ export default {'acceptance.origin.agentFallback': 'Agent','acceptance.origin.backToRuns': 'Back to runs','acceptance.origin.openTopic': 'Open topic',+ 'acceptance.preview.review': 'Review on preview',+ 'acceptance.preview.reviewHint':+ 'Open the deployed preview with the review toolbar to comment on the live page','acceptance.reject.descriptionCopy':'No agent is attached to this delivery. Rejecting copies the repair prompt, including any reason you add — paste it to any agent to start the next round.','acceptance.reject.description':diff --git a/packages/types/src/acceptanceComment.ts b/packages/types/src/acceptanceComment.tsindex 820c0dc4a64..ac73758ae10 100644--- a/packages/types/src/acceptanceComment.ts+++ b/packages/types/src/acceptanceComment.ts@@ -1,3 +1,4 @@+import type { ReviewAnchor } from './acceptanceReview';import type { DocumentCommentJson } from './documentComment';import type { AcceptanceAttachment, AcceptanceReviewAnnotation } from './verify';@@ -33,34 +34,7 @@ export interface AcceptanceCommentAttachmentRef {fileId: string;}-/**- * Where a remark was written when it did not come from the acceptance viewer:- * a reviewer pointing at a page of the delivered product through the embedded- * review toolbar. It is the reproduction recipe the repair agent reads — the- * page, the element, what the page itself reported, and any product-specific- * facts (e.g. which sandbox data scenario was loaded).- */-export interface AcceptanceCommentSource {- /** Build / commit the page was served from, when the product exposes one. */- commit?: string;- /** Recent front-end errors on that page, newest last. */- consoleErrors?: string[];- /** Visible text of the element, trimmed — a way to find it when the selector drifts. */- elementText?: string;- /** Product-defined facts, e.g. `{ scenario: 'training-mixed', seed: 7 }`. */- extra?: Record<string, boolean | number | string>;- kind: 'product-page';- /** Element box in viewport pixels at the time of the remark. */- rect?: { height: number; width: number; x: number; y: number };- /** A CSS selector for the element the reviewer pointed at. */- selector?: string;- /** Document title of the page. */- title?: string;- /** Full page URL. */- url: string;- userAgent?: string;- viewport?: { height: number; width: number };-}+export type AcceptanceCommentSource = ReviewAnchor;/** One emoji on one comment, already tallied for display. */export interface AcceptanceCommentReaction {@@ -138,6 +112,7 @@ export interface AcceptanceCommentItem extends AcceptanceCommentAnchor {reactions: AcceptanceCommentReaction[];resolvedAt: Date | null;resolvedByUserId: string | null;+ source: AcceptanceCommentSource | null;updatedAt: Date;}diff --git a/packages/types/src/acceptanceReview.ts b/packages/types/src/acceptanceReview.tsnew file mode 100644index 00000000000..aeceb77e5d2--- /dev/null+++ b/packages/types/src/acceptanceReview.ts@@ -0,0 +1,126 @@+// Contract for the embeddable review toolbar (`@lobehub/review-sdk`, `src/protocol.ts`).+import { z } from 'zod';++const rectSchema = z.object({+ height: z.number().finite(),+ width: z.number().finite(),+ x: z.number().finite(),+ y: z.number().finite(),+});++export const reviewAnchorSchema = z.object({+ commit: z.string().max(200).optional(),+ context: z+ .record(z.string().max(100), z.union([z.string().max(500), z.number(), z.boolean()]))+ .optional(),+ env: z+ .object({+ consoleErrors: z.array(z.string().max(2000)).max(10),+ userAgent: z.string().max(500),+ })+ .optional(),+ intent: z.enum(['change', 'comment']),+ region: rectSchema.optional(),+ scroll: z.object({ x: z.number().finite(), y: z.number().finite() }),+ targets: z+ .array(+ z.object({+ code: z+ .object({+ chain: z+ .array(+ z.object({+ file: z.string().max(500).optional(),+ line: z.number().int().optional(),+ name: z.string().max(200),+ }),+ )+ .max(5),+ column: z.number().int(),+ file: z.string().max(500),+ line: z.number().int(),+ })+ .optional(),+ label: z.string().max(200),+ rect: rectSchema,+ selector: z.string().max(2000),+ text: z.string().max(200).optional(),+ }),+ )+ .max(8),+ title: z.string().max(300).optional(),+ url: z.string().url().max(2000),+ v: z.literal(1),+ viewport: z.object({+ dpr: z.number().positive(),+ height: z.number().finite(),+ width: z.number().finite(),+ }),+});++export type ReviewAnchor = z.infer<typeof reviewAnchorSchema>;++export const REVIEW_ANCHOR_MAX_BYTES = 32 * 1024;++export const createReviewCommentSchema = z+ .object({+ anchor: reviewAnchorSchema.optional(),+ clientId: z.string().trim().min(1).max(255),+ content: z.string().trim().min(1).max(4000),+ parentId: z.string().trim().min(1).max(64).optional(),+ screenshot: z+ .object({ dataUrl: z.string().regex(/^data:image\/(jpeg|webp);base64,/) })+ .optional(),+ })+ .refine((value) => !(value.parentId && (value.anchor || value.screenshot)), {+ message: 'A reply cannot carry an anchor or a screenshot',+ })+ .refine(+ (value) => !value.anchor || JSON.stringify(value.anchor).length <= REVIEW_ANCHOR_MAX_BYTES,+ {+ message: 'Anchor is too large',+ },+ );++export type CreateReviewCommentInput = z.infer<typeof createReviewCommentSchema>;++export const reviewDecisionSchema = z.object({+ note: z.string().trim().max(2000).optional(),+ verdict: z.enum(['accept', 'send_back']),+});++export interface ReviewUser {+ avatar?: string;+ id: string;+ name: string;+}++export interface ReviewSession {+ acceptance: {+ id: string;+ previewUrl?: string;+ requirement?: string;+ round: number;+ status: string;+ title: string;+ url: string;+ };+ can: { comment: boolean; decide: boolean; moderate: boolean };+ expiresAt: string;+ user: ReviewUser;+}++export interface ReviewComment {+ anchor: ReviewAnchor | null;+ author: ReviewUser;+ clientId?: string;+ content: string;+ createdAt: string;+ id: string;+ mine: boolean;+ parentId: string | null;+ replies: ReviewComment[];+ resolvedAt: string | null;+ round: number | null;+ screenshot: { url: string } | null;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 21d0aeaeb5b..70cb5117b14 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -74,6 +74,7 @@ export * from './work';// it more likes the UI message payloadexport * from './acceptanceComment';export * from './acceptanceFlow';+export * from './acceptanceReview';export * from './agentRuntime';export * from './oauthApp';export * from './openai/chat';diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 12a3f168798..d7f3830ccee 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -676,6 +676,7 @@ export interface VerifyRunMetadata {* run that *authored* the report — and is many-to-one.*/origin?: VerifyRunOrigin;+ previewUrl?: string;/*** The round this one replays (`flow plan --from-run`). A replay is pinned to* the source round's frozen definition, so it never follows later graph editsdiff --git a/src/app/(backend)/api/acceptance-review/[[...route]]/route.ts b/src/app/(backend)/api/acceptance-review/[[...route]]/route.tsnew file mode 100644index 00000000000..1e94518ed1c--- /dev/null+++ b/src/app/(backend)/api/acceptance-review/[[...route]]/route.ts@@ -0,0 +1,12 @@+import app from '@/server/router-hono/acceptance-review';++export const maxDuration = 300;+export const runtime = 'nodejs';++const handler = (request: Request) => app.fetch(request);++export const GET = handler;+export const POST = handler;+export const PATCH = handler;+export const DELETE = handler;+export const OPTIONS = handler;diff --git a/src/app/(backend)/oidc/consent/route.test.ts b/src/app/(backend)/oidc/consent/route.test.tsindex 14292bced6f..74c39fa24fb 100644--- a/src/app/(backend)/oidc/consent/route.test.ts+++ b/src/app/(backend)/oidc/consent/route.test.ts@@ -10,6 +10,14 @@ const mocks = vi.hoisted(() => ({getInteractionDetails: vi.fn(),getInteractionResult: vi.fn(),getUserAuth: vi.fn(),+ findOrCreateGrants: vi.fn(),+ resolveReviewAccess: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));++vi.mock('@/server/services/acceptanceReview/access', () => ({+ resolveReviewAccess: mocks.resolveReviewAccess,}));vi.mock('debug', () => ({ default: () => vi.fn() }));@@ -19,6 +27,7 @@ vi.mock('@lobechat/utils/server', () => ({ getUserAuth: mocks.getUserAuth }));vi.mock('@/server/services/oidc', () => ({OIDCService: {initialize: vi.fn(async () => ({+ findOrCreateGrants: mocks.findOrCreateGrants,getInteractionDetails: mocks.getInteractionDetails,getInteractionResult: mocks.getInteractionResult,})),@@ -66,4 +75,51 @@ describe('POST /oidc/consent', () => {expect(response.status).toBe(400);expect(mocks.getInteractionResult).not.toHaveBeenCalled();});++ describe('acceptance review client', () => {+ const RESOURCE = 'urn:lobehub:acceptance:7f0c9a7e-0000-4000-8000-000000000001';++ beforeEach(() => {+ mocks.getInteractionDetails.mockResolvedValue({+ params: { client_id: 'lobehub-review', resource: RESOURCE },+ prompt: {+ details: { missingResourceScopes: { [RESOURCE]: ['acceptance:review'] } },+ name: 'consent',+ },+ });+ mocks.findOrCreateGrants.mockResolvedValue({+ addOIDCClaims: vi.fn(),+ addOIDCScope: vi.fn(),+ addResourceScope: vi.fn(),+ save: vi.fn(async () => 'grant-1'),+ });+ });++ it('denies the grant when the reviewer cannot read the acceptance', async () => {+ mocks.resolveReviewAccess.mockResolvedValue(null);++ await POST(createRequest({ consent: 'accept', uid: 'uid-1' }));++ expect(mocks.getInteractionResult).toHaveBeenCalledWith('uid-1', {+ error: 'access_denied',+ error_description: 'No access to this acceptance',+ });+ expect(mocks.findOrCreateGrants).not.toHaveBeenCalled();+ });++ it('grants a reviewer who can read the acceptance', async () => {+ mocks.resolveReviewAccess.mockResolvedValue({ acceptance: {}, can: {} });++ await POST(createRequest({ consent: 'accept', uid: 'uid-1' }));++ expect(mocks.resolveReviewAccess).toHaveBeenCalledWith(+ {},+ 'user-1',+ '7f0c9a7e-0000-4000-8000-000000000001',+ );+ expect(mocks.getInteractionResult).toHaveBeenCalledWith('uid-1', {+ consent: { grantId: 'grant-1' },+ });+ });+ });});diff --git a/src/app/(backend)/oidc/consent/route.ts b/src/app/(backend)/oidc/consent/route.tsindex 180a0cfa33d..547f3ac1ddc 100644--- a/src/app/(backend)/oidc/consent/route.ts+++ b/src/app/(backend)/oidc/consent/route.ts@@ -1,12 +1,24 @@+import { acceptanceIdFromReviewResource } from '@lobechat/const';import { getUserAuth } from '@lobechat/utils/server';import debug from 'debug';import { type NextRequest } from 'next/server';import { NextResponse } from 'next/server';+import { getServerDB } from '@/database/core/db-adaptor';+import { isAcceptanceReviewClient } from '@/libs/oidc-provider/acceptanceReview';+import { resolveReviewAccess } from '@/server/services/acceptanceReview/access';import { OIDCService } from '@/server/services/oidc';const log = debug('lobe-oidc:consent');+const canReview = async (userId: string | null | undefined, resource: unknown) => {+ const acceptanceId = acceptanceIdFromReviewResource(+ Array.isArray(resource) ? resource[0] : resource,+ );+ if (!userId || !acceptanceId) return false;+ return Boolean(await resolveReviewAccess(await getServerDB(), userId, acceptanceId));+};+export async function POST(request: NextRequest) {log('Received POST request for /oidc/consent, URL: %s', request.url);try {@@ -61,6 +73,21 @@ export async function POST(request: NextRequest) {// 1. Get necessary IDsconst clientId = details.params.client_id as string;+ if (+ isAcceptanceReviewClient(clientId) &&+ !(await canReview(userId, details.params.resource))+ ) {+ const denied = await oidcService.getInteractionResult(uid, {+ error: 'access_denied',+ error_description: 'No access to this acceptance',+ });+ const { pathname, search, hash } = new URL(denied);+ return new NextResponse(null, {+ headers: { location: `${pathname}${search}${hash}` },+ status: 303,+ });+ }+// 2. Find or create Grant objectconst grant = await oidcService.findOrCreateGrants(userId!, clientId, details.grantId);diff --git a/src/app/(backend)/oidc/interaction/[uid]/route.test.ts b/src/app/(backend)/oidc/interaction/[uid]/route.test.tsindex 9fc3c0ce49c..36b4a0fa6c6 100644--- a/src/app/(backend)/oidc/interaction/[uid]/route.test.ts+++ b/src/app/(backend)/oidc/interaction/[uid]/route.test.ts@@ -10,6 +10,20 @@ const mocks = vi.hoisted(() => ({authEnv: { ENABLE_OIDC: true },getConsentClientMetadata: vi.fn(),getInteractionDetails: vi.fn(),+ getUserAuth: vi.fn(),+ resolveReviewAccess: vi.fn(),+}));++vi.mock('@lobechat/utils/server', () => ({+ getUserAuth: mocks.getUserAuth,+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(async () => ({})),+}));++vi.mock('@/server/services/acceptanceReview/access', () => ({+ resolveReviewAccess: mocks.resolveReviewAccess,}));vi.mock('debug', () => ({@@ -163,4 +177,56 @@ describe('GET /oidc/interaction/[uid]', () => {expect(response.status).toBe(500);await expect(response.json()).resolves.toEqual({ error: 'server_error' });});++ describe('acceptance review client', () => {+ const RESOURCE = 'urn:lobehub:acceptance:7f0c9a7e-0000-4000-8000-000000000001';++ beforeEach(() => {+ mocks.getInteractionDetails.mockResolvedValue({+ params: { client_id: 'lobehub-review', resource: RESOURCE, scope: 'acceptance:review' },+ prompt: { name: 'consent' },+ });+ mocks.getConsentClientMetadata.mockResolvedValue({ clientName: 'LobeHub Review' });+ mocks.getUserAuth.mockResolvedValue({ userId: 'user-1' });+ });++ it('names the acceptance the reviewer is about to open', async () => {+ mocks.resolveReviewAccess.mockResolvedValue({+ acceptance: { metadata: { title: 'Billing redesign' }, requirement: 'r' },+ can: { comment: true, decide: false, moderate: false },+ });++ const response = await GET(createRequest('uid-r'), createProps('uid-r'));++ await expect(response.json()).resolves.toMatchObject({+ acceptanceReview: { allowed: true, title: 'Billing redesign' },+ });+ expect(mocks.resolveReviewAccess).toHaveBeenCalledWith(+ {},+ 'user-1',+ '7f0c9a7e-0000-4000-8000-000000000001',+ );+ });++ it('says nothing about an acceptance the reviewer cannot read', async () => {+ mocks.resolveReviewAccess.mockResolvedValue(null);++ const response = await GET(createRequest('uid-r'), createProps('uid-r'));+ const body = await response.json();++ expect(body.acceptanceReview).toEqual({ allowed: false });+ });++ it('is not looked up for other clients', async () => {+ mocks.getInteractionDetails.mockResolvedValue({+ params: { client_id: 'lobehub-desktop', scope: 'openid' },+ prompt: { name: 'consent' },+ });++ const response = await GET(createRequest('uid-d'), createProps('uid-d'));++ expect((await response.json()).acceptanceReview).toBeUndefined();+ expect(mocks.resolveReviewAccess).not.toHaveBeenCalled();+ });+ });});diff --git a/src/app/(backend)/oidc/interaction/[uid]/route.ts b/src/app/(backend)/oidc/interaction/[uid]/route.tsindex 8ce063b4362..33f011aa2a4 100644--- a/src/app/(backend)/oidc/interaction/[uid]/route.ts+++ b/src/app/(backend)/oidc/interaction/[uid]/route.ts@@ -1,13 +1,35 @@+import { acceptanceIdFromReviewResource } from '@lobechat/const';+import { getUserAuth } from '@lobechat/utils/server';import debug from 'debug';import { type NextRequest } from 'next/server';import { NextResponse } from 'next/server';+import { getServerDB } from '@/database/core/db-adaptor';import { authEnv } from '@/envs/auth';+import { isAcceptanceReviewClient } from '@/libs/oidc-provider/acceptanceReview';+import { resolveReviewAccess } from '@/server/services/acceptanceReview/access';import { OIDCService } from '@/server/services/oidc';import type { OidcInteractionDetailsResponse, OidcInteractionErrorResponse } from '@/types/oidc';const log = debug('lobe-oidc:interaction');+// The title is only revealed once the signed-in reviewer may read the acceptance.+const acceptanceReviewOf = async (+ resource: unknown,+): Promise<OidcInteractionDetailsResponse['acceptanceReview']> => {+ const acceptanceId = acceptanceIdFromReviewResource(+ Array.isArray(resource) ? resource[0] : resource,+ );+ const { userId } = await getUserAuth();+ if (!acceptanceId || !userId) return { allowed: false };+ const access = await resolveReviewAccess(await getServerDB(), userId, acceptanceId);+ if (!access) return { allowed: false };+ return {+ allowed: true,+ title: access.acceptance.metadata?.title || access.acceptance.requirement || undefined,+ };+};+export async function GET(request: NextRequest, props: { params: Promise<{ uid: string }> }) {if (!authEnv.ENABLE_OIDC) {log('OIDC is not enabled');@@ -38,8 +60,13 @@ export async function GET(request: NextRequest, props: { params: Promise<{ uid:const scopes = (details.params.scope as string)?.split(' ') || [];const clientMetadata = await oidcService.getConsentClientMetadata(clientId);+ const acceptanceReview =+ details.prompt.name === 'consent' && isAcceptanceReviewClient(clientId)+ ? await acceptanceReviewOf(details.params.resource)+ : undefined;return NextResponse.json<OidcInteractionDetailsResponse>({+ acceptanceReview,clientId,clientMetadata,prompt: details.prompt.name,diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsxindex 4d1030cd00f..3dd02aff075 100644--- a/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx+++ b/src/features/Acceptance/Viewer/Header/AcceptanceIdentity.tsx@@ -10,6 +10,7 @@ import { useAcceptanceScope } from '../AcceptanceScope';import { acceptanceCodingScope } from '../History/codingScope';import { useAcceptanceBundle } from '../useAcceptanceBundle';import AcceptanceStatusPill from './AcceptanceStatusPill';+import PreviewReviewLink from './PreviewReviewLink';import PullRequestLinks from './PullRequestLinks';const styles = createStaticStyles(({ css }) => ({@@ -125,6 +126,7 @@ const AcceptanceIdentity = ({ focusSlot, statusSlot, topicSlot }: AcceptanceIdenfallback={acceptanceCodingScope(rounds)?.pullRequest}pullRequests={pullRequests}/>+ <PreviewReviewLink acceptanceId={acceptance.id} rounds={rounds} /></Flexbox></Flexbox>);diff --git a/src/features/Acceptance/Viewer/Header/PreviewReviewLink.tsx b/src/features/Acceptance/Viewer/Header/PreviewReviewLink.tsxnew file mode 100644index 00000000000..ef4b966677c--- /dev/null+++ b/src/features/Acceptance/Viewer/Header/PreviewReviewLink.tsx@@ -0,0 +1,53 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowUpRight, MonitorSmartphone } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { AcceptanceBundle } from '@/services/verify';++import { previewReviewUrl } from './previewReview';++const styles = createStaticStyles(({ css }) => ({+ link: css`+ cursor: pointer;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ text-decoration: underline;+ }+ `,+}));++interface PreviewReviewLinkProps {+ acceptanceId: string;+ rounds: AcceptanceBundle['rounds'];+}++const PreviewReviewLink = memo<PreviewReviewLinkProps>(({ acceptanceId, rounds }) => {+ const { t } = useTranslation('verify');+ const href = previewReviewUrl(acceptanceId, rounds);+ if (!href) return null;+ return (+ <a+ className={styles.link}+ href={href}+ rel={'noreferrer'}+ target={'_blank'}+ title={t('acceptance.preview.reviewHint')}+ >+ <Flexbox horizontal align={'center'} gap={4}>+ <Icon icon={MonitorSmartphone} size={13} />+ {t('acceptance.preview.review')}+ <Icon icon={ArrowUpRight} size={12} />+ </Flexbox>+ </a>+ );+});++PreviewReviewLink.displayName = 'PreviewReviewLink';++export default PreviewReviewLink;diff --git a/src/features/Acceptance/Viewer/Header/previewReview.test.ts b/src/features/Acceptance/Viewer/Header/previewReview.test.tsnew file mode 100644index 00000000000..8e1ad465c23--- /dev/null+++ b/src/features/Acceptance/Viewer/Header/previewReview.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { previewReviewUrl } from './previewReview';++const round = (roundIndex: number, metadata: unknown) => ({ run: { metadata, roundIndex } });++describe('previewReviewUrl', () => {+ it('opens the latest round preview with the review toolbar activated', () => {+ expect(+ previewReviewUrl('acc-1', [+ round(1, { previewUrl: 'https://old.example.com/' }),+ round(2, { previewUrl: 'https://pr-12.example.com/app?tab=1#top' }),+ ]),+ ).toBe('https://pr-12.example.com/app?tab=1&lh-acceptance=acc-1#top');+ });++ it('offers nothing when the latest round was not deployed', () => {+ expect(+ previewReviewUrl('acc-1', [+ round(1, { previewUrl: 'https://x.example.com/' }),+ round(2, null),+ ]),+ ).toBeNull();+ expect(previewReviewUrl('acc-1', [])).toBeNull();+ });++ it('never turns a non-web address into a link', () => {+ expect(previewReviewUrl('acc-1', [round(1, { previewUrl: 'javascript:alert(1)' })])).toBeNull();+ expect(previewReviewUrl('acc-1', [round(1, { previewUrl: 'not a url' })])).toBeNull();+ });+});diff --git a/src/features/Acceptance/Viewer/Header/previewReview.ts b/src/features/Acceptance/Viewer/Header/previewReview.tsnew file mode 100644index 00000000000..75779349479--- /dev/null+++ b/src/features/Acceptance/Viewer/Header/previewReview.ts@@ -0,0 +1,18 @@+const ACTIVATION_PARAM = 'lh-acceptance';++interface RoundLike {+ run: { metadata?: unknown };+}++export const previewReviewUrl = (acceptanceId: string, rounds: RoundLike[]) => {+ const metadata = rounds.at(-1)?.run.metadata as { previewUrl?: unknown } | null | undefined;+ if (typeof metadata?.previewUrl !== 'string') return null;+ try {+ const url = new URL(metadata.previewUrl);+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;+ url.searchParams.set(ACTIVATION_PARAM, acceptanceId);+ return url.toString();+ } catch {+ return null;+ }+};diff --git a/src/features/Auth/OAuthConsent/Consent/index.tsx b/src/features/Auth/OAuthConsent/Consent/index.tsxindex c24a1c0cd98..f38e967954b 100644--- a/src/features/Auth/OAuthConsent/Consent/index.tsx+++ b/src/features/Auth/OAuthConsent/Consent/index.tsx@@ -6,13 +6,14 @@ import React, { memo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import AuthCard from '@/features/AuthCard';-import type { OidcClientMetadata } from '@/types/oidc';+import type { OidcClientMetadata, OidcInteractionDetailsResponse } from '@/types/oidc';import OAuthApplicationLogo from '../OAuthApplicationLogo';import ThirdPartyNotice from '../ThirdPartyNotice';import BuiltinConsent from './BuiltinConsent';interface ClientProps {+ acceptanceReview?: OidcInteractionDetailsResponse['acceptanceReview'];clientId: string;clientMetadata: OidcClientMetadata;redirectUri?: string;@@ -29,83 +30,97 @@ function getScopeDescription(scope: string, t: any): string {const BUILTIN_CLIENTS = new Set(['lobehub-desktop', 'lobehub-mobile', 'lobehub-market']);-const ConsentClient = memo<ClientProps>(({ uid, clientId, scopes, clientMetadata }) => {- const { t } = useTranslation('oauth');+const ConsentClient = memo<ClientProps>(+ ({ acceptanceReview, uid, clientId, scopes, clientMetadata }) => {+ const { t } = useTranslation('oauth');- const [isLoading, setIsLoading] = useState(false);- const consentInputRef = useRef<HTMLInputElement>(null);+ const [isLoading, setIsLoading] = useState(false);+ const consentInputRef = useRef<HTMLInputElement>(null);- const clientDisplayName = clientMetadata?.clientName || clientId;+ const clientDisplayName = clientMetadata?.clientName || clientId;+ const reviewDenied = acceptanceReview?.allowed === false;- if (BUILTIN_CLIENTS.has(clientId)) {- return <BuiltinConsent uid={uid} />;- }+ if (BUILTIN_CLIENTS.has(clientId)) {+ return <BuiltinConsent uid={uid} />;+ }- return (- <Flexbox gap={16} width={'min(100%,400px)'}>- <OAuthApplicationLogo- clientDisplayName={clientDisplayName}- isFirstParty={clientMetadata.isFirstParty}- logoUrl={clientMetadata.logo}- />- <AuthCard- centered- subtitle={t('consent.description', { clientName: clientDisplayName })}- title={t('consent.title', { clientName: clientDisplayName })}- footer={- <form action="/oidc/consent" method="post" style={{ width: '100%' }}>- <input name="uid" type="hidden" value={uid} />- <input defaultValue="accept" name="consent" ref={consentInputRef} type="hidden" />- <Flexbox gap={12}>- <Button- data-testid="oauth-consent-accept"- htmlType="submit"- loading={isLoading}- size={'large'}- type="primary"- onClick={() => {- if (consentInputRef.current) consentInputRef.current.value = 'accept';- setIsLoading(true);- }}- >- {t('consent.buttons.accept')}- </Button>- <Button- data-testid="oauth-consent-deny"- htmlType="submit"- size={'large'}- onClick={() => {- if (consentInputRef.current) consentInputRef.current.value = 'deny';- }}- >- {t('consent.buttons.deny')}- </Button>+ return (+ <Flexbox gap={16} width={'min(100%,400px)'}>+ <OAuthApplicationLogo+ clientDisplayName={clientDisplayName}+ isFirstParty={clientMetadata.isFirstParty}+ logoUrl={clientMetadata.logo}+ />+ <AuthCard+ centered+ subtitle={t('consent.description', { clientName: clientDisplayName })}+ title={t('consent.title', { clientName: clientDisplayName })}+ footer={+ <form action="/oidc/consent" method="post" style={{ width: '100%' }}>+ <input name="uid" type="hidden" value={uid} />+ <input defaultValue="accept" name="consent" ref={consentInputRef} type="hidden" />+ <Flexbox gap={12}>+ {!reviewDenied && (+ <Button+ data-testid="oauth-consent-accept"+ htmlType="submit"+ loading={isLoading}+ size={'large'}+ type="primary"+ onClick={() => {+ if (consentInputRef.current) consentInputRef.current.value = 'accept';+ setIsLoading(true);+ }}+ >+ {t('consent.buttons.accept')}+ </Button>+ )}+ <Button+ data-testid="oauth-consent-deny"+ htmlType="submit"+ size={'large'}+ onClick={() => {+ if (consentInputRef.current) consentInputRef.current.value = 'deny';+ }}+ >+ {t('consent.buttons.deny')}+ </Button>+ </Flexbox>+ </form>+ }+ >+ {clientMetadata.isFirstParty === false && (+ <Flexbox style={{ marginBottom: 16 }}>+ <ThirdPartyNotice+ developerName={clientMetadata.developerName}+ policyUri={clientMetadata.policyUri}+ /></Flexbox>- </form>- }- >- {clientMetadata.isFirstParty === false && (- <Flexbox style={{ marginBottom: 16 }}>- <ThirdPartyNotice- developerName={clientMetadata.developerName}- policyUri={clientMetadata.policyUri}- />- </Flexbox>- )}- <Text fontSize={16} type={'secondary'}>- {t('consent.permissionsTitle')}- </Text>- <Flexbox gap={4} style={{ marginTop: 8 }} width={'100%'}>- {scopes.map((scope) => (- <Block key={scope} padding={16} variant={'filled'}>- <Text>{getScopeDescription(scope, t)}</Text>+ )}+ {acceptanceReview && (+ <Block padding={16} style={{ marginBottom: 16 }} variant={'outlined'}>+ <Text type={reviewDenied ? 'danger' : undefined} weight={500}>+ {reviewDenied+ ? t('consent.acceptanceReview.denied')+ : t('consent.acceptanceReview.target', { title: acceptanceReview.title ?? '' })}+ </Text></Block>- ))}- </Flexbox>- </AuthCard>- </Flexbox>- );-});+ )}+ <Text fontSize={16} type={'secondary'}>+ {t('consent.permissionsTitle')}+ </Text>+ <Flexbox gap={4} style={{ marginTop: 8 }} width={'100%'}>+ {scopes.map((scope) => (+ <Block key={scope} padding={16} variant={'filled'}>+ <Text>{getScopeDescription(scope, t)}</Text>+ </Block>+ ))}+ </Flexbox>+ </AuthCard>+ </Flexbox>+ );+ },+);ConsentClient.displayName = 'ConsentClient';diff --git a/src/features/Auth/OAuthConsent/index.tsx b/src/features/Auth/OAuthConsent/index.tsxindex 3430970ed1c..03ee76f0c94 100644--- a/src/features/Auth/OAuthConsent/index.tsx+++ b/src/features/Auth/OAuthConsent/index.tsx@@ -73,6 +73,7 @@ const InteractionContent = memo(() => {return (<Consent+ acceptanceReview={data.acceptanceReview}clientId={data.clientId}clientMetadata={data.clientMetadata}redirectUri={data.redirectUri}diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.tsindex 9bf5413a055..07c3ec730d7 100644--- a/src/libs/next/proxy/define-config.ts+++ b/src/libs/next/proxy/define-config.ts@@ -215,6 +215,7 @@ export function defineConfig() {'/api/webhooks(.*)','/api/workflows(.*)','/api/agent(.*)',+ '/api/acceptance-review(.*)','/api/dev(.*)','/webapi(.*)','/trpc(.*)',diff --git a/src/libs/oidc-provider/acceptanceReview.test.ts b/src/libs/oidc-provider/acceptanceReview.test.tsnew file mode 100644index 00000000000..38ce7e486e7--- /dev/null+++ b/src/libs/oidc-provider/acceptanceReview.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import {+ accessTokenTTL,+ isAcceptanceReviewAudience,+ reviewResourceServer,+} from './acceptanceReview';++const RESOURCE = 'urn:lobehub:acceptance:7f0c9a7e-0000-4000-8000-000000000001';++describe('reviewResourceServer', () => {+ it('issues an eight hour JWT scoped to the one acceptance for the review client', () => {+ expect(reviewResourceServer('lobehub-review', RESOURCE)).toEqual({+ accessTokenFormat: 'jwt',+ accessTokenTTL: 8 * 60 * 60,+ audience: RESOURCE,+ scope: 'acceptance:review',+ });+ });++ it('refuses to widen the review client to the full API audience', () => {+ expect(reviewResourceServer('lobehub-review', 'urn:lobehub:chat')).toBe('reject');+ expect(reviewResourceServer('lobehub-review', 'urn:lobehub:acceptance:../x')).toBe('reject');+ });++ it('refuses a request naming more than one acceptance, since consent names only one', () => {+ const other = 'urn:lobehub:acceptance:7f0c9a7e-0000-4000-8000-000000000002';+ expect(reviewResourceServer('lobehub-review', RESOURCE, [RESOURCE, other])).toBe('reject');+ expect(reviewResourceServer('lobehub-review', RESOURCE, [RESOURCE])).toMatchObject({+ audience: RESOURCE,+ });+ expect(reviewResourceServer('lobehub-review', RESOURCE, RESOURCE)).toMatchObject({+ audience: RESOURCE,+ });+ });++ it('leaves other clients to the default resource rules', () => {+ expect(reviewResourceServer('lobehub-cli', 'urn:lobehub:chat')).toBeNull();+ expect(reviewResourceServer('lobehub-cli', RESOURCE)).toBeNull();+ expect(reviewResourceServer(undefined, 'urn:lobehub:chat')).toBeNull();+ });+});++describe('accessTokenTTL', () => {+ it('uses the resource server lifetime when it has one', () => {+ expect(accessTokenTTL({ resourceServer: { accessTokenTTL: 28_800 } }, 604_800)).toBe(28_800);+ });++ it('falls back to the default lifetime', () => {+ expect(accessTokenTTL({ resourceServer: {} }, 604_800)).toBe(604_800);+ expect(accessTokenTTL({}, 604_800)).toBe(604_800);+ });+});++describe('isAcceptanceReviewAudience', () => {+ it('recognizes review audiences, alone or in a list', () => {+ expect(isAcceptanceReviewAudience(RESOURCE)).toBe(true);+ expect(isAcceptanceReviewAudience(['urn:lobehub:chat', RESOURCE])).toBe(true);+ });++ it('ignores every other audience', () => {+ expect(isAcceptanceReviewAudience('urn:lobehub:chat')).toBe(false);+ expect(isAcceptanceReviewAudience(undefined)).toBe(false);+ expect(isAcceptanceReviewAudience(['urn:lobehub:hetero-operation'])).toBe(false);+ });+});diff --git a/src/libs/oidc-provider/acceptanceReview.ts b/src/libs/oidc-provider/acceptanceReview.tsnew file mode 100644index 00000000000..4c9c75a87e0--- /dev/null+++ b/src/libs/oidc-provider/acceptanceReview.ts@@ -0,0 +1,48 @@+import {+ ACCEPTANCE_REVIEW_CLIENT_ID,+ ACCEPTANCE_REVIEW_RESOURCE_PREFIX,+ ACCEPTANCE_REVIEW_SCOPE,+ ACCEPTANCE_REVIEW_TOKEN_TTL_SECONDS,+ acceptanceIdFromReviewResource,+} from '@lobechat/const';++export const isAcceptanceReviewClient = (clientId: string | undefined) =>+ clientId === ACCEPTANCE_REVIEW_CLIENT_ID;++// The review toolbar's token lives on third-party preview pages, so it must+// only ever carry one acceptance's audience — never the full API audience.+export const reviewResourceServer = (+ clientId: string | undefined,+ indicator: string,+ requested?: unknown,+) => {+ if (!isAcceptanceReviewClient(clientId)) return null;+ if (!acceptanceIdFromReviewResource(indicator)) return 'reject' as const;+ // Consent names and access-checks a single acceptance, so a request for+ // several would grant the ones the reviewer never saw.+ if (Array.isArray(requested) && requested.length > 1) return 'reject' as const;+ return {+ accessTokenFormat: 'jwt' as const,+ accessTokenTTL: ACCEPTANCE_REVIEW_TOKEN_TTL_SECONDS,+ audience: indicator,+ scope: ACCEPTANCE_REVIEW_SCOPE,+ };+};++// A numeric `ttl.AccessToken` overrides every resource server's own lifetime.+export const accessTokenTTL = (+ token: { resourceServer?: { accessTokenTTL?: number } },+ fallback: number,+) => token.resourceServer?.accessTokenTTL ?? fallback;++export const isAcceptanceReviewAudience = (aud: unknown) =>+ (Array.isArray(aud) ? aud : [aud]).some(+ (value) => typeof value === 'string' && value.startsWith(ACCEPTANCE_REVIEW_RESOURCE_PREFIX),+ );++// The review client is public and reachable from any origin, so nothing it was+// issued — access token or ID token — may ever pass as an app session.+export const isAcceptanceReviewIssued = (payload: { aud?: unknown; client_id?: unknown }) =>+ isAcceptanceReviewAudience(payload.aud) ||+ isAcceptanceReviewClient(payload.client_id as string | undefined) ||+ (Array.isArray(payload.aud) ? payload.aud : [payload.aud]).includes(ACCEPTANCE_REVIEW_CLIENT_ID);diff --git a/src/libs/oidc-provider/config.ts b/src/libs/oidc-provider/config.tsindex 8a5d3ed60c5..addcfb669bd 100644--- a/src/libs/oidc-provider/config.ts+++ b/src/libs/oidc-provider/config.ts@@ -1,3 +1,4 @@+import { ACCEPTANCE_REVIEW_CLIENT_ID, ACCEPTANCE_REVIEW_SCOPE } from '@lobechat/const';import { type ClientMetadata } from 'oidc-provider';import urlJoin from 'url-join';@@ -66,6 +67,16 @@ export const defaultClients: ClientMetadata[] = [response_types: [],token_endpoint_auth_method: 'none',},+ {+ application_type: 'native',+ client_id: ACCEPTANCE_REVIEW_CLIENT_ID,+ client_name: 'LobeHub Review',+ grant_types: ['urn:ietf:params:oauth:grant-type:device_code'],+ scope: ACCEPTANCE_REVIEW_SCOPE,+ logo_uri: 'https://hub-apac-1.lobeobjects.space/lobehub-desktop-icon.png',+ response_types: [],+ token_endpoint_auth_method: 'none',+ },{application_type: 'web',client_id: 'lobehub-market',@@ -93,6 +104,7 @@ export const defaultScopes = ['profile','email','offline_access', // Allows obtaining refresh_token+ ACCEPTANCE_REVIEW_SCOPE,];/**diff --git a/src/libs/oidc-provider/jwt.test.ts b/src/libs/oidc-provider/jwt.test.tsindex 5cc69cab9fe..89e0a1cd255 100644--- a/src/libs/oidc-provider/jwt.test.ts+++ b/src/libs/oidc-provider/jwt.test.ts@@ -58,3 +58,62 @@ describe('validateOIDCJWT', () => {expect((error as Error).message).toBe('JWKS_KEY public key retrieval failed: invalid JWK');});});++describe('acceptance review tokens', () => {+ const REVIEW_AUD = 'urn:lobehub:acceptance:7f0c9a7e-0000-4000-8000-000000000001';++ beforeEach(() => {+ vi.clearAllMocks();+ importJWKMock.mockResolvedValue('public-key');+ });++ it('are refused as an app session', async () => {+ jwtVerifyMock.mockResolvedValueOnce({+ payload: { aud: REVIEW_AUD, client_id: 'lobehub-review', sub: 'user-1' },+ });+ const { validateOIDCJWT } = await import('./jwt');+ await expect(validateOIDCJWT('t')).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+ });++ it('refuse anything else the review client was issued, such as its ID token', async () => {+ const { validateOIDCJWT } = await import('./jwt');+ jwtVerifyMock.mockResolvedValueOnce({ payload: { aud: 'lobehub-review', sub: 'user-1' } });+ await expect(validateOIDCJWT('t')).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+ jwtVerifyMock.mockResolvedValueOnce({+ payload: { aud: ['urn:lobehub:chat'], client_id: 'lobehub-review', sub: 'user-1' },+ });+ await expect(validateOIDCJWT('t')).rejects.toMatchObject({ code: 'UNAUTHORIZED' });+ });++ it('do not affect tokens for the app API', async () => {+ jwtVerifyMock.mockResolvedValueOnce({+ payload: { aud: 'urn:lobehub:chat', client_id: 'lobehub-desktop', sub: 'user-1' },+ });+ const { validateOIDCJWT } = await import('./jwt');+ await expect(validateOIDCJWT('t')).resolves.toMatchObject({ userId: 'user-1' });+ });++ it('are read back as the acceptance and user they were issued for', async () => {+ jwtVerifyMock.mockResolvedValueOnce({+ payload: { aud: REVIEW_AUD, client_id: 'lobehub-review', exp: 1_800_000_000, sub: 'user-1' },+ });+ const { verifyAcceptanceReviewJWT } = await import('./jwt');+ await expect(verifyAcceptanceReviewJWT('t')).resolves.toEqual({+ acceptanceId: '7f0c9a7e-0000-4000-8000-000000000001',+ expiresAt: 1_800_000_000,+ userId: 'user-1',+ });+ });++ it('reject any other token as a review token', async () => {+ const { verifyAcceptanceReviewJWT } = await import('./jwt');+ jwtVerifyMock.mockResolvedValueOnce({+ payload: { aud: 'urn:lobehub:chat', client_id: 'lobehub-desktop', sub: 'user-1' },+ });+ await expect(verifyAcceptanceReviewJWT('t')).rejects.toThrow();+ jwtVerifyMock.mockResolvedValueOnce({+ payload: { aud: REVIEW_AUD, client_id: 'lobehub-cli', sub: 'user-1' },+ });+ await expect(verifyAcceptanceReviewJWT('t')).rejects.toThrow();+ });+});diff --git a/src/libs/oidc-provider/jwt.ts b/src/libs/oidc-provider/jwt.tsindex b014a7c3747..964db7cdffe 100644--- a/src/libs/oidc-provider/jwt.ts+++ b/src/libs/oidc-provider/jwt.ts@@ -1,8 +1,11 @@+import { acceptanceIdFromReviewResource } from '@lobechat/const';import { TRPCError } from '@trpc/server';import debug from 'debug';import { authEnv } from '@/envs/auth';+import { isAcceptanceReviewClient, isAcceptanceReviewIssued } from './acceptanceReview';+const log = debug('oidc-jwt');/**@@ -129,6 +132,14 @@ export const validateOIDCJWT = async (token: string) => {});}+ // Review tokens live on third-party preview pages; they only open the review API.+ if (isAcceptanceReviewIssued(payload)) {+ throw new TRPCError({+ code: 'UNAUTHORIZED',+ message: 'Acceptance review tokens are not accepted here',+ });+ }+return {clientId,payload,@@ -160,3 +171,13 @@ export const validateOIDCJWT = async (token: string) => {});}};++export const verifyAcceptanceReviewJWT = async (token: string) => {+ const publicKey = await getVerificationKey();+ const { jwtVerify } = await import('jose');+ const { payload } = await jwtVerify(token, publicKey, { algorithms: ['RS256'] });+ const acceptanceId = acceptanceIdFromReviewResource(payload.aud);+ if (!isAcceptanceReviewClient(payload.client_id as string) || !acceptanceId || !payload.sub)+ throw new Error('Not an acceptance review token');+ return { acceptanceId, expiresAt: payload.exp, userId: payload.sub };+};diff --git a/src/libs/oidc-provider/provider.ts b/src/libs/oidc-provider/provider.tsindex f376b952855..9616a3144ae 100644--- a/src/libs/oidc-provider/provider.ts+++ b/src/libs/oidc-provider/provider.ts@@ -10,6 +10,7 @@ import { getJWKS } from '@/libs/oidc-provider/jwt';import { OIDC_ISSUER_PATH, OIDC_ROUTES } from '@/libs/oidc-provider/routes';import { normalizeLocale } from '@/locales/resources';+import { accessTokenTTL, isAcceptanceReviewClient, reviewResourceServer } from './acceptanceReview';import { isOIDCUserBanned } from './access-control';import { DrizzleAdapter } from './adapter';import { defaultClaims, defaultClients, defaultScopes } from './config';@@ -68,6 +69,10 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Provider// Added: client-based CORS control logicclientBasedCORS(ctx, origin, client) {+ // The review toolbar runs on whatever origin the delivered product is+ // previewed on; its token is scoped to one acceptance by audience.+ if (isAcceptanceReviewClient(client?.clientId)) return true;+// Check if the client allows this origin// A common strategy is to allow origins of all registered redirect_urisif (!client || !client.redirectUris) {@@ -146,6 +151,14 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<ProvidergetResourceServerInfo: (ctx, resourceIndicator) => {logProvider('getResourceServerInfo called with indicator: %s', resourceIndicator); // <-- Add this log line+ const review = reviewResourceServer(+ ctx.oidc.client?.clientId,+ resourceIndicator,+ ctx.oidc.params?.resource,+ );+ if (review === 'reject') throw new errors.InvalidTarget();+ if (review) return review;+if (resourceIndicator === API_AUDIENCE) {logProvider('Indicator matches API_AUDIENCE, returning JWT config.'); // <-- Add this log linereturn {@@ -316,7 +329,10 @@ export const createOIDCProvider = async (db: LobeChatDatabase): Promise<Providerscopes: defaultScopes,// 8. Token TTL- ttl: oidcArtifactTTL,+ ttl: {+ ...oidcArtifactTTL,+ AccessToken: (ctx, token) => accessTokenTTL(token, oidcArtifactTTL.AccessToken),+ },};// Create provider instancediff --git a/src/types/oidc.ts b/src/types/oidc.tsindex f06c96821e1..4050b266b77 100644--- a/src/types/oidc.ts+++ b/src/types/oidc.ts@@ -7,6 +7,7 @@ export interface OidcClientMetadata {}export interface OidcInteractionDetailsResponse {+ acceptanceReview?: { allowed: boolean; title?: string };clientId: string;clientMetadata: OidcClientMetadata;prompt: 'consent' | 'login';