Skip to content

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

✨ feat(acceptance): serve the collaboration table, and let a round introduce itself (#19393)

Arvin Xud2caf84fdd9c
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
index 5c8ea90f2b6..412d1377af3 100644
--- a/apps/cli/src/commands/acceptanceRun.ts
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -590,6 +590,20 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
const reportMdPath = path.join(dir, 'report.md');
const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;
+ // What this round is, said to the person who has to accept it, in their
+ // language β€” the delivery's own note, not the verification write-up. It
+ // posts into the discussion as a message from whoever ran the ingest, so a
+ // reviewer reads it where the conversation already is rather than behind a
+ // report link.
+ const proposalMdPath = path.join(dir, 'proposal.md');
+ const proposal = (
+ existsSync(proposalMdPath)
+ ? readFileSync(proposalMdPath, 'utf8')
+ : typeof result.proposal === 'string'
+ ? result.proposal
+ : ''
+ ).trim();
+
// What kind of delivery this report verified (default: coding).
const scenario = scenarioFromResult(result);
@@ -845,6 +859,33 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
verifyRunId: runId,
});
+ // 4. Post the round's note. It renders as part of the round rather than as
+ // another message, so the discussion reads "<agent> shipped round N"
+ // followed by what it says. Last, and never fatal: the round itself is
+ // the deliverable, and a failed comment must not strand a published round
+ // behind an aborted ingest.
+ let proposalPosted = false;
+ if (proposal) {
+ try {
+ await client.acceptanceComment.create.mutate({
+ acceptanceId,
+ // Signed by the agent that produced the round, not by whoever's
+ // credentials carried the ingest. Absent outside an agent run, and
+ // then it falls back to the account.
+ authorAgentId: process.env.LOBEHUB_AGENT_ID || undefined,
+ // Derived from the round, so re-ingesting the same round edits nothing
+ // and duplicates nothing.
+ clientId: `proposal:${runId}`,
+ content: proposal,
+ contextRunId: runId,
+ kind: 'proposal',
+ });
+ proposalPosted = true;
+ } catch (e) {
+ log.warn(`proposal not posted to the discussion: ${String(e)}`);
+ }
+ }
+
// A case with no matching plan item means the run checked something it
// never planned β€” worth saying out loud, but not a failure. Only
// meaningful against a plan that actually names something: with no plan
@@ -864,6 +905,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
inlined,
origin,
planItems: plan?.length ?? 0,
+ proposalPosted,
pullRequest,
roundIndex,
roundUrl,
@@ -890,6 +932,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
`${unplanned.length > 0 ? pc.dim(` β€” ${unplanned.length} unplanned case(s)`) : ''}`,
);
}
+ if (proposalPosted) console.log(`${pc.bold('proposal')}: posted to the discussion`);
if (pullRequest?.url) console.log(`${pc.bold('pr')}: ${pullRequest.url}`);
if (origin?.topicId) console.log(`${pc.bold('origin topic')}: ${origin.topicId}`);
console.log(`${pc.bold('verifyRunId')}: ${runId} ${pc.dim('(immutable snapshot)')}`);
@@ -1048,7 +1091,7 @@ export function attachAcceptanceRunCommands(acceptance: Command): void {
run
.command('ingest <reportDir>')
.description(
- 'Ingest a local agent-testing report (result.json + report.md + assets) as a new round',
+ 'Ingest a local agent-testing report (result.json + report.md + proposal.md + assets) as a new round',
),
).action(ingestReportAction);
diff --git a/apps/cli/src/utils/acceptanceDir.ts b/apps/cli/src/utils/acceptanceDir.ts
index e15252c5168..badae6dde02 100644
--- a/apps/cli/src/utils/acceptanceDir.ts
+++ b/apps/cli/src/utils/acceptanceDir.ts
@@ -13,6 +13,7 @@ import path from 'node:path';
* β”œβ”€β”€ acceptance.json # which acceptance these rounds belong to
* └── <YYYYMMDD-HHMMSS>-<slug>/ # ONE immutable round
* β”œβ”€β”€ result.json
+ * β”œβ”€β”€ proposal.md # optional β€” posted into the discussion
* β”œβ”€β”€ report.md
* └── assets/
* ```
diff --git a/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts b/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts
new file mode 100644
index 00000000000..faeb431da17
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/acceptanceComment.scoping.test.ts
@@ -0,0 +1,149 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { type LobeChatDatabase } from '@lobechat/database';
+import {
+ acceptances,
+ verifyCheckResults,
+ verifyEvidence,
+ verifyRuns,
+} 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, createTestAgent, createTestUser } from './integration/setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+const rect = { height: 0.2, width: 0.3, x: 0.1, y: 0.1 };
+
+/**
+ * A comment carries three references that the schema alone does not constrain:
+ * the agent it speaks as, the round it was written against, and the evidence it
+ * is pinned to. Access is resolved from `acceptanceId`, so each of those has to
+ * be re-checked against that acceptance before it is stored β€” otherwise a
+ * participant of one acceptance can name rows belonging to another.
+ */
+describe('acceptanceCommentRouter create reference scoping', () => {
+ let serverDB: LobeChatDatabase;
+ let ownerId: string;
+ let strangerId: string;
+ let acceptanceId: string;
+ let foreignAcceptanceId: string;
+ let ownAgentId: string;
+ let foreignAgentId: string;
+ let ownRunId: string;
+ let ownEvidenceId: string;
+ let foreignRunId: string;
+ let foreignEvidenceId: string;
+
+ const seedRound = async (targetAcceptanceId: string, userId: string) => {
+ const [run] = await serverDB
+ .insert(verifyRuns)
+ .values({ acceptanceId: targetAcceptanceId, roundIndex: 1, userId })
+ .returning();
+ const [result] = await serverDB
+ .insert(verifyCheckResults)
+ .values({ checkItemId: 'c1', userId, verifierType: 'agent', verifyRunId: run.id })
+ .returning();
+ const [evidence] = await serverDB
+ .insert(verifyEvidence)
+ .values({ checkResultId: result.id, type: 'screenshot', userId })
+ .returning();
+ return { evidenceId: evidence.id, runId: run.id };
+ };
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ ownerId = await createTestUser(serverDB);
+ strangerId = await createTestUser(serverDB);
+ ownAgentId = await createTestAgent(serverDB, ownerId);
+ foreignAgentId = await createTestAgent(serverDB, strangerId);
+
+ const [own, foreign] = await serverDB
+ .insert(acceptances)
+ .values([
+ { subjectId: randomUUID(), subjectType: 'standalone', userId: ownerId },
+ { subjectId: randomUUID(), subjectType: 'standalone', userId: strangerId },
+ ])
+ .returning();
+ acceptanceId = own.id;
+ foreignAcceptanceId = foreign.id;
+
+ ({ evidenceId: ownEvidenceId, runId: ownRunId } = await seedRound(acceptanceId, ownerId));
+ ({ evidenceId: foreignEvidenceId, runId: foreignRunId } = await seedRound(
+ foreignAcceptanceId,
+ strangerId,
+ ));
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, strangerId);
+ await cleanupTestUser(serverDB, ownerId);
+ vi.clearAllMocks();
+ });
+
+ const caller = (userId: string) =>
+ acceptanceCommentRouter.createCaller({ jwtPayload: { userId }, userId } as any);
+
+ it('rejects an agent the caller cannot use', async () => {
+ await expect(
+ caller(ownerId).create({
+ acceptanceId,
+ authorAgentId: foreignAgentId,
+ clientId: `c-${randomUUID()}`,
+ content: 'signed as someone else',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('attributes an agent the caller owns', async () => {
+ const { data } = await caller(ownerId).create({
+ acceptanceId,
+ authorAgentId: ownAgentId,
+ clientId: `c-${randomUUID()}`,
+ content: 'signed as my own agent',
+ });
+
+ expect(data.author).toMatchObject({ id: ownAgentId, type: 'agent' });
+ });
+
+ it('rejects a round belonging to another acceptance', async () => {
+ await expect(
+ caller(ownerId).create({
+ acceptanceId,
+ clientId: `c-${randomUUID()}`,
+ content: 'quoting a foreign round',
+ contextRunId: foreignRunId,
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('rejects evidence belonging to another acceptance', async () => {
+ await expect(
+ caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: foreignEvidenceId, rect },
+ clientId: `c-${randomUUID()}`,
+ content: 'pinned to foreign evidence',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('accepts the acceptance own round and evidence', async () => {
+ const { data } = await caller(ownerId).create({
+ acceptanceId,
+ anchor: { checkItemId: 'c1', evidenceId: ownEvidenceId, rect },
+ clientId: `c-${randomUUID()}`,
+ content: 'pinned to my own evidence',
+ contextRunId: ownRunId,
+ });
+
+ expect(data).toMatchObject({ contextRoundIndex: 1, evidenceId: ownEvidenceId });
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts b/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
new file mode 100644
index 00000000000..3ef5028cc46
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
@@ -0,0 +1,50 @@
+import { TRPCError } from '@trpc/server';
+import { eq } from 'drizzle-orm';
+
+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
+import type { AcceptanceItem } from '@/database/schemas/verify';
+import { acceptances } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+import { isUuid } from '@/database/utils/uuid';
+
+export interface AcceptanceCommentAccess {
+ acceptance: AcceptanceItem;
+ /** May write comments / approvals: the creator, or a non-viewer member of the acceptance's workspace. */
+ canComment: boolean;
+ isOwner: boolean;
+}
+
+/**
+ * Who may take part in an acceptance's discussion.
+ *
+ * Reading follows the bundle: the creator, anyone when the acceptance is
+ * `public`, or a member of the acceptance's OWN workspace (not the caller's
+ * active one). Writing is narrower β€” a public link lets a visitor read the
+ * discussion, never join it β€” and mirrors the write procedure's member gate:
+ * workspace viewers stay read-only. A personal-scope acceptance has no
+ * collaborators, so only its creator can write there.
+ *
+ * Missing access reads as NOT_FOUND, like the bundle, so existence never leaks.
+ */
+export async function resolveAcceptanceCommentAccess(
+ db: LobeChatDatabase,
+ userId: string | null | undefined,
+ acceptanceId: string,
+): Promise<AcceptanceCommentAccess> {
+ const [acceptance] = isUuid(acceptanceId)
+ ? await db.select().from(acceptances).where(eq(acceptances.id, acceptanceId)).limit(1)
+ : [];
+ if (!acceptance) throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });
+
+ const isOwner = Boolean(userId) && userId === acceptance.userId;
+ const member =
+ !isOwner && userId && acceptance.workspaceId
+ ? await new WorkspaceMemberModel(db, userId).getMember(acceptance.workspaceId, userId)
+ : undefined;
+
+ const canRead = isOwner || acceptance.visibility === 'public' || Boolean(member);
+ if (!canRead) throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });
+
+ const canComment = isOwner || (Boolean(member) && member!.role !== 'viewer');
+ return { acceptance, canComment, isOwner };
+}
diff --git a/apps/server/src/routers/lambda/acceptanceComment.ts b/apps/server/src/routers/lambda/acceptanceComment.ts
new file mode 100644
index 00000000000..d2182256260
--- /dev/null
+++ b/apps/server/src/routers/lambda/acceptanceComment.ts
@@ -0,0 +1,481 @@
+import type {
+ AcceptanceAttachment,
+ AcceptanceCommentAuthor,
+ AcceptanceCommentItem,
+ AcceptanceCommentList,
+ AcceptanceCommentReaction,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { and, eq, inArray, isNull } from 'drizzle-orm';
+import { z } from 'zod';
+
+import {
+ ACCEPTANCE_COMMENT_PARENT_NOT_FOUND,
+ AcceptanceCommentModel,
+ acceptanceReactionClientId,
+} from '@/database/models/acceptanceComment';
+import {
+ agents,
+ users,
+ verifyCheckResults,
+ verifyEvidence,
+ verifyRuns,
+ workspaceMembers,
+} from '@/database/schemas';
+import type { AcceptanceCommentRow } from '@/database/schemas/acceptanceComment';
+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 { createEvidenceFileResolver } from '@/server/services/verify/evidenceFiles';
+
+import { resolveAcceptanceCommentAccess } from './_helpers/acceptanceCommentAccess';
+
+const rectSchema = z.object({
+ height: z.number().min(0).max(1),
+ width: z.number().min(0).max(1),
+ x: z.number().min(0).max(1),
+ y: z.number().min(0).max(1),
+});
+
+const createSchema = z
+ .object({
+ acceptanceId: z.string().min(1),
+ anchor: z
+ .object({
+ checkItemId: z.string().min(1).max(255),
+ evidenceId: z.string().uuid(),
+ rect: rectSchema,
+ })
+ .optional(),
+ attachments: z
+ .array(z.object({ fileId: z.string().trim().min(1).max(255) }))
+ .max(9)
+ .optional(),
+ authorAgentId: z.string().trim().min(1).max(255).optional(),
+ clientId: z.string().trim().min(1).max(255),
+ content: z.string().trim().max(10_000),
+ contextRunId: z.string().uuid().optional(),
+ // The editor's own tree β€” schemaless by nature, and never interpreted here.
+ editorData: z.unknown().optional(),
+ kind: z.enum(['approval', 'comment', 'proposal']).optional(),
+ parentCommentId: z.string().trim().min(1).max(64).optional(),
+ })
+ .refine(
+ (value) =>
+ value.kind === 'approval' || value.content.length > 0 || (value.attachments?.length ?? 0) > 0,
+ // A screenshot on its own is a complete remark β€” "this is what I see".
+ { message: 'Comment content is required', path: ['content'] },
+ )
+ .refine((value) => !(value.parentCommentId && value.anchor), {
+ message: 'A reply cannot carry its own anchor',
+ path: ['anchor'],
+ })
+ .refine((value) => !(value.parentCommentId && value.kind === 'approval'), {
+ message: 'An approval is a thread root',
+ path: ['kind'],
+ })
+ .refine((value) => value.kind !== 'proposal' || Boolean(value.contextRunId), {
+ message: "A proposal belongs to a round, so it needs that round's id",
+ path: ['contextRunId'],
+ });
+
+/** Reads addressed purely by acceptance id β€” visibility is checked in the handler. */
+const readProcedure = publicProcedure
+ .use(serverDatabase)
+ .use(async ({ ctx, next }) =>
+ next({ ctx: { acceptanceCommentModel: new AcceptanceCommentModel(ctx.serverDB) } }),
+ );
+
+const writeProcedure = authedProcedure
+ .use(serverDatabase)
+ .use(async ({ ctx, next }) =>
+ next({ ctx: { acceptanceCommentModel: new AcceptanceCommentModel(ctx.serverDB) } }),
+ );
+
+const deactivatedAuthor: AcceptanceCommentAuthor = {
+ avatar: null,
+ fullName: null,
+ id: null,
+ status: 'deactivated',
+ type: 'user',
+ username: null,
+};
+
+/**
+ * Join author profiles and round indexes onto raw rows. Membership status is
+ * read against the acceptance's own workspace so a departed teammate renders
+ * as `former` rather than vanishing from the discussion.
+ */
+const enrich = async (
+ db: LobeChatDatabase,
+ rows: AcceptanceCommentRow[],
+ scope: { ownerUserId: string; userId?: string | null; workspaceId: string | null },
+): Promise<AcceptanceCommentItem[]> => {
+ const authorIds = [
+ ...new Set(rows.flatMap((row) => (row.authorUserId ? [row.authorUserId] : []))),
+ ];
+ const runIds = [...new Set(rows.flatMap((row) => (row.contextRunId ? [row.contextRunId] : [])))];
+ const agentIds = [
+ ...new Set(rows.flatMap((row) => (row.authorAgentId ? [row.authorAgentId] : []))),
+ ];
+ // Resolved as the acceptance's owner, the way the bundle resolves evidence and
+ // reject attachments: the uploader may be a reviewer, and the visibility gate
+ // has already been applied above.
+ const attachmentIds = [
+ ...new Set(rows.flatMap((row) => (row.attachments ?? []).map((item) => item.fileId))),
+ ];
+ const resolveFile = createEvidenceFileResolver(
+ db,
+ scope.ownerUserId,
+ scope.workspaceId ?? undefined,
+ );
+ const fileById = new Map<string, AcceptanceAttachment>(
+ await Promise.all(
+ attachmentIds.map(async (id): Promise<[string, AcceptanceAttachment]> => {
+ const meta = await resolveFile(id);
+ return [id, { id, name: meta.fileName ?? undefined, url: meta.fileUrl }];
+ }),
+ ),
+ );
+
+ const [profiles, memberships, runs, agentRows] = await Promise.all([
+ authorIds.length
+ ? db
+ .select({
+ avatar: users.avatar,
+ fullName: users.fullName,
+ id: users.id,
+ username: users.username,
+ })
+ .from(users)
+ .where(inArray(users.id, authorIds))
+ : [],
+ authorIds.length && scope.workspaceId
+ ? db
+ .select({ userId: workspaceMembers.userId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, scope.workspaceId),
+ inArray(workspaceMembers.userId, authorIds),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ )
+ : [],
+ runIds.length
+ ? db
+ .select({ id: verifyRuns.id, roundIndex: verifyRuns.roundIndex })
+ .from(verifyRuns)
+ .where(inArray(verifyRuns.id, runIds))
+ : [],
+ agentIds.length
+ ? db
+ .select({ avatar: agents.avatar, id: agents.id, name: agents.name, title: agents.title })
+ .from(agents)
+ .where(inArray(agents.id, agentIds))
+ : [],
+ ]);
+
+ const profileById = new Map(profiles.map((profile) => [profile.id, profile]));
+ const activeIds = new Set(memberships.map(({ userId }) => userId));
+ const roundByRun = new Map(runs.map((run) => [run.id, run.roundIndex]));
+ const agentById = new Map(agentRows.map((agent) => [agent.id, agent]));
+
+ /**
+ * An agent-signed row shows the agent. The account whose key carried it is
+ * still recorded and still governs deletion β€” it is just not who "said" it,
+ * any more than a bot comment on a pull request is attributed to the token
+ * holder.
+ */
+ const getAuthor = (
+ authorUserId: string | null,
+ authorAgentId?: string | null,
+ ): AcceptanceCommentAuthor => {
+ const agent = authorAgentId ? agentById.get(authorAgentId) : undefined;
+ if (agent)
+ return {
+ avatar: agent.avatar,
+ fullName: agent.name ?? agent.title ?? null,
+ id: agent.id,
+ status: 'active',
+ type: 'agent',
+ username: null,
+ };
+ const profile = authorUserId ? profileById.get(authorUserId) : undefined;
+ if (!profile) return deactivatedAuthor;
+ // Without a workspace there is no membership to lapse from.
+ const active = !scope.workspaceId || activeIds.has(profile.id);
+ return { ...profile, status: active ? 'active' : 'former', type: 'user' as const };
+ };
+
+ // Reaction rows are folded into the comment they answer and never surface as
+ // items of their own: the page renders chips, not one-emoji messages.
+ const authorLabel = (authorUserId: string | null) => {
+ const author = getAuthor(authorUserId);
+ return author.fullName || author.username || '';
+ };
+ const reactionsByComment = new Map<string, Map<string, AcceptanceCommentReaction>>();
+ for (const row of rows) {
+ if (row.kind !== 'reaction' || !row.parentCommentId || row.deletedAt) continue;
+ const byEmoji = reactionsByComment.get(row.parentCommentId) ?? new Map();
+ const current = byEmoji.get(row.content) ?? {
+ authorNames: [],
+ count: 0,
+ emoji: row.content,
+ mine: false,
+ };
+ const name = authorLabel(row.authorUserId);
+ byEmoji.set(row.content, {
+ authorNames: name ? [...current.authorNames, name] : current.authorNames,
+ count: current.count + 1,
+ emoji: row.content,
+ mine: current.mine || (Boolean(scope.userId) && row.authorUserId === scope.userId),
+ });
+ reactionsByComment.set(row.parentCommentId, byEmoji);
+ }
+
+ return rows
+ .filter((row) => row.kind !== 'reaction')
+ .map((row) => ({
+ acceptanceId: row.acceptanceId,
+ anchorType: row.anchorType,
+ attachments: (row.attachments ?? []).flatMap((item) => {
+ const file = fileById.get(item.fileId);
+ return file ? [file] : [];
+ }),
+ author: getAuthor(row.authorUserId, row.authorAgentId),
+ authorAgentId: row.authorAgentId,
+ authorUserId: row.authorUserId,
+ canDelete: !row.deletedAt && Boolean(scope.userId) && row.authorUserId === scope.userId,
+ checkItemId: row.checkItemId,
+ clientId: row.clientId,
+ content: row.content,
+ contextRoundIndex: row.contextRunId ? (roundByRun.get(row.contextRunId) ?? null) : null,
+ contextRunId: row.contextRunId,
+ createdAt: row.createdAt,
+ deletedAt: row.deletedAt,
+ editorData: row.editorData ?? null,
+ evidenceId: row.evidenceId,
+ id: row.id,
+ kind: row.kind,
+ parentCommentId: row.parentCommentId,
+ reactions: [...(reactionsByComment.get(row.id)?.values() ?? [])],
+ rect: row.anchorRect,
+ resolvedAt: row.resolvedAt,
+ resolvedByUserId: row.resolvedByUserId,
+ updatedAt: row.updatedAt,
+ }));
+};
+
+const requireComment = async (
+ ctx: {
+ acceptanceCommentModel: AcceptanceCommentModel;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ },
+ id: string,
+) => {
+ const comment = await ctx.acceptanceCommentModel.findById(id);
+ if (!comment) throw new TRPCError({ code: 'NOT_FOUND', message: 'Comment not found' });
+ const access = await resolveAcceptanceCommentAccess(
+ ctx.serverDB,
+ ctx.userId,
+ comment.acceptanceId,
+ );
+ if (!access.canComment) throw new TRPCError({ code: 'FORBIDDEN', message: 'Read-only access' });
+ return { access, comment };
+};
+
+/**
+ * A comment may only speak as an agent the caller is actually allowed to use.
+ *
+ * `author_agent_id` decides whose name, title and avatar the discussion shows,
+ * and a public acceptance shows it to anyone with the link. Without this gate a
+ * participant could name any agent id that exists and impersonate it. The scope
+ * is the acceptance's own workspace, because that is the audience the agent is
+ * being presented to.
+ */
+const assertAuthorAgentUsable = async (
+ db: LobeChatDatabase,
+ ctx: { userId: string; workspaceId?: string },
+ agentId?: string,
+) => {
+ if (!agentId) return;
+ try {
+ await assertAgentUsableBy(db, agentId, ctx);
+ } catch (error) {
+ if (error instanceof TRPCError && error.code === 'NOT_FOUND')
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Author agent not found' });
+ throw error;
+ }
+};
+
+/**
+ * A comment may only point at a round or an evidence tile of its own acceptance.
+ *
+ * The foreign keys prove these ids exist somewhere in the database; they say
+ * nothing about which acceptance they hang off. Access is checked against
+ * `acceptanceId` alone, so an unscoped reference would let a participant pull a
+ * round index or an evidence anchor out of an acceptance they cannot read.
+ */
+const assertReferencesBelongToAcceptance = async (
+ db: LobeChatDatabase,
+ acceptanceId: string,
+ refs: { evidenceId?: string; runId?: string },
+) => {
+ if (refs.runId) {
+ const [run] = await db
+ .select({ id: verifyRuns.id })
+ .from(verifyRuns)
+ .where(and(eq(verifyRuns.id, refs.runId), eq(verifyRuns.acceptanceId, acceptanceId)))
+ .limit(1);
+ if (!run) throw new TRPCError({ code: 'NOT_FOUND', message: 'Round not found' });
+ }
+
+ if (refs.evidenceId) {
+ const [evidence] = await db
+ .select({ id: verifyEvidence.id })
+ .from(verifyEvidence)
+ .innerJoin(verifyCheckResults, eq(verifyCheckResults.id, verifyEvidence.checkResultId))
+ .innerJoin(verifyRuns, eq(verifyRuns.id, verifyCheckResults.verifyRunId))
+ .where(and(eq(verifyEvidence.id, refs.evidenceId), eq(verifyRuns.acceptanceId, acceptanceId)))
+ .limit(1);
+ if (!evidence) throw new TRPCError({ code: 'NOT_FOUND', message: 'Evidence not found' });
+ }
+};
+
+export const acceptanceCommentRouter = router({
+ create: writeProcedure.input(createSchema).mutation(async ({ ctx, input }) => {
+ const access = await resolveAcceptanceCommentAccess(
+ ctx.serverDB,
+ ctx.userId,
+ input.acceptanceId,
+ );
+ if (!access.canComment) throw new TRPCError({ code: 'FORBIDDEN', message: 'Read-only access' });
+
+ await assertAuthorAgentUsable(
+ ctx.serverDB,
+ { userId: ctx.userId, workspaceId: access.acceptance.workspaceId ?? undefined },
+ input.authorAgentId,
+ );
+ await assertReferencesBelongToAcceptance(ctx.serverDB, access.acceptance.id, {
+ evidenceId: input.anchor?.evidenceId,
+ runId: input.contextRunId,
+ });
+
+ try {
+ const { comment } = await ctx.acceptanceCommentModel.create({
+ acceptanceId: access.acceptance.id,
+ anchor: input.anchor,
+ attachments: input.attachments,
+ authorAgentId: input.authorAgentId,
+ authorUserId: ctx.userId,
+ clientId: input.clientId,
+ content: input.content,
+ contextRunId: input.contextRunId,
+ editorData: input.editorData as never,
+ kind: input.kind,
+ parentCommentId: input.parentCommentId,
+ workspaceId: access.acceptance.workspaceId,
+ });
+ const [item] = await enrich(ctx.serverDB, [comment], {
+ ownerUserId: access.acceptance.userId,
+ userId: ctx.userId,
+ workspaceId: access.acceptance.workspaceId,
+ });
+ return { data: item, success: true };
+ } catch (error) {
+ if (error instanceof TRPCError) throw error;
+ if (error instanceof Error && error.message === ACCEPTANCE_COMMENT_PARENT_NOT_FOUND)
+ throw new TRPCError({ code: 'NOT_FOUND', message: error.message });
+ console.error('[acceptanceComment:create]', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to create comment',
+ });
+ }
+ }),
+
+ delete: writeProcedure
+ .input(z.object({ id: z.string().min(1) }))
+ .mutation(async ({ ctx, input }) => {
+ const { comment } = await requireComment(ctx, input.id);
+ if (comment.authorUserId !== ctx.userId)
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Only the author may delete' });
+ const result = await ctx.acceptanceCommentModel.delete(comment.id, ctx.userId);
+ return { data: { deleted: result !== false }, success: true };
+ }),
+
+ list: readProcedure
+ .input(z.object({ acceptanceId: z.string().min(1) }))
+ .query(async ({ ctx, input }): Promise<AcceptanceCommentList> => {
+ const access = await resolveAcceptanceCommentAccess(
+ ctx.serverDB,
+ ctx.userId,
+ input.acceptanceId,
+ );
+ const rows = await ctx.acceptanceCommentModel.listByAcceptance(access.acceptance.id);
+ const items = await enrich(ctx.serverDB, rows, {
+ ownerUserId: access.acceptance.userId,
+ userId: ctx.userId,
+ workspaceId: access.acceptance.workspaceId,
+ });
+ return { canComment: access.canComment, items };
+ }),
+
+ /**
+ * Toggle the caller's own emoji on one comment. Idempotent both ways: the
+ * key is derived from (comment, emoji), so a double-click adds nothing and a
+ * second removal deletes nothing.
+ */
+ react: writeProcedure
+ .input(
+ z.object({
+ emoji: z.string().trim().min(1).max(16),
+ id: z.string().min(1),
+ on: z.boolean(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { access, comment } = await requireComment(ctx, input.id);
+ if (comment.kind === 'reaction')
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Cannot react to a reaction' });
+
+ if (!input.on) {
+ await ctx.acceptanceCommentModel.removeReaction({
+ acceptanceId: comment.acceptanceId,
+ authorUserId: ctx.userId,
+ commentId: comment.id,
+ emoji: input.emoji,
+ });
+ return { data: { on: false }, success: true };
+ }
+
+ await ctx.acceptanceCommentModel.create({
+ acceptanceId: comment.acceptanceId,
+ authorUserId: ctx.userId,
+ clientId: acceptanceReactionClientId(comment.id, input.emoji),
+ content: input.emoji,
+ kind: 'reaction',
+ parentCommentId: comment.id,
+ workspaceId: access.acceptance.workspaceId,
+ });
+ return { data: { on: true }, success: true };
+ }),
+
+ setResolved: writeProcedure
+ .input(z.object({ id: z.string().min(1), resolved: z.boolean() }))
+ .mutation(async ({ ctx, input }) => {
+ const { comment } = await requireComment(ctx, input.id);
+ if (comment.parentCommentId)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Only a thread root can be resolved' });
+ const row = await ctx.acceptanceCommentModel.setResolved(
+ comment.id,
+ input.resolved,
+ ctx.userId,
+ );
+ return { data: { resolvedAt: row?.resolvedAt ?? null }, success: true };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 5ab8e409e36..a2c99c6cd77 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -21,6 +21,7 @@ import { workspaceUsageRouter } from '@/business/server/lambda-routers/workspace
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { acceptanceRouter } from './acceptance';
+import { acceptanceCommentRouter } from './acceptanceComment';
import { agentRouter } from './agent';
import { agentBotProviderRouter } from './agentBotProvider';
import { agentDocumentRouter } from './agentDocument';
@@ -104,6 +105,7 @@ import { workspaceUserSettingsRouter } from './workspaceUserSettings';
export const lambdaRouter = router({
acceptance: acceptanceRouter,
+ acceptanceComment: acceptanceCommentRouter,
agent: agentRouter,
agentBotProvider: agentBotProviderRouter,
agentNotify: agentNotifyRouter,
diff --git a/packages/builtin-skills/src/acceptance/references/report.md b/packages/builtin-skills/src/acceptance/references/report.md
index 6a00054684f..ea321837c44 100644
--- a/packages/builtin-skills/src/acceptance/references/report.md
+++ b/packages/builtin-skills/src/acceptance/references/report.md
@@ -75,6 +75,7 @@ Rounds live under `.acceptances/`, grouped by the delivery they belong to:
β”œβ”€β”€ acceptance.json # which acceptance these rounds belong to
└── <YYYYMMDD-HHMMSS>-<slug>/ # ONE round β€” never write into an existing one
β”œβ”€β”€ result.json # THE report β€” the page renders from this
+ β”œβ”€β”€ proposal.md # what this round delivers, posted to the discussion
β”œβ”€β”€ report.md # narrative tail only (verdict, follow-ups, score)
└── assets/ # evidence referenced from cases[].evidence
```
@@ -134,10 +135,20 @@ supersedes? }`.
4. **Set `title` and `summary.verdict`** (`pass` / `fail` / `partial`) β€” without
them the run lists as "ζœͺ命名ιͺŒθ―" with a permanent amber "?" glyph. Write the
one-paragraph verdict into `summary.conclusion`.
-5. **`report.md` is the narrative tail only** β€” this-round notes, follow-ups,
+5. **Write `proposal.md` β€” the round's own note to the reviewer.** What this
+ round delivers and where you want their eyes, the way a person writes a pull
+ request description: a few sentences, in the language the user is conversing
+ in. `ingest` posts it into the acceptance's discussion as a message on this
+ round, so it is the first thing a reviewer reads and they can answer it in
+ place. It is NOT the verification write-up β€” do not restate the checks or the
+ verdict, those are `result.json` and `report.md`. Every round gets one: the
+ first says what the delivery is, later ones say what changed since the
+ feedback. Skip it only when there is genuinely nothing to say beyond the
+ checks.
+6. **`report.md` is the narrative tail only** β€” this-round notes, follow-ups,
score. Do NOT repeat the scope block or a case table; those double up on the
page. Write it in the language the user is conversing in.
-6. **Review, then publish:** hand the completed plan, report, original evidence,
+7. **Review, then publish:** hand the completed plan, report, original evidence,
and an explicit file list with relevant diff text or prepared diff artifact
paths (including in-round repairs, base and tested revision, and affected case IDs)
to the acceptance-checker for a quick evidence review using [acceptance-checker.md](acceptance-checker.md)
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index d9a8bb7dd60..f26f537aae6 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -170,6 +170,8 @@ const rw = (read: ApiKeyScope | null, write: ApiKeyScope | null): TrpcNamespaceS
export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule> = {
accountDeletion: 'blocked',
acceptance: 'blocked',
+ // the discussion on an acceptance follows the acceptance itself
+ acceptanceComment: 'blocked',
agent: rw('agent:read', 'agent:write'),
// bot channel wiring carries channel credentials
agentBotProvider: 'blocked',