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): let reviewers request edit-collaboration on a delivery (#21496)

LiJiand663e83e7c3d
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.ts
index d5e2903833d..f00ea661a72 100644
--- a/apps/server/src/router-hono/acceptance-review/__tests__/app.test.ts
+++ b/apps/server/src/router-hono/acceptance-review/__tests__/app.test.ts
@@ -200,7 +200,7 @@ describe('GET /session', () => {
status: 'delivered',
title: 'Billing redesign',
},
- can: { comment: true, decide: true, moderate: true },
+ can: { comment: true, decide: true, moderate: true, reject: true },
expiresAt: new Date(2_000_000_000 * 1000).toISOString(),
user: { id: ownerId, name: 'Olivia Owner' },
});
@@ -209,7 +209,7 @@ describe('GET /session', () => {
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.can).toEqual({ comment: true, decide: false, moderate: false, reject: false });
expect(body.user).toMatchObject({ id: visitorId, name: 'vic' });
});
});
@@ -357,6 +357,58 @@ describe('POST /decision', () => {
expect(await res.json()).toEqual({ status: 'accepted' });
});
+ it('lets a visitor granted reject access send it back as the owner, but not accept', async () => {
+ await serverDB.insert(acceptanceComments).values({
+ acceptanceId,
+ authorUserId: visitorId,
+ clientId: randomUUID(),
+ content: 'the pay button still overlaps',
+ kind: 'access_request',
+ metadata: {
+ accessRequest: { decidedByUserId: ownerId, permission: 'collaborate', status: 'granted' },
+ },
+ });
+
+ const session = await (await call(visitorId, '/session')).json();
+ expect(session.can).toMatchObject({ decide: false, reject: true });
+
+ const accept = await call(visitorId, '/decision', {
+ json: { verdict: 'accept' },
+ method: 'POST',
+ });
+ expect(accept.status).toBe(403);
+
+ const res = await call(visitorId, '/decision', {
+ json: { note: 'still overlaps', verdict: 'send_back' },
+ method: 'POST',
+ });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ dispatched: false, status: 'rejected' });
+ // The repair runs the owner's agent, so it is dispatched as the owner.
+ expect(mocks.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: ownerId }),
+ expect.anything(),
+ expect.objectContaining({ id: acceptanceId }),
+ 'still overlaps',
+ );
+ });
+
+ it('stops honouring a grant once it is revoked', async () => {
+ await serverDB.insert(acceptanceComments).values({
+ acceptanceId,
+ authorUserId: visitorId,
+ clientId: randomUUID(),
+ content: '',
+ kind: 'access_request',
+ metadata: { accessRequest: { permission: 'collaborate', status: 'revoked' } },
+ });
+ const res = await call(visitorId, '/decision', {
+ json: { verdict: 'send_back' },
+ method: 'POST',
+ });
+ expect(res.status).toBe(403);
+ });
+
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' },
diff --git a/apps/server/src/router-hono/acceptance-review/handlers.ts b/apps/server/src/router-hono/acceptance-review/handlers.ts
index e4cc6338496..29657345714 100644
--- a/apps/server/src/router-hono/acceptance-review/handlers.ts
+++ b/apps/server/src/router-hono/acceptance-review/handlers.ts
@@ -133,7 +133,8 @@ export const decide = async (c: ReviewContext) => {
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');
+ if (!(verdict === 'accept' ? can.decide : can.reject))
+ return reviewError(c, 403, 'FORBIDDEN', 'Not allowed to decide this acceptance');
const open = verdict === 'accept' ? ['delivered'] : ['delivered', 'errored'];
if (!open.includes(acceptance.status))
diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.collaboration.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.collaboration.test.ts
new file mode 100644
index 00000000000..4cc97cc5772
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/acceptance.collaboration.test.ts
@@ -0,0 +1,204 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import type { LobeChatDatabase } from '@lobechat/database';
+import {
+ acceptanceComments,
+ acceptances,
+ agentOperations,
+ agents,
+ messages,
+ topics,
+ 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 { acceptanceRouter } from '../acceptance';
+import { cleanupTestUser, createTestContext, createTestUser } from './integration/setup';
+
+let serverDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => serverDB }));
+vi.mock('@/server/services/file', () => ({
+ FileService: class {
+ getFileAccessUrl = async ({ url }: { url?: string | null }) => url ?? '';
+ },
+}));
+const mockExecAgent = vi.fn();
+const aiAgentScopes: unknown[][] = [];
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function (...args: unknown[]) {
+ aiAgentScopes.push(args);
+ return { execAgent: mockExecAgent };
+ }),
+}));
+
+/**
+ * Edit-collaboration hands a reader the owner's conversation for one
+ * acceptance: they read it and talk to its agent, and everything they start
+ * runs as the owner. Without the grant, none of it is reachable.
+ */
+describe('acceptanceRouter collaboration', () => {
+ let ownerId: string;
+ let collaboratorId: string;
+ let acceptanceId: string;
+ let agentId: string;
+ let topicId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ ownerId = await createTestUser(serverDB);
+ collaboratorId = await createTestUser(serverDB);
+ await serverDB
+ .update(users)
+ .set({ fullName: 'Canis Reviewer' })
+ .where(eq(users.id, collaboratorId));
+
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Landing Builder', userId: ownerId })
+ .returning();
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ agentId: agent.id, title: 'Simplify the project home', userId: ownerId })
+ .returning();
+ agentId = agent.id;
+ topicId = topic.id;
+ await serverDB.insert(messages).values({
+ agentId,
+ content: 'Round 1 is ready for review.',
+ role: 'assistant',
+ topicId,
+ userId: ownerId,
+ });
+
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({
+ status: 'delivered',
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'public',
+ })
+ .returning();
+ acceptanceId = acceptance.id;
+ await serverDB.insert(verifyRuns).values({
+ acceptanceId,
+ metadata: { origin: { agentId, topicId } },
+ roundIndex: 1,
+ status: 'passed',
+ userId: ownerId,
+ });
+ });
+
+ afterEach(async () => {
+ mockExecAgent.mockReset();
+ aiAgentScopes.length = 0;
+ await cleanupTestUser(serverDB, collaboratorId);
+ await cleanupTestUser(serverDB, ownerId);
+ });
+
+ const grant = (status: 'granted' | 'revoked' = 'granted') =>
+ serverDB.insert(acceptanceComments).values({
+ acceptanceId,
+ authorUserId: collaboratorId,
+ clientId: randomUUID(),
+ content: '',
+ kind: 'access_request',
+ metadata: { accessRequest: { permission: 'collaborate', status } },
+ });
+
+ const caller = (userId: string) => acceptanceRouter.createCaller(createTestContext(userId));
+
+ it('keeps the conversation from a reader who was never granted collaboration', async () => {
+ await expect(
+ caller(collaboratorId).getOriginConversation({ id: acceptanceId }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(
+ caller(collaboratorId).sendToOriginAgent({ content: 'hi', id: acceptanceId }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('stops honouring a revoked grant', async () => {
+ await grant('revoked');
+
+ await expect(
+ caller(collaboratorId).getOriginConversation({ id: acceptanceId }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('shows a collaborator the bound conversation, without the owner’s identity', async () => {
+ await grant();
+
+ const result = await caller(collaboratorId).getOriginConversation({ id: acceptanceId });
+
+ expect(result.running).toBe(false);
+ expect(result.agentId).toBe(agentId);
+ expect(result.messages.map((message) => message.content)).toContain(
+ 'Round 1 is ready for review.',
+ );
+ expect(result.messages.every((message) => !(message as any).sender)).toBe(true);
+ });
+
+ it('tells a collaborator what conversation they can talk in, but never its ids', async () => {
+ await grant();
+
+ const bundle = await caller(collaboratorId).getBundle({ id: acceptanceId });
+
+ expect(bundle).toMatchObject({
+ canCollaborate: true,
+ canReject: true,
+ canReview: false,
+ collaboration: {
+ agent: { title: 'Landing Builder' },
+ topicTitle: 'Simplify the project home',
+ },
+ origin: null,
+ repairDispatchAvailable: true,
+ });
+ expect(JSON.stringify(bundle.collaboration)).not.toContain(topicId);
+ });
+
+ it('sends a collaborator’s message to the owner’s agent, as the owner, signed by them', async () => {
+ await grant();
+ mockExecAgent.mockResolvedValue({ operationId: 'op_collab' });
+
+ const result = await caller(collaboratorId).sendToOriginAgent({
+ content: 'Keep only chat and task in the composer',
+ id: acceptanceId,
+ });
+
+ expect(result).toEqual({ operationId: 'op_collab' });
+ expect(aiAgentScopes.at(-1)?.[1]).toBe(ownerId);
+ expect(mockExecAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId, appContext: { topicId } }),
+ );
+ const prompt = mockExecAgent.mock.calls[0][0].prompt as string;
+ expect(prompt).toContain('Canis Reviewer');
+ expect(prompt).toContain('Keep only chat and task in the composer');
+ });
+
+ it('refuses a second message while the agent is still replying', async () => {
+ await grant();
+ await serverDB
+ .insert(agentOperations)
+ .values({ id: `op_${randomUUID()}`, status: 'running', topicId, userId: ownerId });
+
+ await expect(
+ caller(collaboratorId).sendToOriginAgent({ content: 'one more thing', id: acceptanceId }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ expect(mockExecAgent).not.toHaveBeenCalled();
+ await expect(
+ caller(collaboratorId).getOriginConversation({ id: acceptanceId }),
+ ).resolves.toMatchObject({ running: true });
+ });
+
+ it('leaves the owner on their own chat', async () => {
+ await expect(caller(ownerId).getOriginConversation({ id: acceptanceId })).rejects.toMatchObject(
+ { code: 'FORBIDDEN' },
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/acceptanceComment.accessRequest.test.ts b/apps/server/src/routers/lambda/__tests__/acceptanceComment.accessRequest.test.ts
new file mode 100644
index 00000000000..95b7d4c075f
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/acceptanceComment.accessRequest.test.ts
@@ -0,0 +1,193 @@
+// @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 { AcceptanceCommentModel } from '@/database/models/acceptanceComment';
+
+import { acceptanceCommentRouter } from '../acceptanceComment';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => testDB),
+}));
+
+/**
+ * Someone who may only remark on an acceptance can ask its deciders for the
+ * right to send it back. The request is a discussion turn; the answer is
+ * server-owned state the reject path reads.
+ */
+describe('acceptanceCommentRouter access requests', () => {
+ let serverDB: LobeChatDatabase;
+ let ownerId: string;
+ let visitorId: string;
+ let publicAcceptanceId: string;
+ let privateAcceptanceId: string;
+ let gateAcceptanceId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ ownerId = await createTestUser(serverDB);
+ visitorId = await createTestUser(serverDB);
+
+ const [open, closed, gate] = await serverDB
+ .insert(acceptances)
+ .values([
+ {
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'public',
+ },
+ {
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'private',
+ },
+ {
+ subjectId: randomUUID(),
+ subjectType: 'goal_gate',
+ userId: ownerId,
+ visibility: 'public',
+ },
+ ])
+ .returning();
+ publicAcceptanceId = open.id;
+ privateAcceptanceId = closed.id;
+ gateAcceptanceId = gate.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, visitorId);
+ await cleanupTestUser(serverDB, ownerId);
+ vi.clearAllMocks();
+ });
+
+ const caller = (userId: string) =>
+ acceptanceCommentRouter.createCaller({ jwtPayload: { userId }, userId } as any);
+
+ const request = (userId: string, acceptanceId = publicAcceptanceId, content?: string) =>
+ caller(userId).requestAccess({ acceptanceId, clientId: `r-${randomUUID()}`, content });
+
+ const granted = (userId: string) =>
+ new AcceptanceCommentModel(serverDB).hasAccessGrant(publicAcceptanceId, userId, 'collaborate');
+
+ it('lets a public-link visitor ask for reject access, as a pending discussion turn', async () => {
+ const { data } = await request(visitorId, publicAcceptanceId, 'C2 still overlaps');
+
+ expect(data).toMatchObject({
+ accessRequest: { permission: 'collaborate', status: 'pending' },
+ authorUserId: visitorId,
+ content: 'C2 still overlaps',
+ kind: 'access_request',
+ });
+ const list = await caller(ownerId).list({ acceptanceId: publicAcceptanceId });
+ expect(list.items.map((item) => item.id)).toContain(data.id);
+ });
+
+ it('hands back the standing request instead of opening a second one', async () => {
+ const first = await request(visitorId);
+ const second = await request(visitorId);
+
+ expect(second.data.id).toBe(first.data.id);
+ });
+
+ it('tells deciders, and only deciders, that they answer requests', async () => {
+ await expect(caller(ownerId).list({ acceptanceId: publicAcceptanceId })).resolves.toMatchObject(
+ { canManageAccess: true },
+ );
+ await expect(
+ caller(visitorId).list({ acceptanceId: publicAcceptanceId }),
+ ).resolves.toMatchObject({ canManageAccess: false });
+ });
+
+ it('refuses a request from the owner, who already holds everything a grant hands out', async () => {
+ await expect(request(ownerId)).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+
+ it('refuses a request on an acceptance the caller cannot read', async () => {
+ await expect(request(visitorId, privateAcceptanceId)).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it('refuses a request on a goal gate, whose revision is the goal’s call', async () => {
+ await expect(request(visitorId, gateAcceptanceId)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ });
+
+ it('lets only a decider answer', async () => {
+ const { data } = await request(visitorId);
+
+ await expect(
+ caller(visitorId).answerAccessRequest({ decision: 'grant', id: data.id }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(await granted(visitorId)).toBe(false);
+ });
+
+ it('grants reject access, records who granted it, and refuses a second answer', async () => {
+ const { data } = await request(visitorId);
+
+ const { data: answered } = await caller(ownerId).answerAccessRequest({
+ decision: 'grant',
+ id: data.id,
+ });
+
+ expect(answered.accessRequest).toMatchObject({
+ decidedByUserId: ownerId,
+ permission: 'collaborate',
+ status: 'granted',
+ });
+ expect(await granted(visitorId)).toBe(true);
+ await expect(
+ caller(ownerId).answerAccessRequest({ decision: 'decline', id: data.id }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('takes a grant back on revoke, after which the visitor may ask again', async () => {
+ const { data } = await request(visitorId);
+ await caller(ownerId).answerAccessRequest({ decision: 'grant', id: data.id });
+
+ await caller(ownerId).answerAccessRequest({ decision: 'revoke', id: data.id });
+
+ expect(await granted(visitorId)).toBe(false);
+ const again = await request(visitorId);
+ expect(again.data.id).not.toBe(data.id);
+ expect(again.data.accessRequest?.status).toBe('pending');
+ });
+
+ it('grants nothing on decline', async () => {
+ const { data } = await request(visitorId);
+
+ await caller(ownerId).answerAccessRequest({ decision: 'decline', id: data.id });
+
+ expect(await granted(visitorId)).toBe(false);
+ });
+
+ it('gives a grant back when the requester withdraws the request', async () => {
+ const { data } = await request(visitorId);
+ await caller(ownerId).answerAccessRequest({ decision: 'grant', id: data.id });
+
+ await caller(visitorId).delete({ id: data.id });
+
+ expect(await granted(visitorId)).toBe(false);
+ });
+
+ it('never lets the generic create forge an access request', async () => {
+ await expect(
+ caller(visitorId).create({
+ acceptanceId: publicAcceptanceId,
+ clientId: `c-${randomUUID()}`,
+ content: 'let me reject',
+ kind: 'access_request' as any,
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/acceptance/bundle.ts b/apps/server/src/routers/lambda/acceptance/bundle.ts
index ea89358500b..8226863e7af 100644
--- a/apps/server/src/routers/lambda/acceptance/bundle.ts
+++ b/apps/server/src/routers/lambda/acceptance/bundle.ts
@@ -4,6 +4,7 @@ import { eq } from 'drizzle-orm';
import pMap from 'p-map';
import { z } from 'zod';
+import { AcceptanceCommentModel } from '@/database/models/acceptanceComment';
import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { ScmChangeRequestModel } from '@/database/models/scm';
@@ -65,6 +66,17 @@ export const bundleRouter = router({
// The one rule the write path enforces — same helper, so the page can
// never advertise an action the mutation would refuse.
const canReview = await canManageAcceptance(ctx, acceptance);
+ // A reader a decider granted edit-collaboration to may send the delivery
+ // back — the same widening `resolveAcceptanceForReject` applies to the
+ // write — and talk to the agent bound to it. The owner holds both already.
+ const collaborationGranted =
+ !isOwner &&
+ Boolean(ctx.userId) &&
+ (await new AcceptanceCommentModel(ctx.serverDB).hasAccessGrant(
+ acceptance.id,
+ ctx.userId!,
+ 'collaborate',
+ ));
// Sub-reads (rounds / results / evidence) are ownership-scoped models, so
// read them AS the aggregate's owner — same pattern as the evidence file
@@ -225,6 +237,28 @@ export const bundleRouter = router({
// The authoring conversation (agent + topic), resolved for the header —
// owner-only, same redaction rule as `run.metadata.origin`.
const origin = isOwner ? await ownerService.resolveOrigin(runs) : null;
+ // A grantee's reject runs the owner's agent, so they need to know whether
+ // there is one to run — as a yes/no, never the private topic it names.
+ // A collaborator's reject and messages run the owner's agent, so they need
+ // to know there is one, and how to show it — the agent's face and the
+ // topic's title, never the private ids behind them.
+ const collaboratorOrigin = collaborationGranted
+ ? await ownerService.resolveOrigin(runs)
+ : null;
+ const repairDispatchAvailable = isOwner
+ ? Boolean(origin?.topic)
+ : Boolean(collaboratorOrigin?.topic);
+ const collaboration =
+ collaboratorOrigin?.topic && collaboratorOrigin.agent
+ ? {
+ agent: {
+ avatar: collaboratorOrigin.agent.avatar,
+ backgroundColor: collaboratorOrigin.agent.backgroundColor,
+ title: collaboratorOrigin.agent.title,
+ },
+ topicTitle: collaboratorOrigin.topic.title,
+ }
+ : null;
const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;
const resultsById = new Map(results.map((result) => [result.id, result]));
@@ -291,6 +325,8 @@ export const bundleRouter = router({
})),
})),
acceptance,
+ canCollaborate: collaborationGranted,
+ canReject: canReview || collaborationGranted,
canReview,
isOwner,
checks: checks.map((check) => {
@@ -336,8 +372,10 @@ export const bundleRouter = router({
: userReview,
};
}),
+ collaboration,
latestReport,
origin,
+ repairDispatchAvailable,
rounds,
subject,
};
diff --git a/apps/server/src/routers/lambda/acceptance/collaboration.ts b/apps/server/src/routers/lambda/acceptance/collaboration.ts
new file mode 100644
index 00000000000..bfc0b1ef852
--- /dev/null
+++ b/apps/server/src/routers/lambda/acceptance/collaboration.ts
@@ -0,0 +1,172 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { eq } from 'drizzle-orm';
+import { z } from 'zod';
+
+import { AcceptanceCommentModel } from '@/database/models/acceptanceComment';
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import { users } from '@/database/schemas';
+import { acceptances } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+import { isUuid } from '@/database/utils/uuid';
+import { router } from '@/libs/trpc/lambda';
+import { FileService } from '@/server/services/file';
+import { AcceptanceService } from '@/server/services/verify';
+
+import { agentNotifyRouter } from '../agentNotify';
+import { acceptanceProcedure, canReadAcceptance } from './procedures';
+
+/** One message to the bound agent; long enough for a detailed brief, not a dump. */
+const COLLABORATOR_MESSAGE_MAX_LENGTH = 4000;
+
+/**
+ * The owner's conversation an edit-collaborator may talk in.
+ *
+ * Edit-collaboration is granted per acceptance by one of its deciders, and it
+ * reaches into the OWNER's conversation: the topic the delivery was produced
+ * in, and the agent that produced it. Everything here therefore reads and
+ * writes as the owner, the way a granted reject dispatches its repair — the
+ * collaborator could reach neither on their own, and that reach is exactly
+ * what was granted. The owner holds this conversation already and uses their
+ * own chat, so this path is for grantees only.
+ */
+const resolveCollaboration = async (
+ ctx: { serverDB: LobeChatDatabase; userId: string },
+ id: string,
+) => {
+ const acceptance = isUuid(id)
+ ? await ctx.serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, id) })
+ : undefined;
+ if (!acceptance || !(await canReadAcceptance(ctx, acceptance)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });
+
+ const granted =
+ ctx.userId !== acceptance.userId &&
+ (await new AcceptanceCommentModel(ctx.serverDB).hasAccessGrant(
+ acceptance.id,
+ ctx.userId,
+ 'collaborate',
+ ));
+ if (!granted)
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Edit-collaboration access to this acceptance is required',
+ });
+
+ const workspaceId = acceptance.workspaceId ?? undefined;
+ const origin = await new AcceptanceService(
+ ctx.serverDB,
+ acceptance.userId,
+ workspaceId,
+ ).findRepairOrigin(acceptance.id);
+ const topic = origin?.topicId
+ ? await new TopicModel(ctx.serverDB, acceptance.userId, workspaceId).findOwnTopicById(
+ origin.topicId,
+ )
+ : undefined;
+ const agentId = origin?.agentId ?? topic?.agentId ?? undefined;
+ if (!topic || !agentId)
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'This acceptance has no conversation bound to it',
+ });
+
+ return { acceptance, agentId, topicId: topic.id, workspaceId };
+};
+
+const isAgentRunning = async (
+ db: LobeChatDatabase,
+ owner: { userId: string; workspaceId?: string },
+ topicId: string,
+) =>
+ (await new AgentOperationModel(db, owner.userId, owner.workspaceId).findLiveByTopic(topicId))
+ .length > 0;
+
+/**
+ * Who said it, on the line the agent and the owner read. The message is stored
+ * under the owner's account (it is the owner's conversation), so without this
+ * nothing would tell either of them it came from someone else.
+ */
+export const formatCollaboratorMessage = (name: string, content: string) =>
+ `**${name}** (acceptance collaborator):\n\n${content}`;
+
+export const collaborationRouter = router({
+ /**
+ * The bound conversation as a collaborator sees it: the transcript, read as
+ * the owner but through the visitor projection, which drops the owner's
+ * account identity, model/spend snapshot and raw error payloads — none of
+ * which the grant hands out. `running` says whether the agent is mid-reply,
+ * so the page polls only while it is. `agentId` is the one every assistant
+ * row already carries, returned so the page can put a face and name on them.
+ */
+ getOriginConversation: acceptanceProcedure
+ .input(z.object({ id: z.string() }))
+ .query(
+ async ({
+ ctx,
+ input,
+ }): Promise<{ agentId: string; messages: UIChatMessage[]; running: boolean }> => {
+ const { acceptance, agentId, topicId, workspaceId } = await resolveCollaboration(
+ ctx,
+ input.id,
+ );
+ const fileService = new FileService(ctx.serverDB, acceptance.userId, workspaceId);
+ const [messages, running] = await Promise.all([
+ new MessageModel(ctx.serverDB, acceptance.userId, workspaceId).queryForVisitor(
+ { topicId },
+ {
+ postProcessUrl: (path, file) =>
+ fileService.getFileAccessUrl({ id: file.id, url: path }),
+ },
+ ),
+ isAgentRunning(ctx.serverDB, { userId: acceptance.userId, workspaceId }, topicId),
+ ]);
+ return { agentId, messages, running };
+ },
+ ),
+
+ /**
+ * Talk to the bound agent: the message lands in the owner's conversation and
+ * the owner's agent replies, exactly as if the owner had sent it — through
+ * `agentNotify.notify` itself, so it carries that path's conversation-write
+ * and agent-use gates for the owner. One turn at a time: a message sent while
+ * the agent is still replying is refused rather than started beside it.
+ */
+ sendToOriginAgent: acceptanceProcedure
+ .input(
+ z.object({
+ content: z.string().trim().min(1).max(COLLABORATOR_MESSAGE_MAX_LENGTH),
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { acceptance, agentId, topicId, workspaceId } = await resolveCollaboration(
+ ctx,
+ input.id,
+ );
+ if (await isAgentRunning(ctx.serverDB, { userId: acceptance.userId, workspaceId }, topicId))
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The agent is still replying — send again once it is done',
+ });
+
+ const [sender] = await ctx.serverDB
+ .select({ fullName: users.fullName, username: users.username })
+ .from(users)
+ .where(eq(users.id, ctx.userId))
+ .limit(1);
+ const name = sender?.fullName || sender?.username || 'A collaborator';
+
+ const { operationId } = await agentNotifyRouter
+ .createCaller({ ...ctx, userId: acceptance.userId, workspaceId: acceptance.workspaceId })
+ .notify({
+ agentId,
+ content: formatCollaboratorMessage(name, input.content),
+ role: 'user',
+ topicId,
+ });
+ return { operationId: operationId ?? null };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/acceptance/index.procedures.test.ts b/apps/server/src/routers/lambda/acceptance/index.procedures.test.ts
index dece3198859..4bcbb86dba7 100644
--- a/apps/server/src/routers/lambda/acceptance/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/acceptance/index.procedures.test.ts
@@ -34,6 +34,7 @@ function expected(): Array<
['ensure', 'mutation', 13],
['getBundle', 'query', 7],
['getBySubject', 'query', 12],
+ ['getOriginConversation', 'query', 12],
['linkPullRequest', 'mutation', 13],
['list', 'query', 12],
['listPage', 'query', 12],
@@ -53,6 +54,7 @@ function expected(): Array<
['reviewFlowStep', 'mutation', 13],
['saveChecklist', 'mutation', 13],
['saveGoal', 'mutation', 13],
+ ['sendToOriginAgent', 'mutation', 12],
['setPreviewUrl', 'mutation', 13],
['setProject', 'mutation', 13],
['setProjectBatch', 'mutation', 13],
diff --git a/apps/server/src/routers/lambda/acceptance/index.ts b/apps/server/src/routers/lambda/acceptance/index.ts
index 34096419220..3d9c1804a75 100644
--- a/apps/server/src/routers/lambda/acceptance/index.ts
+++ b/apps/server/src/routers/lambda/acceptance/index.ts
@@ -1,6 +1,7 @@
import { mergeRouters } from '@/libs/trpc/lambda';
import { bundleRouter } from './bundle';
+import { collaborationRouter } from './collaboration';
import { deliveryLinksRouter } from './deliveryLinks';
import { flowRouter } from './flow';
import { listManagementRouter } from './listManagement';
@@ -15,5 +16,6 @@ export const acceptanceRouter = mergeRouters(
deliveryLinksRouter,
subjectRouter,
bundleRouter,
+ collaborationRouter,
listManagementRouter,
);
diff --git a/apps/server/src/routers/lambda/acceptance/procedures.ts b/apps/server/src/routers/lambda/acceptance/procedures.ts
index bf2a650083c..325fd4ca400 100644
--- a/apps/server/src/routers/lambda/acceptance/procedures.ts
+++ b/apps/server/src/routers/lambda/acceptance/procedures.ts
@@ -5,6 +5,7 @@ import {
requireWorkspaceRoleWhenScoped,
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AcceptanceCommentModel } from '@/database/models/acceptanceComment';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { AcceptanceItem } from '@/database/schemas/verify';
import { acceptances } from '@/database/schemas/verify';
@@ -90,6 +91,50 @@ export const resolveAcceptanceForWrite = async (
};
};
+/**
+ * Resolve an acceptance for a REJECT, which reaches one step further than
+ * {@link resolveAcceptanceForWrite}: besides everyone who may manage it, a
+ * reader a decider granted reject access to may send it back.
+ *
+ * `delegated` marks that second case. The acting user is still the one whose
+ * decision is recorded, but the repair belongs to the owner — the agent that
+ * wrote the delivery, in the owner's conversation — so the caller dispatches it
+ * as the owner rather than as a visitor who can reach neither.
+ */
+export const resolveAcceptanceForReject = async (
+ ctx: { serverDB: LobeChatDatabase; userId: string },
+ id: string,
+): Promise<{ acceptance: AcceptanceItem; delegated: boolean; service: AcceptanceService }> => {
+ try {
+ return { ...(await resolveAcceptanceForWrite(ctx, id)), delegated: false };
+ } catch (error) {
+ // FORBIDDEN is only raised for a caller who can read the row; anything
+ // else (missing, unreadable) stays the answer it was.
+ if (!(error instanceof TRPCError) || error.code !== 'FORBIDDEN') throw error;
+ const acceptance = await ctx.serverDB.query.acceptances.findFirst({
+ where: eq(acceptances.id, id),
+ });
+ const granted =
+ acceptance &&
+ (await new AcceptanceCommentModel(ctx.serverDB).hasAccessGrant(
+ acceptance.id,
+ ctx.userId,
+ 'collaborate',
+ ));
+ if (!acceptance || !granted) throw error;
+ return {
+ acceptance,
+ delegated: true,
+ service: new AcceptanceService(
+ ctx.serverDB,
+ acceptance.userId,
+ acceptance.workspaceId ?? undefined,
+ { actorUserId: ctx.userId },
+ ),
+ };
+ }
+};
+
export const canReadAcceptance = async (
ctx: { serverDB: LobeChatDatabase; userId?: string | null },
acceptance: AcceptanceItem,
diff --git a/apps/server/src/routers/lambda/acceptance/review.ts b/apps/server/src/routers/lambda/acceptance/review.ts
index f37f7bfa5c6..8d2906ead38 100644
--- a/apps/server/src/routers/lambda/acceptance/review.ts
+++ b/apps/server/src/routers/lambda/acceptance/review.ts
@@ -27,7 +27,11 @@ import {
} from '../_helpers/acceptanceRepairDispatch';
import { settleGoalSignOff } from '../_helpers/acceptanceStatus';
import * as goalGate from '../_helpers/goalGateAcceptance';
-import { acceptanceWriteProcedure, resolveAcceptanceForWrite } from './procedures';
+import {
+ acceptanceWriteProcedure,
+ resolveAcceptanceForReject,
+ resolveAcceptanceForWrite,
+} from './procedures';
import { reviewAnnotationsSchema } from './schemas';
export const reviewRouter = router({
@@ -328,6 +332,11 @@ export const reviewRouter = router({
* outcome rides on `repairDispatch` so every surface (UI, CLI, external
* callers) reports the same thing. Without one the caller hands the repair
* prompt over itself.
+ *
+ * A reader a decider granted reject access to may call this too. Their
+ * decision is recorded as theirs, but the repair is dispatched as the owner:
+ * it runs the owner's agent in the owner's conversation, which the grantee
+ * could never reach themselves — that reach is exactly what was granted.
*/
reject: acceptanceWriteProcedure
.input(
@@ -346,7 +355,7 @@ export const reviewRouter = router({
ctx,
input,
}): Promise<AcceptanceItem & { repairDispatch: AcceptanceRepairDispatch }> => {
- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);
+ const { acceptance, delegated, service } = await resolveAcceptanceForReject(ctx, input.id);
const comment = input.comment || undefined;
const rejected = await goalGate.withGoalGateAnswer(
@@ -369,7 +378,9 @@ export const reviewRouter = router({
}
const repairDispatch = await dispatchAcceptanceRepair(
- ctx,
+ delegated
+ ? { ...ctx, userId: acceptance.userId, workspaceId: acceptance.workspaceId }
+ : ctx,
service,
acceptance,
input.comment || undefined,
diff --git a/apps/server/src/routers/lambda/acceptanceComment.ts b/apps/server/src/routers/lambda/acceptanceComment.ts
index 9e6ea18fadb..892a3e9b184 100644
--- a/apps/server/src/routers/lambda/acceptanceComment.ts
+++ b/apps/server/src/routers/lambda/acceptanceComment.ts
@@ -1,4 +1,6 @@
import type {
+ AcceptanceAccessRequest,
+ AcceptanceAccessRequestStatus,
AcceptanceAttachment,
AcceptanceCommentAuthor,
AcceptanceCommentItem,
@@ -34,6 +36,7 @@ import { notifyAcceptance } from '@/server/services/acceptanceReview/events';
import { createEvidenceFileResolver } from '@/server/services/verify/evidenceFiles';
import { resolveAcceptanceCommentAccess } from './_helpers/acceptanceCommentAccess';
+import { canManageAcceptance } from './_helpers/acceptanceWriteScope';
const rectSchema = z.object({
height: z.number().min(0).max(1),
@@ -279,6 +282,7 @@ const enrich = async (
return rows
.filter((row) => row.kind !== 'reaction')
.map((row) => ({
+ accessRequest: row.kind === 'access_request' ? (row.metadata?.accessRequest ?? null) : null,
acceptanceId: row.acceptanceId,
anchorType: row.anchorType,
attachments: (row.attachments ?? []).flatMap((item) => {
@@ -444,6 +448,19 @@ const assertReferencesBelongToAcceptance = async (
const VISITOR_COMMENT_WINDOW_MS = 60_000;
const VISITOR_COMMENTS_PER_WINDOW = 10;
+/**
+ * Which answers a decider may give from which state. A grant is taken back,
+ * never declined after the fact; a closed request is asked again, not reopened.
+ */
+const ACCESS_TRANSITIONS: Record<
+ 'decline' | 'grant' | 'revoke',
+ { from: AcceptanceAccessRequestStatus; to: AcceptanceAccessRequestStatus }
+> = {
+ decline: { from: 'pending', to: 'declined' },
+ grant: { from: 'pending', to: 'granted' },
+ revoke: { from: 'granted', to: 'revoked' },
+};
+
export const acceptanceCommentRouter = router({
create: writeProcedure.input(createSchema).mutation(async ({ ctx, input }) => {
const access = await resolveAcceptanceCommentAccess(
@@ -528,6 +545,152 @@ export const acceptanceCommentRouter = router({
}
}),
+ /**
+ * Ask the acceptance's deciders for edit-collaboration: the right to send the
+ * delivery back, and to talk to the agent bound to it. Open to anyone who may
+ * remark here — a visitor on a public link included — because nothing moves
+ * until a decider says yes, and a remark alone never reaches the agent.
+ *
+ * It lands as a discussion turn the deciders answer in place. One standing
+ * request per person: a pending or granted one is handed back rather than
+ * duplicated, and a declined or revoked one may be asked again.
+ */
+ requestAccess: writeProcedure
+ .input(
+ z.object({
+ acceptanceId: z.string().min(1),
+ clientId: z.string().trim().min(1).max(255),
+ content: z.string().trim().max(2000).optional(),
+ contextRunId: z.string().uuid().optional(),
+ }),
+ )
+ .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' });
+ // A gate's revision is the goal's own call, carried out by its main Agent.
+ if (access.acceptance.subjectType === 'goal_gate')
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A goal gate cannot hand out reject access',
+ });
+ // The owner already holds everything a grant hands out. A workspace
+ // admin who may decide still cannot talk to the owner's agent, so they
+ // may ask like anyone else.
+ if (access.isOwner)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'You already own this acceptance',
+ });
+ await assertReferencesBelongToAcceptance(ctx.serverDB, access.acceptance.id, {
+ runId: input.contextRunId,
+ });
+
+ const enrichScope = {
+ canModerate: access.canApprove,
+ ownerUserId: access.acceptance.userId,
+ userId: ctx.userId,
+ visibility: access.acceptance.visibility,
+ workspaceId: access.acceptance.workspaceId,
+ };
+ const accessRequest: AcceptanceAccessRequest = {
+ permission: 'collaborate',
+ status: 'pending',
+ };
+ try {
+ // A pending or granted request already standing comes back as the
+ // duplicate — decided inside the write's own transaction, so two
+ // submissions at once still leave a single standing request.
+ const { comment, isDuplicate } = await ctx.acceptanceCommentModel.create({
+ acceptanceId: access.acceptance.id,
+ authorUserId: ctx.userId,
+ clientId: input.clientId,
+ content: input.content ?? '',
+ contextRunId: input.contextRunId,
+ kind: 'access_request',
+ metadata: { accessRequest },
+ rateLimit: access.canApprove
+ ? undefined
+ : {
+ max: VISITOR_COMMENTS_PER_WINDOW,
+ since: new Date(Date.now() - VISITOR_COMMENT_WINDOW_MS),
+ },
+ workspaceId: access.acceptance.workspaceId,
+ });
+ const [item] = await enrich(ctx.serverDB, [comment], enrichScope);
+ if (!isDuplicate) notifyAcceptance(access.acceptance.id, 'comments', ctx.userId);
+ return { data: item, success: true };
+ } catch (error) {
+ if (error instanceof Error && error.message === ACCEPTANCE_COMMENT_RATE_LIMITED)
+ throw new TRPCError({
+ code: 'TOO_MANY_REQUESTS',
+ message: 'Too many comments on this acceptance, try again in a minute',
+ });
+ throw error;
+ }
+ }),
+
+ /**
+ * A decider's answer to an access request: grant it, decline it, or take a
+ * grant back. Deciding who may send a delivery back is itself a decision on
+ * it, so it takes the same right the reject does.
+ */
+ answerAccessRequest: writeProcedure
+ .input(
+ z.object({
+ decision: z.enum(['decline', 'grant', 'revoke']),
+ id: z.string().min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { access, comment } = await requireComment(ctx, input.id);
+ if (comment.kind !== 'access_request' || comment.deletedAt)
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Access request not found' });
+ if (!(await canManageAcceptance(ctx, access.acceptance)))
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the creator, a workspace owner or a workspace admin can answer this',
+ });
+
+ const transition = ACCESS_TRANSITIONS[input.decision];
+ const current = comment.metadata?.accessRequest;
+ if (current?.status !== transition.from)
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: `This request is already ${current?.status ?? 'closed'}`,
+ });
+
+ const row = await ctx.acceptanceCommentModel.answerAccessRequest(
+ comment.id,
+ transition.from,
+ {
+ ...current,
+ decidedAt: new Date().toISOString(),
+ decidedByUserId: ctx.userId,
+ status: transition.to,
+ },
+ );
+ if (!row)
+ throw new TRPCError({ code: 'CONFLICT', message: 'This request was answered meanwhile' });
+
+ const [item] = await enrich(ctx.serverDB, [row], {
+ canModerate: access.canApprove,
+ ownerUserId: access.acceptance.userId,
+ userId: ctx.userId,
+ visibility: access.acceptance.visibility,
+ workspaceId: access.acceptance.workspaceId,
+ });
+ // The requester's page holds its decision controls in the bundle, so it
+ // has to hear about this as a session change, not only a new remark.
+ notifyAcceptance(comment.acceptanceId, 'comments', ctx.userId);
+ notifyAcceptance(comment.acceptanceId, 'session', ctx.userId);
+ return { data: item, success: true };
+ }),
+
/**
* Take a remark down. Its author always may; the acceptance's reviewers may
* take down anyone's, because the discussion is open to whoever holds the
@@ -549,6 +712,9 @@ export const acceptanceCommentRouter = router({
own ? { authorUserId: ctx.userId } : { moderator: true },
);
notifyAcceptance(comment.acceptanceId, 'comments', ctx.userId);
+ // Withdrawing an access request gives back whatever it was granted.
+ if (comment.kind === 'access_request')
+ notifyAcceptance(comment.acceptanceId, 'session', ctx.userId);
return { data: { deleted: result !== false }, success: true };
}),
@@ -568,7 +734,12 @@ export const acceptanceCommentRouter = router({
visibility: access.acceptance.visibility,
workspaceId: access.acceptance.workspaceId,
});
- return { canApprove: access.canApprove, canComment: access.canComment, items };
+ return {
+ canApprove: access.canApprove,
+ canComment: access.canComment,
+ canManageAccess: await canManageAcceptance(ctx, access.acceptance),
+ items,
+ };
}),
/**
diff --git a/apps/server/src/services/acceptanceReview/access.test.ts b/apps/server/src/services/acceptanceReview/access.test.ts
index 180d5a12660..85c146f6682 100644
--- a/apps/server/src/services/acceptanceReview/access.test.ts
+++ b/apps/server/src/services/acceptanceReview/access.test.ts
@@ -5,10 +5,16 @@ import type { LobeChatDatabase } from '@/database/type';
const commentAccess = vi.fn();
const canManage = vi.fn();
+const hasAccessGrant = vi.fn();
vi.mock('@/server/routers/lambda/_helpers/acceptanceCommentAccess', () => ({
resolveAcceptanceCommentAccess: (...args: unknown[]) => commentAccess(...args),
}));
+vi.mock('@/database/models/acceptanceComment', () => ({
+ AcceptanceCommentModel: class {
+ hasAccessGrant = (...args: unknown[]) => hasAccessGrant(...args);
+ },
+}));
vi.mock('@/server/routers/lambda/_helpers/acceptanceWriteScope', () => ({
canManageAcceptance: (...args: unknown[]) => canManage(...args),
}));
@@ -24,11 +30,12 @@ describe('resolveReviewAccess', () => {
it('maps the existing acceptance rules onto the review capabilities', async () => {
commentAccess.mockResolvedValueOnce({ acceptance, canApprove: false, canComment: true });
canManage.mockResolvedValueOnce(false);
+ hasAccessGrant.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 },
+ can: { comment: true, decide: false, moderate: false, reject: false },
});
expect(commentAccess).toHaveBeenCalledWith(db, 'user-1', 'acc-1');
expect(canManage).toHaveBeenCalledWith({ serverDB: db, userId: 'user-1' }, acceptance);
@@ -40,8 +47,21 @@ describe('resolveReviewAccess', () => {
const { resolveReviewAccess } = await import('./access');
await expect(resolveReviewAccess(db, 'owner', 'acc-1')).resolves.toMatchObject({
- can: { comment: true, decide: true, moderate: true },
+ can: { comment: true, decide: true, moderate: true, reject: true },
+ });
+ expect(hasAccessGrant).not.toHaveBeenCalled();
+ });
+
+ it('lets a reviewer granted reject access reject but not decide', async () => {
+ commentAccess.mockResolvedValueOnce({ acceptance, canApprove: false, canComment: true });
+ canManage.mockResolvedValueOnce(false);
+ hasAccessGrant.mockResolvedValueOnce(true);
+ const { resolveReviewAccess } = await import('./access');
+
+ await expect(resolveReviewAccess(db, 'visitor', 'acc-1')).resolves.toMatchObject({
+ can: { comment: true, decide: false, moderate: false, reject: true },
});
+ expect(hasAccessGrant).toHaveBeenCalledWith('acc-1', 'visitor', 'collaborate');
});
it('reads an unreadable acceptance as none at all', async () => {
diff --git a/apps/server/src/services/acceptanceReview/access.ts b/apps/server/src/services/acceptanceReview/access.ts
index c236a66cfd5..0eab1e947f2 100644
--- a/apps/server/src/services/acceptanceReview/access.ts
+++ b/apps/server/src/services/acceptanceReview/access.ts
@@ -1,5 +1,6 @@
import { TRPCError } from '@trpc/server';
+import { AcceptanceCommentModel } from '@/database/models/acceptanceComment';
import type { AcceptanceItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
import { resolveAcceptanceCommentAccess } from '@/server/routers/lambda/_helpers/acceptanceCommentAccess';
@@ -7,7 +8,7 @@ import { canManageAcceptance } from '@/server/routers/lambda/_helpers/acceptance
export interface ReviewAccess {
acceptance: AcceptanceItem;
- can: { comment: boolean; decide: boolean; moderate: boolean };
+ can: { comment: boolean; decide: boolean; moderate: boolean; reject: boolean };
}
export async function resolveReviewAccess(
@@ -18,9 +19,17 @@ export async function resolveReviewAccess(
try {
const access = await resolveAcceptanceCommentAccess(db, userId, acceptanceId);
const decide = await canManageAcceptance({ serverDB: db, userId }, access.acceptance);
+ // Granted reject access sends the delivery back; accepting stays a decider's.
+ const reject =
+ decide ||
+ (await new AcceptanceCommentModel(db).hasAccessGrant(
+ access.acceptance.id,
+ userId,
+ 'collaborate',
+ ));
return {
acceptance: access.acceptance,
- can: { comment: access.canComment, decide, moderate: access.canApprove },
+ can: { comment: access.canComment, decide, moderate: access.canApprove, reject },
};
} catch (error) {
if (error instanceof TRPCError && error.code === 'NOT_FOUND') return null;
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 15b1e9a6d0a..a1d702d8cc0 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -2,6 +2,29 @@
"acceptance.accept.exceptionsHint": "By accepting, you acknowledge these exceptions and take the delivery as is.",
"acceptance.accept.exceptionsTitle": "{{count}} exception(s) still unresolved:",
"acceptance.accept.summary": "Accept \"{{title}}\"? All verification rounds and their evidence will be archived as the acceptance record.",
+ "acceptance.access.answerFailed": "Couldn't save your answer. Try again.",
+ "acceptance.access.decline": "Decline",
+ "acceptance.access.declinedNote": "Your last request was declined.",
+ "acceptance.access.description": "Ask the creator for edit-collaboration access. Once they agree, you can send this delivery back yourself and talk to the agent that built it.",
+ "acceptance.access.grant": "Grant",
+ "acceptance.access.grantHint": "If you grant this, they can send the delivery back and read and talk in the bound conversation. Their messages run on your agent, under your account.",
+ "acceptance.access.pendingCount": "{{count}} edit-collaboration request(s) waiting",
+ "acceptance.access.pendingDescription": "Waiting for the creator, a workspace owner or an admin to respond.",
+ "acceptance.access.pendingTitle": "Edit-collaboration requested",
+ "acceptance.access.reasonPlaceholder": "What do you want to move forward? (optional)",
+ "acceptance.access.request": "Request edit-collaboration access",
+ "acceptance.access.requestAgain": "Request again",
+ "acceptance.access.requestFailed": "Couldn't send the request. Try again.",
+ "acceptance.access.requested": "{{name}} requested edit-collaboration access",
+ "acceptance.access.revoke": "Revoke access",
+ "acceptance.access.revokedNote": "Your edit-collaboration access was revoked.",
+ "acceptance.access.status.declined": "Declined",
+ "acceptance.access.status.granted": "Granted",
+ "acceptance.access.status.pending": "Waiting for response",
+ "acceptance.access.status.revoked": "Revoked",
+ "acceptance.access.submit": "Send request",
+ "acceptance.access.title": "Want to help move this delivery forward?",
+ "acceptance.access.withdraw": "Withdraw request",
"acceptance.actionError": "Couldn’t update this acceptance. Please try again.",
"acceptance.actions.accept": "Accept delivery",
"acceptance.actions.cancel": "Cancel",
@@ -28,8 +51,9 @@
"acceptance.bar.progress": "{{done}} of {{total}} checks confirmed — {{rest}} awaiting your review",
"acceptance.bar.progressDone": "All {{total}} checks confirmed — ready to accept",
"acceptance.bar.progressZero": "{{total}} checks awaiting your review",
- "acceptance.bar.readOnlyReason": "Only the creator, a workspace owner or an admin can accept or reject this delivery. You can still approve it or comment in Discussion.",
+ "acceptance.bar.readOnlyReason": "Only the creator, a workspace owner or an admin can accept or reject this delivery. You can still approve it, comment in Discussion, or request edit-collaboration access.",
"acceptance.bar.rejectComment": "Reject delivery",
+ "acceptance.bar.rejectOnlyReason": "You have edit-collaboration access. Accepting the delivery stays with the creator, a workspace owner or an admin.",
"acceptance.bar.rerun": "Fix",
"acceptance.bar.rerunDrafted": "Added to your composer — review and send it.",
"acceptance.bar.rerunSent": "Sent to the source conversation — the repair round is starting.",
@@ -79,6 +103,15 @@
"acceptance.checks.rerunHint": "This check ran in {{count}} rounds; the latest result counts.",
"acceptance.checks.title": "Acceptance checks",
"acceptance.checks.viewTrace": "View verification run",
+ "acceptance.collaboration.agentFallback": "the agent",
+ "acceptance.collaboration.empty": "No messages in this conversation yet.",
+ "acceptance.collaboration.expand": "Open the bound conversation",
+ "acceptance.collaboration.hint": "Your messages appear in the creator's conversation, and their agent replies.",
+ "acceptance.collaboration.loadFailed": "Couldn't load the conversation.",
+ "acceptance.collaboration.placeholder": "Message {{agent}}…",
+ "acceptance.collaboration.running": "The agent is replying, or waiting on the creator…",
+ "acceptance.collaboration.send": "Send",
+ "acceptance.collaboration.sendFailed": "Couldn't send the message. Try again.",
"acceptance.comments.addReaction": "Add reaction",
"acceptance.comments.approvalCount": "{{count}} reviewer(s) approved",
"acceptance.comments.approve": "Approve this delivery",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index f711c993b93..b1ee81373b9 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -2,6 +2,29 @@
"acceptance.accept.exceptionsHint": "接受即表示你已知悉这些例外并愿意带着它们验收。",
"acceptance.accept.exceptionsTitle": "仍有 {{count}} 项例外未处理:",
"acceptance.accept.summary": "将「{{title}}」标记为已验收:全部验证轮次与证据将归档为验收依据。",
+ "acceptance.access.answerFailed": "处理没有保存,请重试。",
+ "acceptance.access.decline": "不同意",
+ "acceptance.access.declinedNote": "上次的申请未通过。",
+ "acceptance.access.description": "向发起人申请编辑协作权限。对方同意后,你可以直接打回这次交付,也可以和负责交付的 Agent 对话推进修改。",
+ "acceptance.access.grant": "同意",
+ "acceptance.access.grantHint": "同意后,对方可以打回这次交付,并能查看关联对话、直接和你的 Agent 对话;对方的消息由你的 Agent 用你的账号执行。",
+ "acceptance.access.pendingCount": "{{count}} 个编辑协作申请待处理",
+ "acceptance.access.pendingDescription": "等待发起人、工作区所有者或管理员处理。",
+ "acceptance.access.pendingTitle": "已申请编辑协作权限",
+ "acceptance.access.reasonPlaceholder": "想推进什么?(可选)",
+ "acceptance.access.request": "申请编辑协作权限",
+ "acceptance.access.requestAgain": "再次申请",
+ "acceptance.access.requestFailed": "申请没有发出,请重试。",
+ "acceptance.access.requested": "{{name}} 申请了编辑协作权限",
+ "acceptance.access.revoke": "收回权限",
+ "acceptance.access.revokedNote": "你的编辑协作权限已被收回。",
+ "acceptance.access.status.declined": "未同意",
+ "acceptance.access.status.granted": "已同意",
+ "acceptance.access.status.pending": "待处理",
+ "acceptance.access.status.revoked": "已收回",
+ "acceptance.access.submit": "发送申请",
+ "acceptance.access.title": "想一起推进这次交付?",
+ "acceptance.access.withdraw": "撤回申请",
"acceptance.actionError": "验收状态更新失败,请重试。",
"acceptance.actions.accept": "接受交付",
"acceptance.actions.cancel": "取消",
@@ -28,8 +51,9 @@
"acceptance.bar.progress": "已完成 {{done}} / {{total}} 项验证项,剩余 {{rest}} 项等待你的验收",
"acceptance.bar.progressDone": "{{total}} 项验证项已全部确认,可以接受交付",
"acceptance.bar.progressZero": "共 {{total}} 项等待你的验收",
- "acceptance.bar.readOnlyReason": "只有发起人、工作区所有者或管理员可以接受或打回这次交付。你仍然可以在讨论中批准或留言。",
+ "acceptance.bar.readOnlyReason": "只有发起人、工作区所有者或管理员可以接受或打回这次交付。你仍然可以表达接受、在讨论中留言,或申请编辑协作权限。",
"acceptance.bar.rejectComment": "打回交付",
+ "acceptance.bar.rejectOnlyReason": "你有编辑协作权限;接受交付仍由发起人、工作区所有者或管理员决定。",
"acceptance.bar.rerun": "打回重跑",
"acceptance.bar.rerunDrafted": "已填入对话框,检查后发送。",
"acceptance.bar.rerunSent": "已发送到源会话,修复轮次启动中。",
@@ -79,6 +103,15 @@
"acceptance.checks.rerunHint": "同一检查项在 {{count}} 轮各验证一次,以最后一轮为准",
"acceptance.checks.title": "验收检查清单",
"acceptance.checks.viewTrace": "查看验证过程",
+ "acceptance.collaboration.agentFallback": "Agent",
+ "acceptance.collaboration.empty": "这段对话还没有消息。",
+ "acceptance.collaboration.expand": "打开关联对话",
+ "acceptance.collaboration.hint": "你的消息会出现在发起人的对话里,由发起人的 Agent 回复。",
+ "acceptance.collaboration.loadFailed": "对话没有加载出来。",
+ "acceptance.collaboration.placeholder": "给 {{agent}} 发消息…",
+ "acceptance.collaboration.running": "Agent 正在回复,或在等发起人处理…",
+ "acceptance.collaboration.send": "发送",
+ "acceptance.collaboration.sendFailed": "消息没有发出,请重试。",
"acceptance.comments.addReaction": "添加表情",
"acceptance.comments.approvalCount": "{{count}} 位评审已接受",
"acceptance.comments.approve": "表达接受交付",
diff --git a/packages/database/src/models/__tests__/acceptanceComment.test.ts b/packages/database/src/models/__tests__/acceptanceComment.test.ts
index d559d7a592d..83d9e57b314 100644
--- a/packages/database/src/models/__tests__/acceptanceComment.test.ts
+++ b/packages/database/src/models/__tests__/acceptanceComment.test.ts
@@ -249,6 +249,50 @@ describe('AcceptanceCommentModel', () => {
});
});
+ describe('access requests', () => {
+ const request = (clientId: string, status = 'pending') =>
+ model.create({
+ acceptanceId,
+ authorUserId: reviewer,
+ clientId,
+ content: 'let me collaborate',
+ kind: 'access_request',
+ metadata: { accessRequest: { permission: 'collaborate', status: status as any } },
+ });
+
+ const standingRows = () =>
+ serverDB
+ .select()
+ .from(acceptanceComments)
+ .where(eq(acceptanceComments.kind, 'access_request'));
+
+ it('keeps one standing request when two tabs ask at once', async () => {
+ const [first, second] = await Promise.all([request('tab-a'), request('tab-b')]);
+
+ expect(await standingRows()).toHaveLength(1);
+ expect(first.comment.id).toBe(second.comment.id);
+ expect([first.isDuplicate, second.isDuplicate].sort()).toEqual([false, true]);
+ });
+
+ it('hands back a granted request instead of opening another', async () => {
+ const { comment: granted } = await request('earlier', 'granted');
+
+ const again = await request('later');
+
+ expect(again).toMatchObject({ comment: { id: granted.id }, isDuplicate: true });
+ expect(await standingRows()).toHaveLength(1);
+ });
+
+ it('opens a new request once the last one was declined', async () => {
+ await request('earlier', 'declined');
+
+ const again = await request('later');
+
+ expect(again.isDuplicate).toBe(false);
+ expect(await standingRows()).toHaveLength(2);
+ });
+ });
+
describe('listByAcceptance', () => {
it('returns only this acceptance, oldest first', async () => {
await model.create({ acceptanceId, authorUserId: owner, clientId: 'a', content: 'a' });
diff --git a/packages/database/src/models/acceptanceComment.ts b/packages/database/src/models/acceptanceComment.ts
index c3f3769813d..97a2e2da786 100644
--- a/packages/database/src/models/acceptanceComment.ts
+++ b/packages/database/src/models/acceptanceComment.ts
@@ -1,4 +1,6 @@
import type {
+ AcceptanceAccessRequest,
+ AcceptanceAccessRequestStatus,
AcceptanceCommentAttachmentRef,
AcceptanceCommentKind,
AcceptanceCommentMetadata,
@@ -86,7 +88,8 @@ export class AcceptanceCommentModel {
params: CreateAcceptanceCommentParams,
): Promise<CreateAcceptanceCommentResult> => {
return this.db.transaction(async (tx) => {
- if (params.rateLimit)
+ const isAccessRequest = params.kind === 'access_request';
+ if (params.rateLimit || isAccessRequest)
// One author on one acceptance is the contended pair, and the lock is
// released when this transaction ends either way. Everybody else writes
// in parallel exactly as before.
@@ -94,6 +97,31 @@ export class AcceptanceCommentModel {
sql`select pg_advisory_xact_lock(hashtext(${params.acceptanceId}), hashtext(${params.authorUserId}))`,
);
+ // One standing access request per person. Checked under the lock above,
+ // in the same transaction as the insert: checked before it, two tabs
+ // asking at once would each see none and both write a pending request —
+ // and a grant on the older one would not count, since only the newest
+ // request is ever read back as the grant.
+ if (isAccessRequest) {
+ const [standing] = await tx
+ .select()
+ .from(acceptanceComments)
+ .where(
+ and(
+ eq(acceptanceComments.acceptanceId, params.acceptanceId),
+ eq(acceptanceComments.authorUserId, params.authorUserId),
+ eq(acceptanceComments.kind, 'access_request'),
+ isNull(acceptanceComments.parentCommentId),
+ isNull(acceptanceComments.deletedAt),
+ ),
+ )
+ .orderBy(desc(acceptanceComments.createdAt), desc(acceptanceComments.id))
+ .limit(1);
+ const status = standing?.metadata?.accessRequest?.status;
+ if (standing && (status === 'pending' || status === 'granted'))
+ return { comment: standing, isDuplicate: true };
+ }
+
let parentCommentId: string | undefined;
if (params.parentCommentId) {
const [parent] = await tx
@@ -384,6 +412,69 @@ export class AcceptanceCommentModel {
return deleted.length > 0;
};
+ /**
+ * One person's standing access request on one acceptance: their newest
+ * surviving `access_request` row, whatever its answer. Withdrawing the request
+ * (deleting the row) is how a requester gives a grant back, and a moderator
+ * taking it down takes the grant with it.
+ */
+ findLatestAccessRequest = async (acceptanceId: string, authorUserId: string) => {
+ const [row] = await this.db
+ .select()
+ .from(acceptanceComments)
+ .where(
+ and(
+ eq(acceptanceComments.acceptanceId, acceptanceId),
+ eq(acceptanceComments.authorUserId, authorUserId),
+ eq(acceptanceComments.kind, 'access_request'),
+ isNull(acceptanceComments.parentCommentId),
+ isNull(acceptanceComments.deletedAt),
+ ),
+ )
+ .orderBy(desc(acceptanceComments.createdAt), desc(acceptanceComments.id))
+ .limit(1);
+ return row;
+ };
+
+ /** Whether a decider has granted this person `permission` on this acceptance. */
+ hasAccessGrant = async (
+ acceptanceId: string,
+ userId: string,
+ permission: AcceptanceAccessRequest['permission'],
+ ) => {
+ const request = (await this.findLatestAccessRequest(acceptanceId, userId))?.metadata
+ ?.accessRequest;
+ return request?.status === 'granted' && request.permission === permission;
+ };
+
+ /**
+ * Move an access request from `from` to `next`. Conditional on the status the
+ * caller read, so two deciders answering at once cannot both win — the second
+ * update matches nothing and returns undefined.
+ */
+ answerAccessRequest = async (
+ id: string,
+ from: AcceptanceAccessRequestStatus,
+ next: AcceptanceAccessRequest,
+ ) => {
+ const [row] = await this.db
+ .update(acceptanceComments)
+ .set({
+ metadata: sql`jsonb_set(coalesce(${acceptanceComments.metadata}, '{}'::jsonb), '{accessRequest}', ${JSON.stringify(next)}::jsonb)`,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(acceptanceComments.id, id),
+ eq(acceptanceComments.kind, 'access_request'),
+ isNull(acceptanceComments.deletedAt),
+ sql`${acceptanceComments.metadata} -> 'accessRequest' ->> 'status' = ${from}`,
+ ),
+ )
+ .returning();
+ return row;
+ };
+
/** Mark a thread root handled (or reopen it). Replies are not resolvable. */
setResolved = async (rootId: string, resolved: boolean, userId: string) => {
const [row] = await this.db
diff --git a/packages/database/src/schemas/acceptanceComment.ts b/packages/database/src/schemas/acceptanceComment.ts
index 6de88e272d1..764ed45cdcf 100644
--- a/packages/database/src/schemas/acceptanceComment.ts
+++ b/packages/database/src/schemas/acceptanceComment.ts
@@ -22,7 +22,8 @@ import { workspaces } from './workspace';
* checklist, regions circled on evidence images, and reviewers' approvals.
* Rows never enter the verify execution tables — a comment changes no check
* result, no round, and no acceptance status. The decider still closes the
- * acceptance through `verify_runs.user_decision`.
+ * acceptance through `verify_runs.user_decision`; a granted access request only
+ * widens who may make that decision's reject.
*/
/**
* Short on purpose: this id is the addressable part of a comment's URL, and a
@@ -59,8 +60,10 @@ export const acceptanceComments = pgTable(
parentCommentId: text('parent_comment_id').references((): AnyPgColumn => acceptanceComments.id),
/**
* `comment` (a remark), `approval` (a reviewer's "fine by me" for a round),
- * `reaction` (one emoji on one comment), or `proposal` (the round's own
- * note, which renders as part of the round rather than as a message).
+ * `reaction` (one emoji on one comment), `proposal` (the round's own
+ * note, which renders as part of the round rather than as a message), or
+ * `access_request` (asking the deciders for reject access; the answer is
+ * server-owned `metadata.accessRequest`, read by the reject path).
*/
kind: text('kind').$type<AcceptanceCommentKind>().default('comment').notNull(),
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 18a34d9de84..8713c48bf99 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -213,7 +213,7 @@ export default {
'acceptance.bar.progressDone': 'All {{total}} checks confirmed — ready to accept',
'acceptance.bar.progressZero': '{{total}} checks awaiting your review',
'acceptance.bar.readOnlyReason':
- 'Only the creator, a workspace owner or an admin can accept or reject this delivery. You can still approve it or comment in Discussion.',
+ 'Only the creator, a workspace owner or an admin can accept or reject this delivery. You can still approve it, comment in Discussion, or request edit-collaboration access.',
'acceptance.bar.rejectComment': 'Reject delivery',
'acceptance.bar.rerun': 'Fix',
'acceptance.bar.rerunDrafted': 'Added to your composer — review and send it.',
@@ -1039,4 +1039,42 @@ export default {
'flow.startVerification': 'Start verification',
'flow.rerunVersion': 'Rerun this version',
'flow.roundCreated': 'New round created. Checks are waiting to run.',
+ 'acceptance.access.answerFailed': "Couldn't save your answer. Try again.",
+ 'acceptance.access.decline': 'Decline',
+ 'acceptance.access.declinedNote': 'Your last request was declined.',
+ 'acceptance.access.description':
+ 'Ask the creator for edit-collaboration access. Once they agree, you can send this delivery back yourself and talk to the agent that built it.',
+ 'acceptance.access.grant': 'Grant',
+ 'acceptance.access.grantHint':
+ 'If you grant this, they can send the delivery back and read and talk in the bound conversation. Their messages run on your agent, under your account.',
+ 'acceptance.access.pendingCount': '{{count}} edit-collaboration request(s) waiting',
+ 'acceptance.access.pendingDescription':
+ 'Waiting for the creator, a workspace owner or an admin to respond.',
+ 'acceptance.access.pendingTitle': 'Edit-collaboration requested',
+ 'acceptance.access.reasonPlaceholder': 'What do you want to move forward? (optional)',
+ 'acceptance.access.request': 'Request edit-collaboration access',
+ 'acceptance.access.requestAgain': 'Request again',
+ 'acceptance.access.requestFailed': "Couldn't send the request. Try again.",
+ 'acceptance.access.requested': '{{name}} requested edit-collaboration access',
+ 'acceptance.access.revoke': 'Revoke access',
+ 'acceptance.access.revokedNote': 'Your edit-collaboration access was revoked.',
+ 'acceptance.access.status.declined': 'Declined',
+ 'acceptance.access.status.granted': 'Granted',
+ 'acceptance.access.status.pending': 'Waiting for response',
+ 'acceptance.access.status.revoked': 'Revoked',
+ 'acceptance.access.title': 'Want to help move this delivery forward?',
+ 'acceptance.access.withdraw': 'Withdraw request',
+ 'acceptance.bar.rejectOnlyReason':
+ 'You have edit-collaboration access. Accepting the delivery stays with the creator, a workspace owner or an admin.',
+ 'acceptance.collaboration.empty': 'No messages in this conversation yet.',
+ 'acceptance.collaboration.expand': 'Open the bound conversation',
+ 'acceptance.collaboration.hint':
+ "Your messages appear in the creator's conversation, and their agent replies.",
+ 'acceptance.collaboration.loadFailed': "Couldn't load the conversation.",
+ 'acceptance.collaboration.placeholder': 'Message {{agent}}…',
+ 'acceptance.collaboration.running': 'The agent is replying, or waiting on the creator…',
+ 'acceptance.collaboration.send': 'Send',
+ 'acceptance.collaboration.sendFailed': "Couldn't send the message. Try again.",
+ 'acceptance.collaboration.agentFallback': 'the agent',
+ 'acceptance.access.submit': 'Send request',
};
diff --git a/packages/types/src/acceptanceComment.ts b/packages/types/src/acceptanceComment.ts
index 747d45930c8..b9ad2ac25c4 100644
--- a/packages/types/src/acceptanceComment.ts
+++ b/packages/types/src/acceptanceComment.ts
@@ -23,8 +23,41 @@ export type AcceptanceCommentAnchorType = 'acceptance' | 'evidence';
* - `proposal`: the round's own note, written by the agent that produced it.
* It belongs to the round rather than to the conversation, so the page folds
* it into that round's entry instead of listing it as another message.
+ * - `access_request`: someone who may only remark asking the deciders for the
+ * right to collaborate on this delivery — send it back, and talk to the
+ * agent bound to it. The answer is server-owned state on the same row
+ * ({@link AcceptanceAccessRequest}).
*/
-export type AcceptanceCommentKind = 'approval' | 'comment' | 'proposal' | 'reaction';
+export type AcceptanceCommentKind =
+ 'access_request' | 'approval' | 'comment' | 'proposal' | 'reaction';
+
+/**
+ * What an access request asks for. `collaborate` is edit-collaboration on one
+ * acceptance: rejecting the delivery, and talking to the agent bound to it in
+ * the owner's conversation. Accepting a delivery stays with its deciders.
+ */
+export type AcceptanceAccessPermission = 'collaborate';
+
+/**
+ * Where an access request stands.
+ *
+ * - `pending`: waiting on a decider.
+ * - `granted`: the requester collaborates on this acceptance. Whatever they
+ * start — a reject's repair, a message to the bound agent — runs on the
+ * owner's agent, in the owner's conversation.
+ * - `declined`: a decider said no; the requester may ask again.
+ * - `revoked`: a decider took a grant back.
+ */
+export type AcceptanceAccessRequestStatus = 'declined' | 'granted' | 'pending' | 'revoked';
+
+export interface AcceptanceAccessRequest {
+ decidedAt?: string;
+ decidedByUserId?: string;
+ permission: AcceptanceAccessPermission;
+ status: AcceptanceAccessRequestStatus;
+}
+
+export type AcceptanceAccessDecision = 'decline' | 'grant' | 'revoke';
/**
* A file hung on a comment, as it is STORED: an object rather than a bare id,
@@ -49,6 +82,8 @@ export type AcceptanceCommentTime = z.infer<typeof acceptanceCommentTimeSchema>;
/** Server-owned facts; other comment producers may retain their own keys. */
export interface AcceptanceCommentMetadata extends Record<string, unknown> {
+ /** Only on `access_request` rows; never written by a client. */
+ accessRequest?: AcceptanceAccessRequest;
evidenceAnchor?: {
time: AcceptanceCommentTime;
};
@@ -96,6 +131,8 @@ export interface AcceptanceCommentAnchor {
export interface AcceptanceCommentItem extends AcceptanceCommentAnchor {
acceptanceId: string;
+ /** Set on `access_request` rows only. */
+ accessRequest?: AcceptanceAccessRequest | null;
/**
* Files hung on the remark, resolved to display URLs by the read. Deliberately
* NOT inline in the body: a screenshot answering "what do you see instead" is
@@ -154,6 +191,8 @@ export interface AcceptanceCommentList {
canApprove: boolean;
/** May the caller write comments, annotations and reactions here? */
canComment: boolean;
+ /** May the caller answer access requests — the acceptance's deciders. */
+ canManageAccess?: boolean;
items: AcceptanceCommentItem[];
}
@@ -174,7 +213,7 @@ export interface CreateAcceptanceCommentInput {
contextRunId?: string;
/** The editor's own JSON, when the body was written in one. */
editorData?: DocumentCommentJson;
- /** Reactions are not written here; they have their own toggle endpoint. */
- kind?: Exclude<AcceptanceCommentKind, 'reaction'>;
+ /** Reactions and access requests have their own endpoints. */
+ kind?: Exclude<AcceptanceCommentKind, 'access_request' | 'reaction'>;
parentCommentId?: string;
}
diff --git a/packages/types/src/acceptanceReview.ts b/packages/types/src/acceptanceReview.ts
index aeceb77e5d2..35621ab0a23 100644
--- a/packages/types/src/acceptanceReview.ts
+++ b/packages/types/src/acceptanceReview.ts
@@ -105,7 +105,8 @@ export interface ReviewSession {
title: string;
url: string;
};
- can: { comment: boolean; decide: boolean; moderate: boolean };
+ /** `reject` without `decide`: a decider granted this reviewer reject access. */
+ can: { comment: boolean; decide: boolean; moderate: boolean; reject: boolean };
expiresAt: string;
user: ReviewUser;
}
diff --git a/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx b/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx
index 280befe3c54..2f7db8b5e17 100644
--- a/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx
@@ -26,6 +26,7 @@ vi.mock('./Checks/AcceptanceCheckInventory', () => ({ default: () => null }));
vi.mock('./Checks/AcceptanceCheckOwnerToolbar', () => ({ default: () => null }));
vi.mock('./Comments/AcceptanceDiscussion', () => ({ default: () => null }));
vi.mock('./Comments/ReviewerApprovalBar', () => ({ default: () => null }));
+vi.mock('./Comments/CollaborationRequestBanner', () => ({ default: () => null }));
vi.mock('./Conversation/AcceptanceOriginTopic', () => ({ default: () => null }));
vi.mock('./Evidence/AcceptanceResources', () => ({ default: () => null }));
vi.mock('./Flow/AcceptanceFlow', () => ({ AcceptanceFlow: () => null }));
diff --git a/src/features/Acceptance/Viewer/AcceptanceOverview.tsx b/src/features/Acceptance/Viewer/AcceptanceOverview.tsx
index 1829106f3ba..c0d6bf43caa 100644
--- a/src/features/Acceptance/Viewer/AcceptanceOverview.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceOverview.tsx
@@ -9,6 +9,7 @@ import AcceptanceCheckInventory from './Checks/AcceptanceCheckInventory';
import AcceptanceCheckOwnerToolbar from './Checks/AcceptanceCheckOwnerToolbar';
import AcceptanceDiscussion from './Comments/AcceptanceDiscussion';
import { commentIdFromHash } from './Comments/anchor';
+import CollaborationRequestBanner from './Comments/CollaborationRequestBanner';
import { countDiscussionMessages } from './Comments/discussionTimeline';
import { useAcceptanceComments } from './Comments/hooks';
import ReviewerApprovalBar from './Comments/ReviewerApprovalBar';
@@ -108,6 +109,9 @@ export const AcceptanceOverview = ({
<AcceptanceShare />
</Flexbox>
{!gateDossier && <AcceptanceGoal editSlot={<AcceptanceGoalEdit />} />}
+ {/* About the delivery as a whole, not one tab's face of it — a reviewer
+ reading the discussion needs it as much as one on the checklist. */}
+ <CollaborationRequestBanner />
{/* The requirement needs room to land before the tabs start a new
thought — at the band's uniform gap it read as another row of
the same list. */}
diff --git a/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx b/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx
index e93725bacfb..f9a70425391 100644
--- a/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx
+++ b/src/features/Acceptance/Viewer/Comments/AcceptanceDiscussion.tsx
@@ -1,7 +1,7 @@
'use client';
import type { AcceptanceCommentThread } from '@lobechat/types';
-import { Button, createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
+import { Button, createStaticStyles, cssVar, cx, Flexbox, Text } from '@lobehub/ui';
import { BadgeCheck, Undo2 } from 'lucide-react';
import { nanoid } from 'nanoid';
import { memo, useCallback, useMemo, useState } from 'react';
@@ -13,7 +13,8 @@ import { buildAuthReturnUrl, currentReturnPath } from '@/utils/authReturnUrl';
import { useAcceptanceScope } from '../AcceptanceScope';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
-import { useCommentAnchor } from './anchor';
+import AccessRequestEntry from './AccessRequestEntry';
+import { commentAnchorId, useCommentAnchor } from './anchor';
import { commentAuthorName } from './CommentCard';
import CommentComposer from './CommentComposer';
import DiscussionAside from './DiscussionAside';
@@ -112,6 +113,7 @@ const entryCommentIds = (entry: DiscussionEntry): string[] => {
if (entry.kind === 'region')
return [entry.thread.root.id, ...entry.thread.replies.map((reply) => reply.id)];
if (entry.kind === 'round' && entry.proposal) return [entry.proposal.id];
+ if (entry.kind === 'accessRequest') return [entry.request.id];
return [];
};
@@ -132,8 +134,10 @@ const AcceptanceDiscussion = memo<{ onOpenChecks?: () => void }>(({ onOpenChecks
const isSignedIn = useUserStore(authSelectors.isLogin);
const { data } = useAcceptanceBundle(acceptanceId);
const {
+ answerAccessRequest,
canApprove,
canComment,
+ canManageAccess,
create,
error,
isLoading,
@@ -257,6 +261,21 @@ const AcceptanceDiscussion = memo<{ onOpenChecks?: () => void }>(({ onOpenChecks
{entry.comment && <div className={entryStyles.quote}>{entry.comment}</div>}
</TimelineEvent>
);
+ if (entry.kind === 'accessRequest')
+ return (
+ <div
+ className={cx(entry.request.id === anchoredId && styles.entryAnchored)}
+ id={commentAnchorId(entry.request.id)}
+ key={entry.request.id}
+ >
+ <AccessRequestEntry
+ at={entry.at}
+ canManage={canManageAccess}
+ request={entry.request}
+ onAnswer={answerAccessRequest}
+ />
+ </div>
+ );
if (entry.kind === 'approval') {
const who =
entry.approval.contextRoundIndex === null
diff --git a/src/features/Acceptance/Viewer/Comments/AccessRequestEntry.tsx b/src/features/Acceptance/Viewer/Comments/AccessRequestEntry.tsx
new file mode 100644
index 00000000000..d274074369f
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/AccessRequestEntry.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import type { AcceptanceAccessDecision, AcceptanceCommentItem } from '@lobechat/types';
+import { Button, Flexbox, Tag, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { UsersRound } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import TimelineEvent from './TimelineEvent';
+
+const styles = stylex.create({
+ hint: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ },
+ // Same voice as a send-back's reason under its event line.
+ quote: {
+ borderInlineStartColor: cssVar.colorBorder,
+ borderInlineStartStyle: 'solid',
+ borderInlineStartWidth: 2,
+ color: cssVar.colorText,
+ fontSize: 13,
+ lineHeight: 1.65,
+ overflowWrap: 'anywhere',
+ paddingBlock: 6,
+ paddingInline: 12,
+ whiteSpace: 'pre-wrap',
+ },
+});
+
+const STATUS_COLOR = {
+ declined: undefined,
+ granted: 'success',
+ pending: 'warning',
+ revoked: undefined,
+} as const;
+
+/**
+ * An access request in the discussion: who asked, why, where it stands, and —
+ * for the acceptance's deciders — the answer, given right where the request
+ * was read. A grant can be taken back from the same place.
+ *
+ * Kept free of the interactive discussion's modules so the read-only report can
+ * render it too.
+ */
+const AccessRequestEntry = ({
+ at,
+ canManage,
+ onAnswer,
+ request,
+}: {
+ at: Date;
+ /** The viewer is one of the acceptance's deciders. */
+ canManage: boolean;
+ onAnswer?: (id: string, decision: AcceptanceAccessDecision) => Promise<void>;
+ request: AcceptanceCommentItem;
+}) => {
+ const { t } = useTranslation('verify');
+ const [pending, setPending] = useState<AcceptanceAccessDecision>();
+ const status = request.accessRequest?.status ?? 'pending';
+ const reason = request.content.trim();
+
+ const answer = async (decision: AcceptanceAccessDecision) => {
+ if (!onAnswer) return;
+ setPending(decision);
+ try {
+ await onAnswer(request.id, decision);
+ } catch (cause) {
+ console.error('[acceptance:access]', cause);
+ toast.error(t('acceptance.access.answerFailed'));
+ } finally {
+ setPending(undefined);
+ }
+ };
+
+ const actions =
+ canManage && onAnswer
+ ? status === 'pending'
+ ? (['decline', 'grant'] as const)
+ : status === 'granted'
+ ? (['revoke'] as const)
+ : []
+ : [];
+
+ return (
+ <TimelineEvent
+ at={at}
+ icon={UsersRound}
+ text={
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <span>
+ {t('acceptance.access.requested', {
+ name: request.author.fullName || request.author.username || '—',
+ })}
+ </span>
+ <Tag color={STATUS_COLOR[status]} size={'small'}>
+ {t(`acceptance.access.status.${status}`)}
+ </Tag>
+ </Flexbox>
+ }
+ >
+ {reason && <div {...stylex.props(styles.quote)}>{reason}</div>}
+ {actions.length > 0 && (
+ <Flexbox gap={8}>
+ {status === 'pending' && (
+ <span {...stylex.props(styles.hint)}>{t('acceptance.access.grantHint')}</span>
+ )}
+ <Flexbox horizontal gap={8}>
+ {actions.map((decision) => (
+ <Button
+ disabled={Boolean(pending) && pending !== decision}
+ key={decision}
+ loading={pending === decision}
+ size={'small'}
+ type={decision === 'grant' ? 'primary' : 'default'}
+ onClick={() => void answer(decision)}
+ >
+ {t(`acceptance.access.${decision}`)}
+ </Button>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+ </TimelineEvent>
+ );
+};
+
+export default AccessRequestEntry;
diff --git a/src/features/Acceptance/Viewer/Comments/CollaborationRequestBanner.tsx b/src/features/Acceptance/Viewer/Comments/CollaborationRequestBanner.tsx
new file mode 100644
index 00000000000..c54c6623919
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/CollaborationRequestBanner.tsx
@@ -0,0 +1,162 @@
+'use client';
+
+import type { AcceptanceCommentItem } from '@lobechat/types';
+import { Button, Flexbox, Icon, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { UsersRound } from 'lucide-react';
+import { nanoid } from 'nanoid';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { useAcceptanceScope } from '../AcceptanceScope';
+import { useAcceptanceBundle } from '../useAcceptanceBundle';
+import { openCollaborationRequestModal } from './CollaborationRequestModal';
+import { useAcceptanceComments } from './hooks';
+
+const styles = stylex.create({
+ banner: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: 10,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ paddingBlock: 10,
+ paddingInline: 14,
+ },
+ description: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ },
+});
+
+/** The viewer's newest surviving request on this acceptance. */
+export const findOwnAccessRequest = (
+ items: AcceptanceCommentItem[],
+ viewerId: string | undefined,
+) =>
+ viewerId
+ ? [...items]
+ .reverse()
+ .find(
+ (item) =>
+ item.kind === 'access_request' && !item.deletedAt && item.authorUserId === viewerId,
+ )
+ : undefined;
+
+/**
+ * For whoever may remark on a delivery but not own it: ask its deciders for
+ * edit-collaboration. Before, such a reviewer could only comment — and a
+ * comment, however pointed, never reaches the agent.
+ *
+ * It sits in the page header, above the tabs, because it is about the delivery
+ * as a whole rather than any one face of it: a reviewer reading the discussion
+ * needs it as much as one reading the checklist. One line, so it never pushes
+ * the content down; the reason is asked for in a dialog.
+ *
+ * The request lands in the discussion, where a decider grants or declines it.
+ * Once granted, the decision bar's reject turns on for this person and the
+ * conversation bound to the delivery opens to them; whatever they start there
+ * runs on the owner's agent.
+ */
+const CollaborationRequestBanner = () => {
+ const { t } = useTranslation('verify');
+ const { acceptanceId } = useAcceptanceScope();
+ const { data, mutate: mutateBundle } = useAcceptanceBundle(acceptanceId);
+ const { canComment, items, remove, requestAccess } = useAcceptanceComments(acceptanceId);
+ const viewerId = useUserStore(userProfileSelectors.userId);
+ const [withdrawing, setWithdrawing] = useState(false);
+
+ if (!data || !canComment || data.isOwner || data.canCollaborate) return null;
+ if (data.acceptance.subjectType === 'goal_gate') return null;
+ if (data.acceptance.status === 'accepted' || data.acceptance.status === 'closed') return null;
+
+ const mine = findOwnAccessRequest(items, viewerId);
+ const status = mine?.accessRequest?.status;
+ // Granted but the bundle has not caught up yet: the collaborator surfaces are
+ // about to take over.
+ if (status === 'granted') return null;
+
+ const pending = status === 'pending';
+ const note =
+ status === 'declined'
+ ? t('acceptance.access.declinedNote')
+ : status === 'revoked'
+ ? t('acceptance.access.revokedNote')
+ : undefined;
+
+ const withdraw = async () => {
+ if (!mine) return;
+ setWithdrawing(true);
+ try {
+ await remove(mine.id);
+ await mutateBundle();
+ } catch (cause) {
+ console.error('[acceptance:access]', cause);
+ toast.error(t('acceptance.actionError'));
+ } finally {
+ setWithdrawing(false);
+ }
+ };
+
+ const request = () =>
+ openCollaborationRequestModal({
+ onSubmit: async (reason) => {
+ try {
+ await requestAccess({
+ clientId: nanoid(),
+ content: reason || undefined,
+ contextRunId: (data.rounds ?? []).at(-1)?.run.id,
+ });
+ return true;
+ } catch (cause) {
+ console.error('[acceptance:access]', cause);
+ toast.error(t('acceptance.access.requestFailed'));
+ return false;
+ }
+ },
+ });
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ data-testid={'acceptance-collaboration-request'}
+ gap={12}
+ wrap={'wrap'}
+ {...stylex.props(styles.banner)}
+ >
+ <Icon
+ color={pending ? cssVar.colorWarning : cssVar.colorTextSecondary}
+ icon={UsersRound}
+ size={16}
+ />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 200 }}>
+ <Text fontSize={13} weight={500}>
+ {pending ? t('acceptance.access.pendingTitle') : t('acceptance.access.title')}
+ </Text>
+ <span {...stylex.props(styles.description)}>
+ {pending
+ ? t('acceptance.access.pendingDescription')
+ : note
+ ? `${note} ${t('acceptance.access.description')}`
+ : t('acceptance.access.description')}
+ </span>
+ </Flexbox>
+ {pending ? (
+ <Button loading={withdrawing} size={'small'} onClick={() => void withdraw()}>
+ {t('acceptance.access.withdraw')}
+ </Button>
+ ) : (
+ <Button size={'small'} type={'primary'} onClick={request}>
+ {note ? t('acceptance.access.requestAgain') : t('acceptance.access.request')}
+ </Button>
+ )}
+ </Flexbox>
+ );
+};
+
+export default CollaborationRequestBanner;
diff --git a/src/features/Acceptance/Viewer/Comments/CollaborationRequestModal.tsx b/src/features/Acceptance/Viewer/Comments/CollaborationRequestModal.tsx
new file mode 100644
index 00000000000..34e615995f2
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Comments/CollaborationRequestModal.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { Button, createModal, Flexbox, Text, TextArea, useModalContext } from '@lobehub/ui';
+import { t } from 'i18next';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { frostedModalStyles } from '../Review/modals';
+
+interface CollaborationRequestContentProps {
+ /** Send the request with an optional reason; resolve true to close. */
+ onSubmit: (reason: string) => Promise<boolean>;
+}
+
+const CollaborationRequestContent = ({ onSubmit }: CollaborationRequestContentProps) => {
+ const { t: translate } = useTranslation('verify');
+ const { close } = useModalContext();
+ const [reason, setReason] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ const submit = async () => {
+ setLoading(true);
+ try {
+ if (await onSubmit(reason.trim())) close();
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text type={'secondary'}>{translate('acceptance.access.description')}</Text>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 3 }}
+ maxLength={2000}
+ placeholder={translate('acceptance.access.reasonPlaceholder')}
+ value={reason}
+ onChange={(event) => setReason(event.target.value)}
+ />
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={loading} onClick={close}>
+ {translate('acceptance.actions.cancel')}
+ </Button>
+ <Button loading={loading} type={'primary'} onClick={() => void submit()}>
+ {translate('acceptance.access.submit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+/** Ask for edit-collaboration, with room to say why. */
+export const openCollaborationRequestModal = (props: CollaborationRequestContentProps) =>
+ createModal({
+ content: <CollaborationRequestContent {...props} />,
+ footer: null,
+ maskClosable: true,
+ styles: frostedModalStyles,
+ title: t('acceptance.access.request', { ns: 'verify' }),
+ width: 'min(90vw, 480px)',
+ });
diff --git a/src/features/Acceptance/Viewer/Comments/discussionRounds.ts b/src/features/Acceptance/Viewer/Comments/discussionRounds.ts
index 94b142b43b7..509bcb8cebd 100644
--- a/src/features/Acceptance/Viewer/Comments/discussionRounds.ts
+++ b/src/features/Acceptance/Viewer/Comments/discussionRounds.ts
@@ -19,6 +19,9 @@ const saysSomething = (entry: DiscussionEntry) => {
case 'round': {
return Boolean(entry.proposal?.content.trim());
}
+ case 'accessRequest': {
+ return true;
+ }
case 'roundReject':
case 'checkReject': {
return Boolean(entry.comment);
diff --git a/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.ts b/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.ts
index 28c344c211e..48c5a73f563 100644
--- a/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.ts
+++ b/src/features/Acceptance/Viewer/Comments/discussionTimeline.test.ts
@@ -373,3 +373,51 @@ describe('buildDiscussionTimeline', () => {
expect(timeline.map((entry) => entry.kind)).toEqual(['region']);
});
});
+
+describe('access requests', () => {
+ const request = (overrides: Partial<AcceptanceCommentItem> = {}) =>
+ item({
+ accessRequest: { permission: 'reject', status: 'pending' },
+ content: 'C2 still overlaps',
+ kind: 'access_request',
+ ...overrides,
+ });
+
+ it('is its own turn, answered in place, while replies to it stay messages', () => {
+ const root = request({ id: 'req' });
+ const reply = item({ id: 'reply', parentCommentId: 'req' });
+
+ const timeline = buildDiscussionTimeline({
+ approvals: [],
+ rounds: [],
+ threads: groupCommentThreads([root, reply]),
+ });
+
+ expect(timeline.map((entry) => entry.kind)).toEqual(['accessRequest', 'message']);
+ expect(timeline[0]).toMatchObject({ kind: 'accessRequest', request: { id: 'req' } });
+ expect(timeline[1]).toMatchObject({ comment: { id: 'reply' } });
+ });
+
+ it('drops a withdrawn request but keeps what people said to it', () => {
+ const root = request({ deletedAt: new Date(), id: 'gone' });
+ const reply = item({ id: 'reply', parentCommentId: 'gone' });
+
+ const timeline = buildDiscussionTimeline({
+ approvals: [],
+ rounds: [],
+ threads: groupCommentThreads([root, reply]),
+ });
+
+ expect(timeline.map((entry) => entry.kind)).toEqual(['message']);
+ });
+
+ it('counts a request as a contribution to the discussion', () => {
+ expect(
+ countDiscussionMessages({
+ approvals: [],
+ rounds: [],
+ threads: groupCommentThreads([request()]),
+ }),
+ ).toBe(1);
+ });
+});
diff --git a/src/features/Acceptance/Viewer/Comments/discussionTimeline.ts b/src/features/Acceptance/Viewer/Comments/discussionTimeline.ts
index fce14376d02..ab12590f1b2 100644
--- a/src/features/Acceptance/Viewer/Comments/discussionTimeline.ts
+++ b/src/features/Acceptance/Viewer/Comments/discussionTimeline.ts
@@ -30,7 +30,9 @@ export type DiscussionEntry =
roundIndex: number;
runId?: string;
}
- | { approval: AcceptanceCommentItem; at: Date; kind: 'approval' };
+ | { approval: AcceptanceCommentItem; at: Date; kind: 'approval' }
+ /** Someone asking the deciders for reject access, answered in place. */
+ | { at: Date; kind: 'accessRequest'; request: AcceptanceCommentItem };
/**
* Threads that belong in the discussion stream: plain, delivery-wide remarks.
@@ -97,10 +99,20 @@ export const buildDiscussionTimeline = ({
// Flattened: the discussion is a chat, so a reply to a delivery-wide remark
// is just the next message. Threading is for regions, where a note and its
- // answers are about one spot on one picture.
- for (const thread of messageThreads(threads))
- for (const comment of [thread.root, ...thread.replies])
+ // answers are about one spot on one picture. An access request is a turn of
+ // its own — it carries an answer — while what people say back to it stays
+ // ordinary messages.
+ for (const thread of messageThreads(threads)) {
+ const isRequest = thread.root.kind === 'access_request';
+ if (isRequest && !thread.root.deletedAt)
+ entries.push({
+ at: new Date(thread.root.createdAt),
+ kind: 'accessRequest',
+ request: thread.root,
+ });
+ for (const comment of isRequest ? thread.replies : [thread.root, ...thread.replies])
entries.push({ at: new Date(comment.createdAt), comment, kind: 'message' });
+ }
// A region note leads with its root: that is when it was said, and its
// replies stay under it because they are about the same spot.
@@ -176,6 +188,9 @@ export const countDiscussionMessages = (input: BuildInput): number =>
case 'roundReject': {
return total + (entry.comment ? 1 : 0);
}
+ case 'accessRequest': {
+ return total + 1;
+ }
default: {
return total;
}
diff --git a/src/features/Acceptance/Viewer/Comments/hooks.ts b/src/features/Acceptance/Viewer/Comments/hooks.ts
index 8edc56777e2..f0da2c2fb58 100644
--- a/src/features/Acceptance/Viewer/Comments/hooks.ts
+++ b/src/features/Acceptance/Viewer/Comments/hooks.ts
@@ -1,4 +1,8 @@
-import type { AcceptanceCommentList, CreateAcceptanceCommentInput } from '@lobechat/types';
+import type {
+ AcceptanceAccessDecision,
+ AcceptanceCommentList,
+ CreateAcceptanceCommentInput,
+} from '@lobechat/types';
import { useCallback, useMemo } from 'react';
import { acceptanceCommentService } from '@/services/acceptanceComment';
@@ -42,6 +46,21 @@ export const useAcceptanceComments = (acceptanceId: string | undefined) => {
},
[mutate],
);
+ const requestAccess = useCallback(
+ async (input: { clientId: string; content?: string; contextRunId?: string }) => {
+ if (!acceptanceId) return;
+ await acceptanceCommentService.requestAccess({ ...input, acceptanceId });
+ await mutate();
+ },
+ [acceptanceId, mutate],
+ );
+ const answerAccessRequest = useCallback(
+ async (id: string, decision: AcceptanceAccessDecision) => {
+ await acceptanceCommentService.answerAccessRequest(id, decision);
+ await mutate();
+ },
+ [mutate],
+ );
/**
* Optimistic on purpose: a chip that waits for a round trip before it fills
* in makes the click feel broken, and the write is a single idempotent row.
@@ -73,9 +92,11 @@ export const useAcceptanceComments = (acceptanceId: string | undefined) => {
);
return {
+ answerAccessRequest,
approvals,
canApprove: data.canApprove,
canComment: data.canComment,
+ canManageAccess: Boolean(data.canManageAccess),
/**
* A failed read is not a permission answer. Without this the page falls
* back to `canComment: false` and tells the owner to sign in, which is
@@ -88,6 +109,7 @@ export const useAcceptanceComments = (acceptanceId: string | undefined) => {
participants,
react,
remove,
+ requestAccess,
setResolved,
threads,
};
diff --git a/src/features/Acceptance/Viewer/Conversation/AcceptanceOriginTopic.tsx b/src/features/Acceptance/Viewer/Conversation/AcceptanceOriginTopic.tsx
index 285912dd0e2..aa70f184ce6 100644
--- a/src/features/Acceptance/Viewer/Conversation/AcceptanceOriginTopic.tsx
+++ b/src/features/Acceptance/Viewer/Conversation/AcceptanceOriginTopic.tsx
@@ -33,15 +33,29 @@ const AcceptanceOriginTopic = () => {
const { acceptanceId, embedded } = useAcceptanceScope();
const { data } = useAcceptanceBundle(acceptanceId);
const originConversation = useOriginConversation();
+ // A collaborator never sees the owner's topic id; the bundle names the
+ // conversation for them, and the rail reads it through the acceptance.
+ const collaborationTitle = data?.canCollaborate
+ ? (data.collaboration?.topicTitle ?? data.subject.title ?? undefined)
+ : undefined;
const openTopic = useCallback(() => {
- if (!originConversation || !data?.origin?.topic) return;
- originConversation.openTopicDrawer(data.origin.topic.id, {
- agentId: data.origin.agent?.id,
- title: data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id,
- });
- }, [data, originConversation]);
+ if (!originConversation || !data) return;
+ if (data.origin?.topic) {
+ originConversation.openTopicDrawer(data.origin.topic.id, {
+ agentId: data.origin.agent?.id,
+ title: data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id,
+ });
+ return;
+ }
+ if (data.collaboration) originConversation.openTopicDrawer('', { title: collaborationTitle });
+ }, [collaborationTitle, data, originConversation]);
- if (embedded || !data?.origin?.topic || !originConversation) return null;
+ const title = data?.origin?.topic
+ ? (data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id)
+ : data?.collaboration
+ ? collaborationTitle
+ : undefined;
+ if (embedded || !title || !originConversation) return null;
return (
<button
@@ -52,7 +66,7 @@ const AcceptanceOriginTopic = () => {
>
<Flexbox horizontal align={'center'} gap={4}>
<Icon icon={MessagesSquare} size={13} />
- {data.origin.topic.title ?? data.subject.title ?? data.origin.topic.id}
+ {title}
</Flexbox>
</button>
);
diff --git a/src/features/Acceptance/Viewer/Conversation/CollaboratorConversationRail.tsx b/src/features/Acceptance/Viewer/Conversation/CollaboratorConversationRail.tsx
new file mode 100644
index 00000000000..2f5342dc624
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Conversation/CollaboratorConversationRail.tsx
@@ -0,0 +1,105 @@
+'use client';
+
+import { DraggablePanel, Flexbox, Icon, useResponsive } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { MessagesSquare } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import { AcceptanceDrawer } from '../../AcceptanceDrawer';
+import { useAcceptanceScope } from '../AcceptanceScope';
+import { useAcceptanceRailState } from '../History/useAcceptanceRailState';
+import { useAcceptanceBundle } from '../useAcceptanceBundle';
+import CollaboratorTopicPanel from './CollaboratorTopicPanel';
+
+const styles = stylex.create({
+ // Same footprint as the owner's collapsed ledger chip: a thumb-width strip on
+ // the content's right edge.
+ toggle: {
+ backgroundColor: {
+ ':hover': cssVar.colorFillQuaternary,
+ 'default': cssVar.colorBgContainer,
+ },
+ borderColor: {
+ ':hover': cssVar.colorBorder,
+ 'default': cssVar.colorBorderSecondary,
+ },
+ borderRadius: 99,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ cursor: 'pointer',
+ insetBlockStart: 16,
+ insetInlineEnd: 12,
+ paddingBlock: 8,
+ paddingInline: 5,
+ position: 'absolute',
+ zIndex: 10,
+ },
+});
+
+/**
+ * The right rail for an edit-collaborator: the conversation bound to the
+ * delivery, in the column the owner's round ledger occupies. The owner keeps
+ * the ledger rail (with their own chat behind the topic chip); a collaborator
+ * has no round history to browse, so their rail is the conversation alone.
+ *
+ * Only the standalone page mounts it: an embedded viewer already sits beside a
+ * conversation, and has no column of its own for a second one.
+ */
+const CollaboratorConversationRail = () => {
+ const { t } = useTranslation('verify');
+ const { lg = true } = useResponsive();
+ const isNarrowViewport = !lg;
+ const params = useParams<{ checkId?: string }>();
+ const { acceptanceId } = useAcceptanceScope();
+ const { data } = useAcceptanceBundle(acceptanceId);
+ const focused = Boolean(params.checkId);
+ const { expand, onExpandChange } = useAcceptanceRailState({ focused, isNarrowViewport });
+
+ if (!data || data.isOwner || !data.canCollaborate || !data.collaboration) return null;
+
+ const panel = <CollaboratorTopicPanel onCollapse={() => onExpandChange(false)} />;
+
+ return (
+ <>
+ {!focused && !expand && (
+ <Flexbox
+ align={'center'}
+ title={t('acceptance.collaboration.expand')}
+ onClick={() => onExpandChange(true)}
+ {...stylex.props(styles.toggle)}
+ >
+ <Icon icon={MessagesSquare} size={14} />
+ </Flexbox>
+ )}
+ {isNarrowViewport ? (
+ <AcceptanceDrawer
+ noHeader
+ containerMaxWidth={'100%'}
+ open={expand}
+ placement={'right'}
+ styles={{ bodyContent: { height: '100%', padding: 0 } }}
+ title={t('acceptance.collaboration.expand')}
+ width={'min(380px, 92vw)'}
+ onClose={() => onExpandChange(false)}
+ >
+ {panel}
+ </AcceptanceDrawer>
+ ) : (
+ <DraggablePanel
+ defaultSize={{ width: 380 }}
+ expand={expand}
+ minWidth={320}
+ placement={'right'}
+ style={{ flex: 'none', height: '100%' }}
+ onExpandChange={onExpandChange}
+ >
+ <Flexbox style={{ height: '100%', minHeight: 0, overflow: 'hidden' }}>{panel}</Flexbox>
+ </DraggablePanel>
+ )}
+ </>
+ );
+};
+
+export default CollaboratorConversationRail;
diff --git a/src/features/Acceptance/Viewer/Conversation/CollaboratorTopicPanel.tsx b/src/features/Acceptance/Viewer/Conversation/CollaboratorTopicPanel.tsx
new file mode 100644
index 00000000000..88ce732690e
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Conversation/CollaboratorTopicPanel.tsx
@@ -0,0 +1,247 @@
+'use client';
+
+import type { UIChatMessage } from '@lobechat/types';
+import { ActionIcon, Avatar, Button, Flexbox, Text, TextArea, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { PanelRightClose } from 'lucide-react';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ type ConversationContext,
+ ConversationProvider,
+ MessageItem,
+} from '@/features/Conversation';
+import { MessageActionProvider } from '@/features/Conversation/Messages/Contexts/MessageActionProvider';
+import { dataSelectors, useConversationStore } from '@/features/Conversation/store';
+import { useClientDataSWR } from '@/libs/swr';
+import { acceptanceCollaborationKeys } from '@/libs/swr/keys';
+import { acceptanceCollaborationService } from '@/services/acceptanceCollaboration';
+import { useAgentStore } from '@/store/agent';
+
+import { useAcceptanceScope } from '../AcceptanceScope';
+import { useAcceptanceBundle } from '../useAcceptanceBundle';
+
+/** Stable, so a missing transcript does not hand the provider a new array each render. */
+const EMPTY_MESSAGES: UIChatMessage[] = [];
+
+/** While the agent is replying, how often the transcript is read again. */
+const RUNNING_POLL_INTERVAL = 2000;
+
+const styles = stylex.create({
+ composer: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ flexShrink: 0,
+ paddingBlock: 12,
+ paddingInline: 12,
+ },
+ empty: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 13,
+ paddingBlock: 24,
+ paddingInline: 16,
+ },
+ header: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ flexShrink: 0,
+ paddingBlock: 12,
+ paddingInline: 12,
+ },
+ hint: {
+ color: cssVar.colorTextTertiary,
+ fontSize: 12,
+ },
+ panel: {
+ backgroundColor: cssVar.colorBgContainer,
+ height: '100%',
+ minHeight: 0,
+ overflow: 'hidden',
+ },
+ thread: {
+ flex: '1',
+ minHeight: 0,
+ overflowY: 'auto',
+ paddingBlock: 8,
+ },
+});
+
+const Transcript = () => {
+ const ids = useConversationStore(dataSelectors.displayMessageIds);
+ return (
+ <MessageActionProvider withSingletonActionsBar={false}>
+ {ids.map((id, index) => (
+ <MessageItem disableEditing id={id} index={index} key={id} />
+ ))}
+ </MessageActionProvider>
+ );
+};
+
+/**
+ * The conversation bound to an acceptance, as an edit-collaborator has it.
+ *
+ * The owner opens the same conversation in their own chat; a collaborator has
+ * no seat there, so the transcript is read through the acceptance (as the
+ * owner, through the visitor projection) and rendered by the real message
+ * renderer without its edit affordances. A message they send lands in the
+ * owner's conversation and the owner's agent replies; the transcript is read
+ * again every few seconds only while that reply is running.
+ */
+const CollaboratorTopicPanel = ({ onCollapse }: { onCollapse: () => void }) => {
+ const { t } = useTranslation('verify');
+ const { acceptanceId } = useAcceptanceScope();
+ const { data: bundle } = useAcceptanceBundle(acceptanceId);
+ const [draft, setDraft] = useState('');
+ const [sending, setSending] = useState(false);
+
+ const { data, error, mutate } = useClientDataSWR(
+ acceptanceCollaborationKeys.conversation(acceptanceId),
+ () => acceptanceCollaborationService.getConversation(acceptanceId),
+ {
+ refreshInterval: (latest) => (latest?.running ? RUNNING_POLL_INTERVAL : 0),
+ revalidateOnFocus: true,
+ },
+ );
+ const messages = data?.messages ?? EMPTY_MESSAGES;
+ // A transcript with no real coordinates of its own: it is held, never synced.
+ // It is also someone else's conversation, read through a grant, so it renders
+ // the way a shared topic does — no retry, no raw error details, and none of
+ // the owner-scoped side reads (run verification, notebook, memories).
+ const context = useMemo<ConversationContext>(
+ () => ({
+ agentId: '',
+ topicId: `acceptance-collaboration:${acceptanceId}`,
+ topicShareId: `acceptance-collaboration:${acceptanceId}`,
+ }),
+ [acceptanceId],
+ );
+
+ // Follow the newest turn, like a chat does: what a collaborator comes back
+ // for is the latest exchange, not the delivery's opening brief.
+ const threadRef = useRef<HTMLDivElement>(null);
+ const messageCount = messages.length;
+ useEffect(() => {
+ const thread = threadRef.current;
+ if (thread && messageCount > 0) thread.scrollTop = thread.scrollHeight;
+ }, [messageCount]);
+
+ // A send-back starts a new turn in this conversation from outside the panel
+ // (the decision bar), and the transcript is only polled while a reply is
+ // known to be running — so a status change is the cue to read it again.
+ const acceptanceStatus = bundle?.acceptance.status;
+ useEffect(() => {
+ if (acceptanceStatus) void mutate();
+ }, [acceptanceStatus, mutate]);
+
+ const collaboration = bundle?.collaboration;
+ const agentId = data?.agentId;
+ const agentAvatar = collaboration?.agent.avatar;
+ const agentBackground = collaboration?.agent.backgroundColor;
+ const agentTitle = collaboration?.agent.title;
+ // The assistant rows name the owner's agent, which the collaborator's own
+ // agent store has never loaded — without its face and title every reply
+ // reads as an unnamed assistant. Seeded only while this panel is mounted,
+ // and only when the store does not already know the agent.
+ useEffect(() => {
+ if (!agentId || useAgentStore.getState().agentMap[agentId]) return;
+ useAgentStore.setState((state) => ({
+ agentMap: {
+ ...state.agentMap,
+ [agentId]: {
+ avatar: agentAvatar,
+ backgroundColor: agentBackground,
+ title: agentTitle,
+ } as never,
+ },
+ }));
+ return () => {
+ useAgentStore.setState((state) => {
+ const { [agentId]: _seeded, ...rest } = state.agentMap;
+ return { agentMap: rest };
+ });
+ };
+ }, [agentAvatar, agentBackground, agentId, agentTitle]);
+
+ if (!collaboration) return null;
+ const agentName = collaboration.agent.title || t('acceptance.collaboration.agentFallback');
+ const running = Boolean(data?.running);
+
+ const send = async () => {
+ const content = draft.trim();
+ if (!content || running) return;
+ setSending(true);
+ try {
+ await acceptanceCollaborationService.send(acceptanceId, content);
+ setDraft('');
+ await mutate();
+ } catch (cause) {
+ console.error('[acceptance:collaboration]', cause);
+ toast.error(t('acceptance.collaboration.sendFailed'));
+ } finally {
+ setSending(false);
+ }
+ };
+
+ return (
+ <Flexbox {...stylex.props(styles.panel)}>
+ <Flexbox horizontal align={'center'} gap={8} {...stylex.props(styles.header)}>
+ <Avatar
+ avatar={collaboration.agent.avatar ?? undefined}
+ background={collaboration.agent.backgroundColor ?? undefined}
+ size={20}
+ />
+ <Text ellipsis strong style={{ flex: 1, fontSize: 13, minWidth: 0 }}>
+ {collaboration.topicTitle ?? agentName}
+ </Text>
+ <ActionIcon
+ icon={PanelRightClose}
+ size={'small'}
+ title={t('acceptance.ledger.collapse')}
+ onClick={onCollapse}
+ />
+ </Flexbox>
+ <div ref={threadRef} {...stylex.props(styles.thread)}>
+ {error && !data ? (
+ <div {...stylex.props(styles.empty)}>{t('acceptance.collaboration.loadFailed')}</div>
+ ) : data && messages.length === 0 ? (
+ <div {...stylex.props(styles.empty)}>{t('acceptance.collaboration.empty')}</div>
+ ) : data ? (
+ <ConversationProvider context={context} messages={messages}>
+ <Transcript />
+ </ConversationProvider>
+ ) : null}
+ </div>
+ <Flexbox gap={8} {...stylex.props(styles.composer)}>
+ <span {...stylex.props(styles.hint)}>
+ {running ? t('acceptance.collaboration.running') : t('acceptance.collaboration.hint')}
+ </span>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ disabled={sending}
+ maxLength={4000}
+ placeholder={t('acceptance.collaboration.placeholder', { agent: agentName })}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) void send();
+ }}
+ />
+ <Button
+ disabled={!draft.trim() || running}
+ loading={sending}
+ style={{ alignSelf: 'flex-end' }}
+ type={'primary'}
+ onClick={() => void send()}
+ >
+ {t('acceptance.collaboration.send')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export default CollaboratorTopicPanel;
diff --git a/src/features/Acceptance/Viewer/ReadOnly/Discussion.tsx b/src/features/Acceptance/Viewer/ReadOnly/Discussion.tsx
index 5322a3bc67d..c00d7399ccc 100644
--- a/src/features/Acceptance/Viewer/ReadOnly/Discussion.tsx
+++ b/src/features/Acceptance/Viewer/ReadOnly/Discussion.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { useActivityTime } from '@/hooks/useActivityTime';
import { useAcceptanceScope } from '../AcceptanceScope';
+import AccessRequestEntry from '../Comments/AccessRequestEntry';
import CommentContent from '../Comments/CommentContent';
import { buildDiscussionTimeline } from '../Comments/discussionTimeline';
import { styles } from '../Comments/styles';
@@ -127,6 +128,15 @@ const ReadDiscussion = () => {
/>
);
}
+ if (entry.kind === 'accessRequest')
+ return (
+ <AccessRequestEntry
+ at={entry.at}
+ canManage={false}
+ key={entry.request.id}
+ request={entry.request}
+ />
+ );
// A circled note reads as its thread; the picture it points at stays on
// the check section of this report.
if (entry.kind === 'region')
diff --git a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx
index c5e996b78c2..523757a5386 100644
--- a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx
+++ b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx
@@ -20,7 +20,11 @@ import { acceptanceCheckPath, useAcceptanceRouteBase } from '../routes';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
import { useAcceptanceTurn } from '../useAcceptanceTurn';
import { formatAcceptanceCountsText, LIVE_ACCEPTANCE_STATUSES } from '../verdict';
-import { canReviewAcceptance, isReadOnlyAcceptanceDecider } from '../visibility';
+import {
+ canRejectAcceptanceOnly,
+ canReviewAcceptance,
+ isReadOnlyAcceptanceDecider,
+} from '../visibility';
import DecisionBar from './DecisionBar';
import FeedbackDrawer, { type FeedbackListEntry } from './FeedbackDrawer';
import { draftRepairPromptInMobile } from './mobileBridge';
@@ -41,9 +45,16 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
const { turn, setTurn } = useAcceptanceTurn(embedded);
const [pending, setPending] = useState(false);
const [feedbackOpen, setFeedbackOpen] = useState(false);
- const { approvals, canApprove } = useAcceptanceComments(acceptanceId);
- const readOnly = isReadOnlyAcceptanceDecider(data, canApprove);
- if (!data || (!canReviewAcceptance(data) && !readOnly) || data.acceptance.status === 'closed')
+ const { approvals, canApprove, canManageAccess, items } = useAcceptanceComments(acceptanceId);
+ // A grant is narrower than deciding, so it is checked before the read-only
+ // fallback: a teammate granted reject access gets the live reject button.
+ const rejectOnly = canRejectAcceptanceOnly(data);
+ const readOnly = !rejectOnly && isReadOnlyAcceptanceDecider(data, canApprove);
+ if (
+ !data ||
+ (!canReviewAcceptance(data) && !readOnly && !rejectOnly) ||
+ data.acceptance.status === 'closed'
+ )
return null;
if (flowPlanPhase(data.rounds.at(-1))) return null;
@@ -133,7 +144,23 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
const count = approvals.filter((approval) => approval.contextRoundIndex === roundIndex).length;
return count > 0 ? t('acceptance.comments.approvalCount', { count }) : undefined;
})();
- const subTextWithApprovals = [barTexts.subText, approvalText].filter(Boolean).join(' · ');
+ // Requests waiting on this decider, so a reviewer's ask does not sit unread
+ // in the discussion while the decider is here on the checks.
+ const pendingAccessCount = canManageAccess
+ ? items.filter(
+ (item) =>
+ item.kind === 'access_request' &&
+ !item.deletedAt &&
+ item.accessRequest?.status === 'pending',
+ ).length
+ : 0;
+ const accessText =
+ pendingAccessCount > 0
+ ? t('acceptance.access.pendingCount', { count: pendingAccessCount })
+ : undefined;
+ const subTextWithApprovals = [barTexts.subText, approvalText, accessText]
+ .filter(Boolean)
+ .join(' · ');
const currentRoundIndex = currentRound?.run.roundIndex ?? 0;
const groupFeedbackEntries = rounds.flatMap((round) =>
@@ -198,6 +225,7 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
needsFixCount={needsFixCount}
pending={pending}
readOnlyReason={readOnly ? t('acceptance.bar.readOnlyReason') : undefined}
+ rejectOnlyReason={rejectOnly ? t('acceptance.bar.rejectOnlyReason') : undefined}
repairing={acceptance.status === 'repairing'}
rerunAvailable={embedded}
rerunPending={false}
@@ -242,10 +270,10 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
// `origin` is only visible to the record owner, so this is the
// viewer's promise, not the server's gate — the copy path below
// opts out of dispatch explicitly.
- dispatchAvailable: Boolean(data.origin?.topic),
+ dispatchAvailable: Boolean(data.origin?.topic) || Boolean(data.repairDispatchAvailable),
acceptanceId: acceptance.id,
onConfirm: async (comment) => {
- if (!data.origin?.topic) {
+ if (!data.origin?.topic && !data.repairDispatchAvailable) {
const rejected = await runAction(() =>
rejectCopyOnly({
acceptanceId: acceptance.id,
diff --git a/src/features/Acceptance/Viewer/Review/DecisionBar.tsx b/src/features/Acceptance/Viewer/Review/DecisionBar.tsx
index b5a27057087..9fe6689316e 100644
--- a/src/features/Acceptance/Viewer/Review/DecisionBar.tsx
+++ b/src/features/Acceptance/Viewer/Review/DecisionBar.tsx
@@ -9,6 +9,7 @@ import {
Lock,
MessageSquarePlus,
RotateCcw,
+ UsersRound,
Wrench,
} from 'lucide-react';
import { memo, useEffect, useRef } from 'react';
@@ -245,6 +246,9 @@ interface DecisionBarProps {
/** The viewer may weigh in but not decide: the closing actions stay on the
bar, disabled, with this reason shown beside them. */
readOnlyReason?: string;
+ /** The viewer was granted reject access: reject is live, accept stays
+ disabled, and this reason says who accepts. */
+ rejectOnlyReason?: string;
/** A live round that is a dispatched repair — coloured as an in-progress task
(warning), not a neutral verify, to match the system's task-process cue. */
repairing?: boolean;
@@ -282,6 +286,7 @@ const DecisionBar = memo<DecisionBarProps>(
onRerun,
pending,
readOnlyReason,
+ rejectOnlyReason,
repairing,
rerunAvailable,
rerunPending,
@@ -367,16 +372,20 @@ const DecisionBar = memo<DecisionBarProps>(
{subText}
</Text>
)}
- {readOnlyReason && (
+ {(readOnlyReason || rejectOnlyReason) && (
<Flexbox
horizontal
align={'center'}
data-testid={'acceptance-decision-reason'}
gap={4}
>
- <Icon icon={Lock} size={12} style={{ flex: 'none' }} />
+ <Icon
+ icon={readOnlyReason ? Lock : UsersRound}
+ size={12}
+ style={{ flex: 'none' }}
+ />
<Text fontSize={12} type={'secondary'}>
- {readOnlyReason}
+ {readOnlyReason ?? rejectOnlyReason}
</Text>
</Flexbox>
)}
@@ -410,6 +419,18 @@ const DecisionBar = memo<DecisionBarProps>(
</Button>
</Flexbox>
)
+ ) : rejectOnlyReason ? (
+ // Granted reject access only: sending back is theirs, accepting is not.
+ state === 'settled' && (
+ <Flexbox horizontal className={styles.actions} gap={8}>
+ <Button disabled={pending} type={'fill'} onClick={onRejectComment}>
+ {t('acceptance.bar.rejectComment')}
+ </Button>
+ <Button disabled title={rejectOnlyReason} type={'fill'}>
+ {t('acceptance.actions.accept')}
+ </Button>
+ </Flexbox>
+ )
) : (
<Flexbox horizontal className={styles.actions} gap={8}>
{/* A dispatched send-back (repairing) keeps the copy entry alive —
diff --git a/src/features/Acceptance/Viewer/index.tsx b/src/features/Acceptance/Viewer/index.tsx
index 2cf5d933a5c..40638dc89c1 100644
--- a/src/features/Acceptance/Viewer/index.tsx
+++ b/src/features/Acceptance/Viewer/index.tsx
@@ -7,6 +7,7 @@ import { useParams } from 'react-router';
import { extractUuid } from '../utils';
import { AcceptanceOverview } from './AcceptanceOverview';
import { AcceptanceBundleGate, AcceptanceScope } from './AcceptanceScope';
+import CollaboratorConversationRail from './Conversation/CollaboratorConversationRail';
import { FlowPanelHostContext } from './Flow/FlowPanelHost';
import AcceptanceFocusWorkspace from './Focus/AcceptanceFocusWorkspace';
import AcceptanceLedgerRail from './History/AcceptanceLedgerRail';
@@ -85,6 +86,7 @@ const AcceptancePage = ({
{!focused && <AcceptanceOverview onDraftToComposer={onDraftToComposer} />}
</Flexbox>
<AcceptanceLedgerRail />
+ {!embedded && <CollaboratorConversationRail />}
</Flexbox>
<div className={styles.flowPanel} ref={setFlowPanelHostContext} />
</Flexbox>
diff --git a/src/features/Acceptance/Viewer/visibility.test.ts b/src/features/Acceptance/Viewer/visibility.test.ts
index 2e20457a4df..caa406b19c0 100644
--- a/src/features/Acceptance/Viewer/visibility.test.ts
+++ b/src/features/Acceptance/Viewer/visibility.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
canCommentOnAcceptanceEvidence,
+ canRejectAcceptanceOnly,
canReviewAcceptance,
canViewAcceptanceHistory,
isReadOnlyAcceptanceDecider,
@@ -72,3 +73,18 @@ describe('isReadOnlyAcceptanceDecider', () => {
expect(isReadOnlyAcceptanceDecider(undefined, true)).toBe(false);
});
});
+
+describe('canRejectAcceptanceOnly', () => {
+ it('turns on reject for a reviewer a decider granted reject access to', () => {
+ expect(canRejectAcceptanceOnly({ canReject: true, canReview: false })).toBe(true);
+ });
+
+ it('leaves a decider on the full bar', () => {
+ expect(canRejectAcceptanceOnly({ canReject: true, canReview: true })).toBe(false);
+ });
+
+ it('grants nothing without the grant, or before the bundle loads', () => {
+ expect(canRejectAcceptanceOnly({ canReject: false, canReview: false })).toBe(false);
+ expect(canRejectAcceptanceOnly(undefined)).toBe(false);
+ });
+});
diff --git a/src/features/Acceptance/Viewer/visibility.ts b/src/features/Acceptance/Viewer/visibility.ts
index 184bb39858f..371e6080a54 100644
--- a/src/features/Acceptance/Viewer/visibility.ts
+++ b/src/features/Acceptance/Viewer/visibility.ts
@@ -34,6 +34,16 @@ export const isReadOnlyAcceptanceDecider = (
canApprove: boolean,
) => Boolean(bundle) && !canReviewAcceptance(bundle) && canApprove;
+/**
+ * Whether the viewer may send the delivery back but not otherwise decide it:
+ * a decider granted them reject access. The server widens `canReject` by the
+ * same grant the reject mutation honours, and the repair it starts runs on the
+ * owner's agent.
+ */
+export const canRejectAcceptanceOnly = (
+ bundle?: { canReject?: boolean; canReview?: boolean } | null,
+) => Boolean(bundle?.canReject) && !bundle?.canReview;
+
/** Evidence discussion follows comment access, independently of review decisions. */
export const canCommentOnAcceptanceEvidence = (
bundle: { isOwner: boolean } | null | undefined,
diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsx
index e673e8ce0f5..5b026ece912 100644
--- a/src/features/Conversation/Error/index.test.tsx
+++ b/src/features/Conversation/Error/index.test.tsx
@@ -16,6 +16,7 @@ const dynamicComponentPropsMock = vi.hoisted(() => vi.fn());
const serverConfigMock = vi.hoisted(() => ({ enableBusinessFeatures: false }));
const shareContextMock = vi.hoisted(() => ({ topicShareId: '' }));
+const transcriptSourceMock = vi.hoisted(() => ({ value: 'chat' as 'chat' | 'static' }));
const delAndRegenerateMessageMock = vi.hoisted(() => vi.fn());
const detectHeterogeneousAgentCommandMock = vi.hoisted(() => vi.fn());
const cancelHeteroContinuationMock = vi.hoisted(() => vi.fn());
@@ -182,6 +183,7 @@ vi.mock('@/features/Conversation/store', () => ({
useConversationStore: (selector: (state: unknown) => unknown) =>
selector({
context: { ...conversationContextMock, ...shareContextMock },
+ transcriptSource: transcriptSourceMock.value,
cancelHeteroContinuation: cancelHeteroContinuationMock,
delAndRegenerateMessage: delAndRegenerateMessageMock,
deleteMessage: vi.fn(),
@@ -217,6 +219,7 @@ describe('ErrorMessageExtra', () => {
businessSlot.render = false;
serverConfigMock.enableBusinessFeatures = false;
shareContextMock.topicShareId = '';
+ transcriptSourceMock.value = 'chat';
businessErrorContentMock.mockReturnValue({
errorType: undefined,
hideMessage: false,
@@ -276,6 +279,23 @@ describe('ErrorMessageExtra', () => {
expect(screen.queryByText('card-retry')).toBeNull();
});
+ it('offers no retry on a static transcript, which nothing could regenerate', () => {
+ transcriptSourceMock.value = 'static';
+ displayMessageMock.set('msg-static', { parentId: 'user-1' });
+
+ render(
+ <ErrorMessageExtra
+ error={{ message: 'provider exploded' }}
+ data={{
+ error: { body: { provider: 'openai' }, type: 'ProviderBizError' } as any,
+ id: 'msg-static',
+ }}
+ />,
+ );
+
+ expect(screen.queryByText('card-retry')).toBeNull();
+ });
+
it('offers the trace-id report card a retry as well', () => {
serverConfigMock.enableBusinessFeatures = true;
displayMessageMock.set('msg-trace', { parentId: 'user-1' });
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index b0c8fdf872d..94af2618c9a 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -331,6 +331,10 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
const conversationAgentId = useConversationStore(contextSelectors.agentId);
const conversationTopicId = useConversationStore(contextSelectors.topicId);
const isSharedTopic = useConversationStore((s) => !!s.context?.topicShareId);
+ // A static transcript (a render gallery, a preview, a conversation read
+ // through a grant) is held, never synced: nothing behind it could take the
+ // delete-and-regenerate, so it must not offer one.
+ const isStaticTranscript = useConversationStore((s) => s.transcriptSource === 'static');
const sessionErrorBody = error?.body;
const rawErrorMessage = getRawErrorMessage(error);
const errorDetails = getErrorDetails(error);
@@ -359,7 +363,7 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
// to retrying this message on our own, but only advertise it when that can
// actually run: a block that isn't a top-level displayMessage, or one with no
// parent user turn, would delete itself and regenerate nothing.
- const canRetry = canCreate && (!!onRegenerate || !!ownParentId);
+ const canRetry = !isStaticTranscript && canCreate && (!!onRegenerate || !!ownParentId);
const handleRetryAgentMessage = useCallback(() => {
if (!canRetry) return;
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 3dbe6245a7a..1331c4dde9e 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -148,6 +148,14 @@ export const acceptanceCommentKeys = {
]),
};
+// ---- acceptance collaboration -------------------------------------------
+export const acceptanceCollaborationKeys = {
+ conversation: def('acceptanceCollaboration:conversation', (acceptanceId: string) => [
+ 'acceptanceCollaboration:conversation',
+ acceptanceId,
+ ]),
+};
+
// ---- document comment ---------------------------------------------------
export const documentCommentKeys = {
anchors: def('documentComment:anchors', (workspaceId: string | null, documentId: string) => [
@@ -974,6 +982,7 @@ export const swrKeys = {
thread: threadKeys,
tool: toolKeys,
topic: topicKeys,
+ acceptanceCollaboration: acceptanceCollaborationKeys,
acceptanceComment: acceptanceCommentKeys,
documentComment: documentCommentKeys,
documentLike: documentLikeKeys,
diff --git a/src/services/acceptanceCollaboration.ts b/src/services/acceptanceCollaboration.ts
new file mode 100644
index 00000000000..0cce9d671a9
--- /dev/null
+++ b/src/services/acceptanceCollaboration.ts
@@ -0,0 +1,12 @@
+import { lambdaClient } from '@/libs/trpc/client';
+
+/** Edit-collaboration on an acceptance: its bound conversation, read and written as its owner. */
+class AcceptanceCollaborationService {
+ getConversation = (acceptanceId: string) =>
+ lambdaClient.acceptance.getOriginConversation.query({ id: acceptanceId });
+
+ send = (acceptanceId: string, content: string) =>
+ lambdaClient.acceptance.sendToOriginAgent.mutate({ content, id: acceptanceId });
+}
+
+export const acceptanceCollaborationService = new AcceptanceCollaborationService();
diff --git a/src/services/acceptanceComment.ts b/src/services/acceptanceComment.ts
index cd296cd8962..52b50d10861 100644
--- a/src/services/acceptanceComment.ts
+++ b/src/services/acceptanceComment.ts
@@ -1,8 +1,15 @@
-import type { AcceptanceCommentList, CreateAcceptanceCommentInput } from '@lobechat/types';
+import type {
+ AcceptanceAccessDecision,
+ AcceptanceCommentList,
+ CreateAcceptanceCommentInput,
+} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
class AcceptanceCommentService {
+ answerAccessRequest = (id: string, decision: AcceptanceAccessDecision) =>
+ lambdaClient.acceptanceComment.answerAccessRequest.mutate({ decision, id });
+
create = (input: CreateAcceptanceCommentInput) =>
lambdaClient.acceptanceComment.create.mutate(input);
@@ -11,6 +18,13 @@ class AcceptanceCommentService {
list = (acceptanceId: string): Promise<AcceptanceCommentList> =>
lambdaClient.acceptanceComment.list.query({ acceptanceId });
+ requestAccess = (input: {
+ acceptanceId: string;
+ clientId: string;
+ content?: string;
+ contextRunId?: string;
+ }) => lambdaClient.acceptanceComment.requestAccess.mutate(input);
+
react = (id: string, emoji: string, on: boolean) =>
lambdaClient.acceptanceComment.react.mutate({ emoji, id, on });