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.

🐛 fix(acceptance): list every workspace acceptance under All, default to Created by me, and add only-me visibility (#21804)

Rdmclin22bec94ff7e22
diff --git a/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts b/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts
index 271e7a8e930..b7a2f7a5c30 100644
--- a/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/acceptanceComment.access.test.ts
@@ -327,6 +327,33 @@ describe('acceptanceCommentRouter workspace scoping', () => {
expect(data.authorUserId).toBe(visitorId);
});
+ it('hides an only-me delivery from its own workspace', async () => {
+ const [hidden] = await serverDB
+ .insert(acceptances)
+ .values({
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'owner',
+ workspaceId,
+ })
+ .returning();
+
+ await expect(
+ caller(viewerId).create({
+ acceptanceId: hidden.id,
+ clientId: `c-${randomUUID()}`,
+ content: 'can I see this?',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ const { data } = await caller(ownerId).create({
+ acceptanceId: hidden.id,
+ clientId: `c-${randomUUID()}`,
+ content: 'note to self',
+ });
+ expect(data.authorUserId).toBe(ownerId);
+ });
+
// Read-only in the workspace means read-only on its private deliveries, the
// same rule topic and document comments enforce.
it('keeps a workspace viewer read-only on a private delivery', async () => {
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts b/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
index 4e1407b998f..d49dc65c45c 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceCommentAccess.ts
@@ -1,3 +1,4 @@
+import { isWorkspaceReadableVisibility } from '@lobechat/const/verify';
import { TRPCError } from '@trpc/server';
import { eq } from 'drizzle-orm';
@@ -32,7 +33,8 @@ export interface AcceptanceCommentAccess {
*
* Reading follows the bundle: the creator, anyone when the acceptance is
* `public`, or a member of the acceptance's OWN workspace (not the caller's
- * active one).
+ * active one). An `owner` acceptance is the creator's alone: membership and
+ * project roles open nothing.
*
* Remarking is as wide as READING A PUBLIC LINK, minus anonymity — whoever was
* handed the link can answer the evidence in front of them, and a shared
@@ -61,6 +63,8 @@ export async function resolveAcceptanceCommentAccess(
if (acceptance.subjectType === 'site') return resolveSiteReviewAccess(db, userId, acceptance);
const isOwner = Boolean(userId) && userId === acceptance.userId;
+ if (!isOwner && !isWorkspaceReadableVisibility(acceptance.visibility))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });
const member =
!isOwner && userId && acceptance.workspaceId
? await new WorkspaceMemberModel(db, userId).getMember(acceptance.workspaceId, userId)
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceReadScope.ts b/apps/server/src/routers/lambda/_helpers/acceptanceReadScope.ts
index bf1903b15b3..c886e0f5486 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceReadScope.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceReadScope.ts
@@ -1,3 +1,5 @@
+import { isWorkspaceReadableVisibility } from '@lobechat/const/verify';
+
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { AcceptanceItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
@@ -20,7 +22,7 @@ export const canReadAcceptance = async (
}
if (ctx.userId && ctx.userId === acceptance.userId) return true;
if (acceptance.visibility === 'public') return true;
- if (!ctx.userId) return false;
+ if (!ctx.userId || !isWorkspaceReadableVisibility(acceptance.visibility)) return false;
// Membership in the acceptance's OWN workspace — not the viewer's currently
// active one, which may be a different workspace entirely.
if (acceptance.workspaceId) {
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts
index 4d47dd8e7c9..1ed4e40f707 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.test.ts
@@ -14,8 +14,13 @@ vi.mock('@/database/models/workspaceMember', () => ({
}));
const db = {} as never;
-const row = (userId: string, workspaceId: string | null) =>
- ({ userId, workspaceId }) as { userId: string; workspaceId: string | null };
+type Visibility = 'owner' | 'private' | 'public';
+const row = (userId: string, workspaceId: string | null, visibility: Visibility = 'private') =>
+ ({ userId, visibility, workspaceId }) as {
+ userId: string;
+ visibility: Visibility;
+ workspaceId: string | null;
+ };
beforeEach(() => {
getMember.mockReset();
@@ -84,6 +89,17 @@ describe('canManageAcceptance', () => {
expect(getMember).not.toHaveBeenCalled();
});
+ it("keeps an only-me delivery its creator's, whatever the teammate's role", async () => {
+ getMember.mockResolvedValue({ role: 'owner' });
+
+ await expect(
+ canManageAcceptance({ serverDB: db, userId: 'me' }, row('teammate', 'ws_a', 'owner')),
+ ).resolves.toBe(false);
+ await expect(
+ canManageAcceptance({ serverDB: db, userId: 'me' }, row('me', 'ws_a', 'owner')),
+ ).resolves.toBe(true);
+ });
+
it('refuses an anonymous caller', async () => {
await expect(canManageAcceptance({ serverDB: db }, row('teammate', 'ws_a'))).resolves.toBe(
false,
@@ -122,6 +138,8 @@ describe('filterManageableAcceptances', () => {
row('teammate', 'ws_member'),
row('teammate', 'ws_viewer'),
row('teammate', null),
+ row('teammate', 'ws_owned', 'owner'),
+ row('me', 'ws_owned', 'owner'),
];
await expect(
filterManageableAcceptances({ serverDB: db, userId: 'me' }, rows),
@@ -131,6 +149,7 @@ describe('filterManageableAcceptances', () => {
row('teammate', 'ws_owned'),
row('teammate', 'ws_admin'),
row('teammate', 'ws_member'),
+ row('me', 'ws_owned', 'owner'),
]);
});
diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts
index 1c03362523f..ec9c497a7e7 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceWriteScope.ts
@@ -1,3 +1,5 @@
+import { isWorkspaceReadableVisibility } from '@lobechat/const/verify';
+
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { AcceptanceItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
@@ -26,9 +28,10 @@ export interface AcceptanceScopeCtx {
* all. Reading membership off the row's own workspace is what makes the rule
* stable no matter where the caller happens to be standing, and it is the same
* rule `getBundle` reports as `canReview`, so the page can never advertise an
- * action the mutation would refuse.
+ * action the mutation would refuse. An `owner` acceptance is managed by its
+ * creator alone.
*/
-type ScopedAcceptance = Pick<AcceptanceItem, 'userId' | 'workspaceId'> & {
+type ScopedAcceptance = Pick<AcceptanceItem, 'userId' | 'visibility' | 'workspaceId'> & {
subjectType?: AcceptanceItem['subjectType'];
};
@@ -40,6 +43,7 @@ export async function canManageAcceptance(
if (acceptance.subjectType === 'site') return false;
if (ctx.userId && ctx.userId === acceptance.userId) return true;
if (!ctx.userId || !acceptance.workspaceId) return false;
+ if (!isWorkspaceReadableVisibility(acceptance.visibility)) return false;
const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(
acceptance.workspaceId,
@@ -64,7 +68,12 @@ export async function filterManageableAcceptances<T extends ScopedAcceptance>(
const foreignWorkspaceIds = [
...new Set(
rows
- .filter((row) => row.userId !== userId && row.workspaceId)
+ .filter(
+ (row) =>
+ row.userId !== userId &&
+ row.workspaceId &&
+ isWorkspaceReadableVisibility(row.visibility),
+ )
.map((row) => row.workspaceId as string),
),
];
@@ -77,6 +86,8 @@ export async function filterManageableAcceptances<T extends ScopedAcceptance>(
(row) =>
row.subjectType !== 'site' &&
(row.userId === userId ||
- (row.workspaceId ? isDeciderRole(roles.get(row.workspaceId)) : false)),
+ (row.workspaceId && isWorkspaceReadableVisibility(row.visibility)
+ ? isDeciderRole(roles.get(row.workspaceId))
+ : false)),
);
}
diff --git a/apps/server/src/routers/lambda/acceptance/listManagement.ts b/apps/server/src/routers/lambda/acceptance/listManagement.ts
index dd0c8e6217b..1e99be5a445 100644
--- a/apps/server/src/routers/lambda/acceptance/listManagement.ts
+++ b/apps/server/src/routers/lambda/acceptance/listManagement.ts
@@ -48,7 +48,9 @@ const acceptanceListFiltersSchema = z.object({
* delete it. "Participated" rows are often someone else's, so the panel must
* know which menus to offer instead of letting the write fail as NOT_FOUND.
*/
-const withManageFlag = async <T extends Pick<AcceptanceItem, 'id' | 'userId' | 'workspaceId'>>(
+const withManageFlag = async <
+ T extends Pick<AcceptanceItem, 'id' | 'userId' | 'visibility' | 'workspaceId'>,
+>(
ctx: { serverDB: LobeChatDatabase; userId: string },
rows: T[],
): Promise<Array<T & { canManage: boolean }>> => {
@@ -135,13 +137,19 @@ export const listManagementRouter = router({
}),
/**
* Flip who can read the acceptance beyond its creator. Creation defaults are
- * scope-dependent (personal → public, workspace → private); this is the
- * deliberate override.
+ * scope-dependent (personal → public, workspace → private, i.e. the whole
+ * team); this is the deliberate override. Only the creator may make it
+ * `owner`: a teammate must not hide someone else's delivery from its team.
*/
setVisibility: acceptanceWriteProcedure
.input(z.object({ id: z.string(), visibility: z.enum(acceptanceVisibilities) }))
.mutation(async ({ ctx, input }) => {
const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);
+ if (input.visibility === 'owner' && acceptance.userId !== ctx.userId)
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the creator can make an acceptance private',
+ });
const updated = await service.acceptanceModel.update(acceptance.id, {
visibility: input.visibility,
@@ -224,7 +232,7 @@ export const listManagementRouter = router({
const rows =
resolvableIds.length > 0
? await ctx.serverDB.query.acceptances.findMany({
- columns: { id: true, userId: true, workspaceId: true },
+ columns: { id: true, userId: true, visibility: true, workspaceId: true },
where: inArray(acceptances.id, resolvableIds),
})
: [];
diff --git a/apps/server/src/routers/lambda/verify/index.test.ts b/apps/server/src/routers/lambda/verify/index.test.ts
index f18b2ed9bd3..86606638db0 100644
--- a/apps/server/src/routers/lambda/verify/index.test.ts
+++ b/apps/server/src/routers/lambda/verify/index.test.ts
@@ -590,6 +590,27 @@ describe('verifyRouter', () => {
expect(bundle).toMatchObject({ isOwner: true, run: { id: RUN_UUID } });
});
+ it("keeps an only-me run from its workspace's members", async () => {
+ const run = {
+ goal: 'Ship a working page',
+ id: RUN_UUID,
+ title: 'Run report',
+ userId: 'owner-user',
+ visibility: 'owner',
+ workspaceId: 'ws-1',
+ };
+ modelMocks.getServerDB.mockResolvedValue({
+ query: {
+ verifyReports: { findFirst: vi.fn(async () => null) },
+ verifyRuns: { findFirst: vi.fn(async () => run) },
+ },
+ select: vi.fn().mockReturnValueOnce(selectRows([])),
+ });
+
+ const teammate = verifyRouter.createCaller({ userId: 'teammate-user' } as any);
+ expect(await teammate.getReportBundle({ verifyRunId: RUN_UUID })).toBeNull();
+ });
+
it('reads a standalone report without a logged-in user', async () => {
const run = {
goal: 'Ship a working page',
diff --git a/apps/server/src/routers/lambda/verifyRunReport.ts b/apps/server/src/routers/lambda/verifyRunReport.ts
index fa68814f3a4..3e071b0e924 100644
--- a/apps/server/src/routers/lambda/verifyRunReport.ts
+++ b/apps/server/src/routers/lambda/verifyRunReport.ts
@@ -1,3 +1,4 @@
+import { isWorkspaceReadableVisibility } from '@lobechat/const/verify';
import type { LobeChatDatabase } from '@lobechat/database';
import { asc, eq } from 'drizzle-orm';
import pMap from 'p-map';
@@ -25,7 +26,7 @@ const verifyRunIdInputSchema = z.object({ verifyRunId: z.string() });
/**
* Load a run through the read capability its id grants: a `public` run is
* readable by anyone holding the id; a `private` one only by its owner and (for
- * workspace scope) members of that workspace. Missing, malformed and denied all
+ * workspace scope) members of that workspace; an `owner` one by its owner alone. Missing, malformed and denied all
* read as `null` — existence must not leak.
*/
const findReadableVerifyRun = async (
@@ -43,7 +44,7 @@ const findReadableVerifyRun = async (
const isOwner = Boolean(ctx.userId) && ctx.userId === run.userId;
let canRead = isOwner || run.visibility === 'public';
- if (!canRead && ctx.userId && run.workspaceId) {
+ if (!canRead && ctx.userId && run.workspaceId && isWorkspaceReadableVisibility(run.visibility)) {
const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(
run.workspaceId,
ctx.userId,
diff --git a/apps/server/src/services/acceptanceReview/projectAccess.test.ts b/apps/server/src/services/acceptanceReview/projectAccess.test.ts
index eb92aa8684f..f348974b646 100644
--- a/apps/server/src/services/acceptanceReview/projectAccess.test.ts
+++ b/apps/server/src/services/acceptanceReview/projectAccess.test.ts
@@ -200,4 +200,28 @@ describe('site review access', () => {
);
expect(await canRead(strangerId)).toBe(false);
});
+
+ it('keeps an only-me project delivery from teammates and project admins', async () => {
+ await add(teammateId, 'admin');
+ const [acceptance] = await db
+ .insert(acceptances)
+ .values({
+ projectId,
+ subjectId: randomUUID(),
+ subjectType: 'standalone',
+ userId: ownerId,
+ visibility: 'owner',
+ workspaceId,
+ })
+ .returning();
+ const canRead = (userId: string) => canReadAcceptance({ serverDB: db, userId }, acceptance);
+
+ expect(await canRead(ownerId)).toBe(true);
+ expect(await canRead(teammateId)).toBe(false);
+ expect(await canRead(viewerId)).toBe(false);
+ await expect(resolveAcceptanceCommentAccess(db, teammateId, acceptance.id)).rejects.toThrow(
+ TRPCError,
+ );
+ await expect(resolveAcceptanceCommentAccess(db, ownerId, acceptance.id)).resolves.toBeTruthy();
+ });
});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts
index 13ea1b03439..d6869c95077 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceListSearch.test.ts
@@ -170,6 +170,44 @@ describe('AcceptanceService.listWithSubjects', () => {
).toEqual(['Task mine', 'Task theirs-0', 'Topic theirs-1', 'X-3', null]);
});
+ it("resolves a teammate's workspace row through the unscoped read", async () => {
+ mocks.resolveTasks.mockReset();
+ mocks.resolveTasks.mockResolvedValue({
+ byRef: new Map([['mine', { id: 'mine', identifier: 'T-1', name: 'Task mine' }]]),
+ });
+ mocks.resolveTopics.mockResolvedValue([]);
+ mocks.resolveDocuments.mockResolvedValue([]);
+ mocks.taskScopes.length = 0;
+
+ const rows = [
+ { id: 'a', subjectId: 'mine', subjectType: 'task', userId: 'user-1', workspaceId: 'ws-1' },
+ // The teammate's private task is invisible to the caller's scoped TaskModel.
+ { id: 'b', subjectId: 'theirs', subjectType: 'task', userId: 'user-2', workspaceId: 'ws-1' },
+ ];
+ const db = {
+ query: {
+ documents: { findMany: vi.fn().mockResolvedValue([]) },
+ tasks: {
+ findMany: vi
+ .fn()
+ .mockResolvedValue([{ id: 'theirs', identifier: 'T-2', name: 'Task theirs' }]),
+ },
+ topics: { findMany: vi.fn().mockResolvedValue([]) },
+ },
+ };
+ const service = new AcceptanceService(db as any, 'user-1', 'ws-1') as any;
+ service.acceptanceModel = { query: vi.fn().mockResolvedValue(rows) };
+ service.latestCheckCounts = vi.fn().mockResolvedValue(new Map());
+ service.resolveProjects = vi.fn().mockResolvedValue(new Map());
+
+ const result = await service.listWithSubjects({ q: 'theirs', scope: 'all' });
+
+ expect(mocks.resolveTasks).toHaveBeenCalledWith(['mine']);
+ expect(
+ result.map(({ subject }: { subject: { title: string | null } }) => subject.title),
+ ).toEqual(['Task theirs']);
+ });
+
it('reads check counts for rows of any owner in two batched queries', async () => {
const db = {
query: {
diff --git a/apps/server/src/services/verify/acceptanceService/listing.ts b/apps/server/src/services/verify/acceptanceService/listing.ts
index 76ceec2f984..5f967ce0c67 100644
--- a/apps/server/src/services/verify/acceptanceService/listing.ts
+++ b/apps/server/src/services/verify/acceptanceService/listing.ts
@@ -179,10 +179,16 @@ export const latestCheckCounts = async (
return out;
};
+/**
+ * Rows the caller created in the active scope — their subjects resolve through
+ * the scoped models. A teammate's row in the same workspace does not qualify:
+ * its private task/topic/document is hidden from the caller's models, though
+ * the list already granted the row itself, so it resolves like any other
+ * owner's.
+ */
export const isInOwnScope = (deps: AcceptanceServiceDeps, row: AcceptanceItem) =>
- row.workspaceId
- ? row.workspaceId === deps.workspaceId
- : !deps.workspaceId && row.userId === deps.userId;
+ row.userId === deps.userId &&
+ (row.workspaceId ? row.workspaceId === deps.workspaceId : !deps.workspaceId);
export const resolveForeignSubjects = async (
deps: AcceptanceServiceDeps,
diff --git a/locales/ar/verify.json b/locales/ar/verify.json
index ece7d97ec09..81ada49c1b6 100644
--- a/locales/ar/verify.json
+++ b/locales/ar/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "غير مؤكد",
"acceptance.roundStatus.verifying": "قيد التحقق",
"acceptance.share.copyFailed": "تعذر نسخ الرابط. انسخه من شريط العنوان.",
- "acceptance.share.makePrivate": "تقييد الوصول",
- "acceptance.share.makePublic": "السماح بالوصول عبر الرابط",
"acceptance.share.privateHint": "سيتمكن فقط المنشئ وأعضاء مساحة العمل من قراءة هذا القبول وجولاته. لا يمكن استرجاع النسخ التي تم تنزيلها بالفعل.",
"acceptance.share.publicHint": "سيتمكن أي شخص لديه الرابط من قراءة هذا القبول، جميع جولاته، الأدلة والتعليقات. يمكن للزوار المسجلين أيضًا التعليق والتوضيح. راجع المحتوى قبل جعله عامًا.",
"acceptance.share.saved": "تم تحديث أذونات المشاركة",
diff --git a/locales/bg-BG/verify.json b/locales/bg-BG/verify.json
index 93951ee3815..87f0e47c57d 100644
--- a/locales/bg-BG/verify.json
+++ b/locales/bg-BG/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Несигурно",
"acceptance.roundStatus.verifying": "В процес на проверка",
"acceptance.share.copyFailed": "Неуспешно копиране на връзката. Копирайте я от адресната лента.",
- "acceptance.share.makePrivate": "Ограничете достъпа",
- "acceptance.share.makePublic": "Позволете достъп с връзката",
"acceptance.share.privateHint": "Само създателят и членовете на работното пространство ще могат да четат това приемане и неговите кръгове. Копията, които вече са изтеглени, не могат да бъдат оттеглени.",
"acceptance.share.publicHint": "Всеки с връзката ще може да чете това приемане, всичките му кръгове, доказателства и коментари. Влезлите посетители също могат да коментират и анотират. Прегледайте съдържанието, преди да го направите публично.",
"acceptance.share.saved": "Разрешенията за споделяне са актуализирани",
diff --git a/locales/de-DE/verify.json b/locales/de-DE/verify.json
index eb8baf3aa11..7421a48a404 100644
--- a/locales/de-DE/verify.json
+++ b/locales/de-DE/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Unsicher",
"acceptance.roundStatus.verifying": "In Bearbeitung",
"acceptance.share.copyFailed": "Der Link konnte nicht kopiert werden. Kopieren Sie ihn aus der Adressleiste.",
- "acceptance.share.makePrivate": "Zugriff einschränken",
- "acceptance.share.makePublic": "Zugriff mit dem Link erlauben",
"acceptance.share.privateHint": "Nur der Ersteller und Mitglieder des Arbeitsbereichs können diese Akzeptanz und ihre Runden lesen. Bereits heruntergeladene Kopien können nicht zurückgerufen werden.",
"acceptance.share.publicHint": "Jeder mit dem Link kann diese Akzeptanz, alle ihre Runden, Beweise und Kommentare lesen. Angemeldete Besucher können auch kommentieren und annotieren. Überprüfen Sie den Inhalt, bevor Sie ihn öffentlich machen.",
"acceptance.share.saved": "Freigabeberechtigungen aktualisiert",
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index ab1044d9512..1357f6d6062 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -439,9 +439,12 @@
"acceptance.roundStatus.repairing": "Repairing",
"acceptance.roundStatus.uncertain": "Uncertain",
"acceptance.roundStatus.verifying": "In progress",
+ "acceptance.share.access.owner": "Only me",
+ "acceptance.share.access.public": "Anyone with the link",
+ "acceptance.share.access.title": "Who can see",
+ "acceptance.share.access.workspace": "Workspace members",
"acceptance.share.copyFailed": "Could not copy the link. Copy it from the address bar.",
- "acceptance.share.makePrivate": "Restrict access",
- "acceptance.share.makePublic": "Allow access with the link",
+ "acceptance.share.ownerHint": "Only you will be able to read this acceptance and its rounds. It leaves your teammates' lists, and links they hold stop opening.",
"acceptance.share.privateHint": "Only the creator and workspace members will be able to read this acceptance and its rounds. Copies already downloaded cannot be recalled.",
"acceptance.share.publicHint": "Anyone with the link will be able to read this acceptance, all its rounds, evidence and comments. Signed-in visitors can also comment and annotate. Review the content before making it public.",
"acceptance.share.saved": "Sharing permissions updated",
diff --git a/locales/es-ES/verify.json b/locales/es-ES/verify.json
index 8ca4ceb4aa8..8f4c41464b8 100644
--- a/locales/es-ES/verify.json
+++ b/locales/es-ES/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Incierto",
"acceptance.roundStatus.verifying": "En progreso",
"acceptance.share.copyFailed": "No se pudo copiar el enlace. Cópialo desde la barra de direcciones.",
- "acceptance.share.makePrivate": "Restringir acceso",
- "acceptance.share.makePublic": "Permitir acceso con el enlace",
"acceptance.share.privateHint": "Solo el creador y los miembros del espacio de trabajo podrán leer esta aceptación y sus rondas. Las copias ya descargadas no se pueden recuperar.",
"acceptance.share.publicHint": "Cualquiera con el enlace podrá leer esta aceptación, todas sus rondas, evidencias y comentarios. Los visitantes registrados también pueden comentar y anotar. Revisa el contenido antes de hacerlo público.",
"acceptance.share.saved": "Permisos de compartición actualizados",
diff --git a/locales/fa-IR/verify.json b/locales/fa-IR/verify.json
index 78430c90ba9..0949f2e5b0a 100644
--- a/locales/fa-IR/verify.json
+++ b/locales/fa-IR/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "نامشخص",
"acceptance.roundStatus.verifying": "در حال بررسی",
"acceptance.share.copyFailed": "لینک را نمی‌توان کپی کرد. آن را از نوار آدرس کپی کنید.",
- "acceptance.share.makePrivate": "محدود کردن دسترسی",
- "acceptance.share.makePublic": "اجازه دسترسی با لینک",
"acceptance.share.privateHint": "فقط سازنده و اعضای فضای کاری قادر به خواندن این تأییدیه و دورهای آن خواهند بود. نسخه‌های دانلود شده قبلی قابل بازخوانی نیستند.",
"acceptance.share.publicHint": "هر کسی که لینک را داشته باشد می‌تواند این تأییدیه، تمام دورهای آن، شواهد و نظرات را بخواند. بازدیدکنندگان وارد شده نیز می‌توانند نظر دهند و حاشیه‌نویسی کنند. قبل از عمومی کردن محتوا، آن را بررسی کنید.",
"acceptance.share.saved": "مجوزهای اشتراک‌گذاری به‌روزرسانی شد",
diff --git a/locales/fr-FR/verify.json b/locales/fr-FR/verify.json
index ffe4cf515d3..5eb8ae92491 100644
--- a/locales/fr-FR/verify.json
+++ b/locales/fr-FR/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Incertain",
"acceptance.roundStatus.verifying": "En cours",
"acceptance.share.copyFailed": "Impossible de copier le lien. Copiez-le depuis la barre d'adresse.",
- "acceptance.share.makePrivate": "Restreindre l'accès",
- "acceptance.share.makePublic": "Autoriser l'accès avec le lien",
"acceptance.share.privateHint": "Seul le créateur et les membres de l'espace de travail pourront lire cette acceptation et ses phases. Les copies déjà téléchargées ne peuvent pas être rappelées.",
"acceptance.share.publicHint": "Toute personne disposant du lien pourra lire cette acceptation, toutes ses phases, preuves et commentaires. Les visiteurs connectés peuvent également commenter et annoter. Vérifiez le contenu avant de le rendre public.",
"acceptance.share.saved": "Permissions de partage mises à jour",
diff --git a/locales/it-IT/verify.json b/locales/it-IT/verify.json
index 2b54a637043..99e7e082b50 100644
--- a/locales/it-IT/verify.json
+++ b/locales/it-IT/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Incerto",
"acceptance.roundStatus.verifying": "In corso",
"acceptance.share.copyFailed": "Impossibile copiare il link. Copialo dalla barra degli indirizzi.",
- "acceptance.share.makePrivate": "Limita l'accesso",
- "acceptance.share.makePublic": "Consenti l'accesso con il link",
"acceptance.share.privateHint": "Solo il creatore e i membri del workspace potranno leggere questa accettazione e i suoi round. Le copie già scaricate non possono essere richiamate.",
"acceptance.share.publicHint": "Chiunque abbia il link potrà leggere questa accettazione, tutti i suoi round, le prove e i commenti. I visitatori connessi possono anche commentare e annotare. Rivedi il contenuto prima di renderlo pubblico.",
"acceptance.share.saved": "Permessi di condivisione aggiornati",
diff --git a/locales/ja-JP/verify.json b/locales/ja-JP/verify.json
index 03bc4c92f77..c1f34621033 100644
--- a/locales/ja-JP/verify.json
+++ b/locales/ja-JP/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "不確定",
"acceptance.roundStatus.verifying": "進行中",
"acceptance.share.copyFailed": "リンクをコピーできませんでした。アドレスバーからコピーしてください。",
- "acceptance.share.makePrivate": "アクセスを制限する",
- "acceptance.share.makePublic": "リンクでのアクセスを許可する",
"acceptance.share.privateHint": "作成者とワークスペースメンバーのみがこの承認とそのラウンドを閲覧できます。既にダウンロードされたコピーは取り消せません。",
"acceptance.share.publicHint": "リンクを持つ誰もがこの承認、そのすべてのラウンド、証拠、コメントを閲覧できます。サインインした訪問者はコメントや注釈を追加することもできます。公開する前に内容を確認してください。",
"acceptance.share.saved": "共有権限が更新されました",
diff --git a/locales/ko-KR/verify.json b/locales/ko-KR/verify.json
index 5df5924671b..3cedc2ee2f1 100644
--- a/locales/ko-KR/verify.json
+++ b/locales/ko-KR/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "불확실",
"acceptance.roundStatus.verifying": "진행 중",
"acceptance.share.copyFailed": "링크를 복사할 수 없습니다. 주소 표시줄에서 복사하세요.",
- "acceptance.share.makePrivate": "접근 제한",
- "acceptance.share.makePublic": "링크로 접근 허용",
"acceptance.share.privateHint": "창작자와 작업 공간 멤버만 이 승인 및 라운드를 읽을 수 있습니다. 이미 다운로드된 복사본은 회수할 수 없습니다.",
"acceptance.share.publicHint": "링크를 가진 누구나 이 승인, 모든 라운드, 증거 및 댓글을 읽을 수 있습니다. 로그인한 방문자는 댓글을 달고 주석을 추가할 수도 있습니다. 공개하기 전에 내용을 검토하세요.",
"acceptance.share.saved": "공유 권한이 업데이트되었습니다",
diff --git a/locales/nl-NL/verify.json b/locales/nl-NL/verify.json
index 1a0533d0457..d8c0e904534 100644
--- a/locales/nl-NL/verify.json
+++ b/locales/nl-NL/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Onzeker",
"acceptance.roundStatus.verifying": "Bezig met verificatie",
"acceptance.share.copyFailed": "Kon de link niet kopiëren. Kopieer het vanuit de adresbalk.",
- "acceptance.share.makePrivate": "Toegang beperken",
- "acceptance.share.makePublic": "Toegang met de link toestaan",
"acceptance.share.privateHint": "Alleen de maker en werkruimtemedewerkers kunnen deze acceptatie en zijn rondes lezen. Kopieën die al zijn gedownload, kunnen niet worden teruggeroepen.",
"acceptance.share.publicHint": "Iedereen met de link kan deze acceptatie, al zijn rondes, bewijzen en opmerkingen lezen. Ingelogde bezoekers kunnen ook opmerkingen maken en annoteren. Controleer de inhoud voordat u deze openbaar maakt.",
"acceptance.share.saved": "Deelrechten bijgewerkt",
diff --git a/locales/pl-PL/verify.json b/locales/pl-PL/verify.json
index 08c11289303..d631f3e7cdf 100644
--- a/locales/pl-PL/verify.json
+++ b/locales/pl-PL/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Niepewne",
"acceptance.roundStatus.verifying": "W trakcie",
"acceptance.share.copyFailed": "Nie udało się skopiować linku. Skopiuj go z paska adresu.",
- "acceptance.share.makePrivate": "Ogranicz dostęp",
- "acceptance.share.makePublic": "Zezwól na dostęp za pomocą linku",
"acceptance.share.privateHint": "Tylko twórca i członkowie przestrzeni roboczej będą mogli czytać tę akceptację i jej rundy. Kopii już pobranych nie można cofnąć.",
"acceptance.share.publicHint": "Każdy z linkiem będzie mógł czytać tę akceptację, wszystkie jej rundy, dowody i komentarze. Zalogowani odwiedzający mogą również komentować i dodawać adnotacje. Przejrzyj treść przed jej upublicznieniem.",
"acceptance.share.saved": "Uprawnienia do udostępniania zostały zaktualizowane",
diff --git a/locales/pt-BR/verify.json b/locales/pt-BR/verify.json
index ea1feda3d48..fd15eed432d 100644
--- a/locales/pt-BR/verify.json
+++ b/locales/pt-BR/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Incerto",
"acceptance.roundStatus.verifying": "Em progresso",
"acceptance.share.copyFailed": "Não foi possível copiar o link. Copie-o da barra de endereço.",
- "acceptance.share.makePrivate": "Restringir acesso",
- "acceptance.share.makePublic": "Permitir acesso com o link",
"acceptance.share.privateHint": "Somente o criador e os membros do espaço de trabalho poderão ler esta aceitação e suas rodadas. Cópias já baixadas não podem ser revogadas.",
"acceptance.share.publicHint": "Qualquer pessoa com o link poderá ler esta aceitação, todas as suas rodadas, evidências e comentários. Visitantes conectados também podem comentar e anotar. Revise o conteúdo antes de torná-lo público.",
"acceptance.share.saved": "Permissões de compartilhamento atualizadas",
diff --git a/locales/ru-RU/verify.json b/locales/ru-RU/verify.json
index 2b155030a5e..6586d26a189 100644
--- a/locales/ru-RU/verify.json
+++ b/locales/ru-RU/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Неопределено",
"acceptance.roundStatus.verifying": "В процессе",
"acceptance.share.copyFailed": "Не удалось скопировать ссылку. Скопируйте её из адресной строки.",
- "acceptance.share.makePrivate": "Ограничить доступ",
- "acceptance.share.makePublic": "Разрешить доступ по ссылке",
"acceptance.share.privateHint": "Только создатель и участники рабочего пространства смогут просматривать это принятие и его раунды. Уже загруженные копии нельзя отозвать.",
"acceptance.share.publicHint": "Любой, у кого есть ссылка, сможет просматривать это принятие, все его раунды, доказательства и комментарии. Авторизованные посетители также смогут комментировать и добавлять аннотации. Проверьте содержимое перед тем, как сделать его общедоступным.",
"acceptance.share.saved": "Разрешения на доступ обновлены",
diff --git a/locales/tr-TR/verify.json b/locales/tr-TR/verify.json
index 2fc1c16d7c2..16a17a2fe33 100644
--- a/locales/tr-TR/verify.json
+++ b/locales/tr-TR/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Belirsiz",
"acceptance.roundStatus.verifying": "Devam ediyor",
"acceptance.share.copyFailed": "Bağlantı kopyalanamadı. Adres çubuğundan kopyalayın.",
- "acceptance.share.makePrivate": "Erişimi kısıtla",
- "acceptance.share.makePublic": "Bağlantı ile erişime izin ver",
"acceptance.share.privateHint": "Yalnızca oluşturucu ve çalışma alanı üyeleri bu kabulü ve turlarını okuyabilir. Zaten indirilen kopyalar geri çağrılamaz.",
"acceptance.share.publicHint": "Bağlantıya sahip olan herkes bu kabulü, tüm turlarını, kanıtları ve yorumları okuyabilir. Oturum açmış ziyaretçiler ayrıca yorum yapabilir ve not ekleyebilir. İçeriği herkese açık hale getirmeden önce gözden geçirin.",
"acceptance.share.saved": "Paylaşım izinleri güncellendi",
diff --git a/locales/vi-VN/verify.json b/locales/vi-VN/verify.json
index 64caf67a4d1..58d144f7df1 100644
--- a/locales/vi-VN/verify.json
+++ b/locales/vi-VN/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "Không chắc chắn",
"acceptance.roundStatus.verifying": "Đang tiến hành",
"acceptance.share.copyFailed": "Không thể sao chép liên kết. Hãy sao chép từ thanh địa chỉ.",
- "acceptance.share.makePrivate": "Hạn chế quyền truy cập",
- "acceptance.share.makePublic": "Cho phép truy cập bằng liên kết",
"acceptance.share.privateHint": "Chỉ người tạo và các thành viên trong không gian làm việc mới có thể đọc được sự chấp nhận này và các vòng của nó. Các bản sao đã tải xuống không thể được thu hồi.",
"acceptance.share.publicHint": "Bất kỳ ai có liên kết đều có thể đọc được sự chấp nhận này, tất cả các vòng, bằng chứng và nhận xét. Khách đã đăng nhập cũng có thể nhận xét và chú thích. Hãy xem xét nội dung trước khi công khai.",
"acceptance.share.saved": "Quyền chia sẻ đã được cập nhật",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 508755be3a1..f91d41c9a58 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -439,9 +439,12 @@
"acceptance.roundStatus.repairing": "修复中",
"acceptance.roundStatus.uncertain": "不确定",
"acceptance.roundStatus.verifying": "进行中",
+ "acceptance.share.access.owner": "仅自己",
+ "acceptance.share.access.public": "任何持有链接的人",
+ "acceptance.share.access.title": "谁可以查看",
+ "acceptance.share.access.workspace": "工作区成员",
"acceptance.share.copyFailed": "链接复制失败,请从地址栏复制。",
- "acceptance.share.makePrivate": "限制访问",
- "acceptance.share.makePublic": "允许通过链接访问",
+ "acceptance.share.ownerHint": "只有你可以阅读这条验收及其轮次。它会从队友的列表中消失,队友手里的链接也将无法打开。",
"acceptance.share.privateHint": "仅创建者和所属工作区成员可以阅读这条验收及其轮次。已下载的副本无法收回。",
"acceptance.share.publicHint": "任何持有链接的人都可以阅读这条验收、全部轮次、证据和评论。已登录的访客还可以评论和标注。请先检查内容是否适合公开。",
"acceptance.share.saved": "分享权限已更新",
diff --git a/locales/zh-TW/verify.json b/locales/zh-TW/verify.json
index 0c9bd723661..0fd6181b2de 100644
--- a/locales/zh-TW/verify.json
+++ b/locales/zh-TW/verify.json
@@ -440,8 +440,6 @@
"acceptance.roundStatus.uncertain": "不確定",
"acceptance.roundStatus.verifying": "進行中",
"acceptance.share.copyFailed": "無法複製連結。請從地址欄複製。",
- "acceptance.share.makePrivate": "限制存取",
- "acceptance.share.makePublic": "允許使用連結存取",
"acceptance.share.privateHint": "只有創建者和工作區成員可以閱讀此驗收及其回合。已下載的副本無法撤回。",
"acceptance.share.publicHint": "任何擁有連結的人都可以閱讀此驗收、所有回合、證據和評論。已登入的訪客也可以評論和註解。公開前請檢查內容。",
"acceptance.share.saved": "共享權限已更新",
diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.ts
index 15ef722d996..33f35fa9ce8 100644
--- a/packages/const/src/verify.ts
+++ b/packages/const/src/verify.ts
@@ -249,13 +249,24 @@ export const creatableAcceptanceSubjectTypes = [
*/
/**
* Who can see a verify artifact (a run's report page, an acceptance page)
- * beyond its creator. Personal-scope rows default to `public` (the page is
- * meant to be linked from PRs / reports); workspace-scope rows default to
- * `private` (org data stays member-gated until deliberately opened up).
+ * beyond its creator:
+ *
+ * - `public` — anyone holding the link.
+ * - `private` — the creator and members of the row's own workspace. In a
+ * workspace this is "shared with the team", the default there.
+ * - `owner` — the creator alone, even inside a workspace.
+ *
+ * Personal-scope rows default to `public` (the page is meant to be linked from
+ * PRs / reports); workspace-scope rows default to `private`, so org data reaches
+ * every member without leaking past the workspace.
*/
-export const verifyVisibilities = ['private', 'public'] as const;
+export const verifyVisibilities = ['private', 'public', 'owner'] as const;
export type VerifyVisibility = (typeof verifyVisibilities)[number];
+/** Whether a member of the row's workspace (not its creator) may read it. */
+export const isWorkspaceReadableVisibility = (visibility: VerifyVisibility) =>
+ visibility !== 'owner';
+
export const acceptanceVisibilities = verifyVisibilities;
export type AcceptanceVisibility = VerifyVisibility;
diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.ts
index b10e63147d8..2e969a3a78c 100644
--- a/packages/database/src/models/__tests__/acceptance.test.ts
+++ b/packages/database/src/models/__tests__/acceptance.test.ts
@@ -467,6 +467,108 @@ describe('AcceptanceModel', () => {
'by-me',
]);
});
+
+ it('lists teammates private workspace acceptances under all, but keeps writes creator-only', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'editor', userId: otherUserId, workspaceId },
+ ]);
+ // Workspace creation defaults to `private` — member-gated, not creator-only.
+ await new AcceptanceModel(serverDB, userId, workspaceId).create({
+ subjectId: 'by-me',
+ subjectType: 'standalone',
+ });
+ const teammates = await new AcceptanceModel(serverDB, otherUserId, workspaceId).create({
+ subjectId: 'by-teammate',
+ subjectType: 'standalone',
+ });
+ expect(teammates.visibility).toBe('private');
+
+ const model = new AcceptanceModel(serverDB, userId, workspaceId);
+ expect((await model.query({ scope: 'all' })).map((row) => row.subjectId).sort()).toEqual([
+ 'by-me',
+ 'by-teammate',
+ ]);
+ expect(
+ (await model.queryPage({ scope: 'all' })).items.map((row) => row.subjectId).sort(),
+ ).toEqual(['by-me', 'by-teammate']);
+ expect((await model.query({ scope: 'created' })).map((row) => row.subjectId)).toEqual([
+ 'by-me',
+ ]);
+ // The personal scope never sees workspace rows.
+ expect(await new AcceptanceModel(serverDB, userId).query({ scope: 'all' })).toEqual([]);
+ // Widening the list leaves the model's write scope alone (members write via canManageAcceptance).
+ await model.updateStatus(teammates.id, 'accepted');
+ expect(
+ (await new AcceptanceModel(serverDB, otherUserId, workspaceId).findById(teammates.id))
+ ?.status,
+ ).toBe('pending');
+ });
+
+ it('keeps an only-me workspace acceptance out of teammates lists, participated included', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'editor', userId: otherUserId, workspaceId },
+ ]);
+ const teammateModel = new AcceptanceModel(serverDB, otherUserId, workspaceId);
+ await teammateModel.create({ subjectId: 'team', subjectType: 'standalone' });
+ const hidden = await teammateModel.create({
+ subjectId: 'only-teammate',
+ subjectType: 'standalone',
+ visibility: 'owner',
+ });
+ await comment(hidden.id, userId);
+
+ const model = new AcceptanceModel(serverDB, userId, workspaceId);
+ expect((await model.query({ scope: 'all' })).map((row) => row.subjectId)).toEqual(['team']);
+ expect((await model.queryPage({ scope: 'all' })).items.map((row) => row.subjectId)).toEqual([
+ 'team',
+ ]);
+ expect(await model.query({ scope: 'participated' })).toEqual([]);
+ // Its creator still sees it everywhere.
+ expect(
+ (await teammateModel.query({ scope: 'all' })).map((row) => row.subjectId).sort(),
+ ).toEqual(['only-teammate', 'team']);
+ expect(
+ (await teammateModel.query({ scope: 'created' })).map((row) => row.subjectId).sort(),
+ ).toEqual(['only-teammate', 'team']);
+ });
+
+ it('keeps an only-me acceptance and its rounds within its creator ownership scope', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'editor', userId: otherUserId, workspaceId },
+ ]);
+ const model = new AcceptanceModel(serverDB, userId, workspaceId);
+ const acceptance = await model.create({ subjectId: 'flip', subjectType: 'standalone' });
+ const runs = new VerifyRunModel(serverDB, userId, workspaceId);
+ const run = await runs.create({ goal: 'g' });
+ await runs.attachToAcceptance(run.id, acceptance.id);
+
+ await model.update(acceptance.id, { visibility: 'owner' });
+ await runs.setVisibilityByAcceptance(acceptance.id, 'owner');
+
+ // The creator still reads and writes it, and still sees its rounds.
+ expect((await model.findById(acceptance.id))?.visibility).toBe('owner');
+ expect((await runs.listByAcceptance(acceptance.id)).map((row) => row.id)).toEqual([run.id]);
+ await model.update(acceptance.id, { visibility: 'private' });
+ expect((await model.findById(acceptance.id))?.visibility).toBe('private');
+
+ // A teammate's ownership scope never reaches an owner row.
+ await model.update(acceptance.id, { visibility: 'owner' });
+ expect(
+ await new AcceptanceModel(serverDB, otherUserId, workspaceId).findById(acceptance.id),
+ ).toBeUndefined();
+ });
});
it('updateStatus stamps completedAt only on user-terminal statuses', async () => {
diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.ts
index 05822cde7c8..ea87433c04e 100644
--- a/packages/database/src/models/acceptance.ts
+++ b/packages/database/src/models/acceptance.ts
@@ -6,7 +6,7 @@ import type {
AcceptanceSubjectType,
} from '@lobechat/types';
import type { SQL } from 'drizzle-orm';
-import { and, desc, eq, exists, inArray, isNull, lt, not, or, sql } from 'drizzle-orm';
+import { and, desc, eq, exists, inArray, isNull, lt, ne, not, or, sql } from 'drizzle-orm';
import { acceptanceComments } from '../schemas/acceptanceComment';
import { goalNodes } from '../schemas/goalGraph';
@@ -87,6 +87,25 @@ export class AcceptanceModel {
private ownership = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, acceptances);
+ /**
+ * What the list reads in the active scope. Wider than {@link ownership} in a
+ * workspace: a `private` workspace acceptance is member-gated, not
+ * creator-only — every member can open it (`resolveAcceptanceCommentAccess`),
+ * so the list must show it too. Only an `owner` row stays its creator's.
+ * Writes keep using `ownership`.
+ */
+ private listScope = (): SQL => {
+ const scope = buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },
+ );
+ if (!this.workspaceId) return scope;
+ return and(scope, or(eq(acceptances.userId, this.userId), this.workspaceReadable()))!;
+ };
+
+ /** Rows a member of their workspace may read; mirrors `isWorkspaceReadableVisibility`. */
+ private workspaceReadable = (): SQL => ne(acceptances.visibility, 'owner');
+
/**
* Acceptances the caller has spoken on — a remark or an approval, replies
* included; a bare emoji reaction is not taking part. Rows the caller can no
@@ -112,17 +131,20 @@ export class AcceptanceModel {
or(
eq(acceptances.userId, this.userId),
eq(acceptances.visibility, 'public'),
- exists(
- this.db
- .select({ one: sql`1` })
- .from(workspaceMembers)
- .where(
- and(
- eq(workspaceMembers.workspaceId, acceptances.workspaceId),
- eq(workspaceMembers.userId, this.userId),
- isNull(workspaceMembers.deletedAt),
+ and(
+ this.workspaceReadable(),
+ exists(
+ this.db
+ .select({ one: sql`1` })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, acceptances.workspaceId),
+ eq(workspaceMembers.userId, this.userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
),
- ),
+ ),
),
),
)!;
@@ -167,7 +189,7 @@ export class AcceptanceModel {
const conditions: SQL[] = [];
if (scope === 'participated') conditions.push(this.participation());
else {
- conditions.push(this.ownership());
+ conditions.push(this.listScope());
if (scope === 'created') conditions.push(eq(acceptances.userId, this.userId));
}
if (projectId === null) conditions.push(isNull(acceptances.projectId));
diff --git a/packages/database/src/utils/workspace.test.ts b/packages/database/src/utils/workspace.test.ts
index 117d80f3943..43c427de440 100644
--- a/packages/database/src/utils/workspace.test.ts
+++ b/packages/database/src/utils/workspace.test.ts
@@ -43,9 +43,9 @@ describe('workspace utils', () => {
// restricted to their creator. NULL is treated as public for backwards
// compatibility with rows that pre-date the `visibility` column.
expect(built.sql).toBe(
- '("agents"."workspace_id" = $1 and ("agents"."visibility" is null or "agents"."visibility" = $2 or ("agents"."visibility" = $3 and "agents"."user_id" = $4)))',
+ '("agents"."workspace_id" = $1 and ("agents"."visibility" is null or "agents"."visibility" = $2 or ("agents"."visibility" in ($3, $4) and "agents"."user_id" = $5)))',
);
- expect(built.params).toStrictEqual(['ws-1', 'public', 'private', 'user-1']);
+ expect(built.params).toStrictEqual(['ws-1', 'public', 'private', 'owner', 'user-1']);
});
it('omits visibility filter when the cols object has no visibility column', () => {
@@ -95,9 +95,9 @@ describe('workspace utils', () => {
const built = new PgDialect().sqlToQuery(condition);
expect(built.sql).toBe(
- '("agents"."workspace_id" = $1 and ("agents"."visibility" is null or "agents"."visibility" = $2 or ("agents"."visibility" = $3 and "agents"."user_id" = $4)))',
+ '("agents"."workspace_id" = $1 and ("agents"."visibility" is null or "agents"."visibility" = $2 or ("agents"."visibility" in ($3, $4) and "agents"."user_id" = $5)))',
);
- expect(built.params).toStrictEqual(['ws-1', 'public', 'private', 'user-1']);
+ expect(built.params).toStrictEqual(['ws-1', 'public', 'private', 'owner', 'user-1']);
});
it('leaves the standard filter in place when callerAgentVisibility is null (unresolved)', () => {
@@ -115,9 +115,9 @@ describe('workspace utils', () => {
const built = new PgDialect().sqlToQuery(condition);
expect(built.sql).toBe(
- '("agents"."workspace_id" = $1 and ("agents"."visibility" is null or "agents"."visibility" = $2 or ("agents"."visibility" = $3 and "agents"."user_id" = $4)))',
+ '("agents"."workspace_id" = $1 and ("agents"."visibility" is null or "agents"."visibility" = $2 or ("agents"."visibility" in ($3, $4) and "agents"."user_id" = $5)))',
);
- expect(built.params).toStrictEqual(['ws-1', 'public', 'private', 'user-1']);
+ expect(built.params).toStrictEqual(['ws-1', 'public', 'private', 'owner', 'user-1']);
});
it('ignores callerAgentVisibility in personal mode (no workspaceId)', () => {
diff --git a/packages/database/src/utils/workspace.ts b/packages/database/src/utils/workspace.ts
index 30e24e166ea..1c6e358f0e3 100644
--- a/packages/database/src/utils/workspace.ts
+++ b/packages/database/src/utils/workspace.ts
@@ -1,4 +1,4 @@
-import { and, eq, isNull, or, type SQL } from 'drizzle-orm';
+import { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm';
import type { AnyPgColumn } from 'drizzle-orm/pg-core';
import { notTrashed } from './softDelete';
@@ -166,11 +166,12 @@ function buildScopeWhere(
// Workspace + visibility-aware mode: every member sees public rows; private
// rows are scoped to their creator. NULL visibility is treated as public for
- // backwards compatibility with rows that pre-date the column.
+ // backwards compatibility with rows that pre-date the column. `owner` (an
+ // acceptance or verify run kept to its creator) is creator-scoped too.
const visibilityFilter = or(
isNull(cols.visibility),
eq(cols.visibility, 'public'),
- and(eq(cols.visibility, 'private'), eq(cols.userId, ctx.userId)),
+ and(inArray(cols.visibility, ['private', 'owner']), eq(cols.userId, ctx.userId)),
) as SQL;
return and(workspaceMatch, visibilityFilter) as SQL;
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 813dc442a3b..78b96d9856f 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -25,12 +25,16 @@ export default {
'acceptance.comments.evidenceNumber': 'Evidence {{index}}',
'acceptance.comments.evidenceModalTitle': 'Comment on evidence',
'acceptance.share.title': 'Share',
- 'acceptance.share.makePublic': 'Allow access with the link',
- 'acceptance.share.makePrivate': 'Restrict access',
+ 'acceptance.share.access.title': 'Who can see',
+ 'acceptance.share.access.owner': 'Only me',
+ 'acceptance.share.access.workspace': 'Workspace members',
+ 'acceptance.share.access.public': 'Anyone with the link',
'acceptance.share.publicHint':
'Anyone with the link will be able to read this acceptance, all its rounds, evidence and comments. Signed-in visitors can also comment and annotate. Review the content before making it public.',
'acceptance.share.privateHint':
'Only the creator and workspace members will be able to read this acceptance and its rounds. Copies already downloaded cannot be recalled.',
+ 'acceptance.share.ownerHint':
+ "Only you will be able to read this acceptance and its rounds. It leaves your teammates' lists, and links they hold stop opening.",
'acceptance.share.saved': 'Sharing permissions updated',
'acceptance.share.copyFailed': 'Could not copy the link. Copy it from the address bar.',
'acceptance.video.annotateHint':
diff --git a/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx b/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx
index 642f03e80af..5ba5bfc9c6b 100644
--- a/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx
+++ b/src/features/Acceptance/Viewer/AcceptanceOverview.test.tsx
@@ -41,10 +41,19 @@ vi.mock('./Header/AcceptanceStatusControl', () => ({ default: () => null }));
vi.mock('./Header/AcceptanceTabs', () => ({ default: () => null }));
vi.mock('./Review/AcceptanceDecision', () => ({ default: () => null }));
-const buildBundle = (overrides: { canReview: boolean; visibility: 'private' | 'public' }) => ({
- acceptance: { id: 'acc-1', visibility: overrides.visibility },
+const buildBundle = (overrides: {
+ canReview: boolean;
+ isOwner?: boolean;
+ visibility: 'owner' | 'private' | 'public';
+ workspaceId?: string;
+}) => ({
+ acceptance: {
+ id: 'acc-1',
+ visibility: overrides.visibility,
+ workspaceId: overrides.workspaceId ?? null,
+ },
canReview: overrides.canReview,
- isOwner: overrides.canReview,
+ isOwner: overrides.isOwner ?? overrides.canReview,
rounds: [],
subject: { id: 'subject-1', type: 'task' },
});
@@ -70,7 +79,7 @@ describe('AcceptanceOverview sharing', () => {
const share = screen.getByRole('button', { name: /acceptance\.share\.title/ });
fireEvent.click(share);
- expect(await screen.findByText('acceptance.share.makePublic')).toBeTruthy();
+ expect(await screen.findByText('acceptance.share.access.public')).toBeTruthy();
expect(screen.getByText('report.actions.copyLink')).toBeTruthy();
});
@@ -88,13 +97,41 @@ describe('AcceptanceOverview sharing', () => {
);
});
- it('offers to make a public acceptance private', async () => {
+ it('offers a personal acceptance only-me and link access', async () => {
bundle.current = buildBundle({ canReview: true, visibility: 'public' });
renderOverview();
fireEvent.click(screen.getByRole('button', { name: /acceptance\.share\.title/ }));
- expect(await screen.findByText('acceptance.share.makePrivate')).toBeTruthy();
+ expect(await screen.findByText('acceptance.share.access.owner')).toBeTruthy();
+ expect(screen.getByText('acceptance.share.access.public')).toBeTruthy();
+ expect(screen.queryByText('acceptance.share.access.workspace')).toBeNull();
+ });
+
+ it('lets the creator of a workspace acceptance keep it to themselves', async () => {
+ bundle.current = buildBundle({ canReview: true, visibility: 'private', workspaceId: 'ws-1' });
+ renderOverview();
+
+ fireEvent.click(screen.getByRole('button', { name: /acceptance\.share\.title/ }));
+
+ expect(await screen.findByText('acceptance.share.access.owner')).toBeTruthy();
+ expect(screen.getByText('acceptance.share.access.workspace')).toBeTruthy();
+ expect(screen.getByText('acceptance.share.access.public')).toBeTruthy();
+ });
+
+ it('does not let a teammate hide a workspace acceptance from the team', async () => {
+ bundle.current = buildBundle({
+ canReview: true,
+ isOwner: false,
+ visibility: 'private',
+ workspaceId: 'ws-1',
+ });
+ renderOverview();
+
+ fireEvent.click(screen.getByRole('button', { name: /acceptance\.share\.title/ }));
+
+ expect(await screen.findByText('acceptance.share.access.workspace')).toBeTruthy();
+ expect(screen.queryByText('acceptance.share.access.owner')).toBeNull();
});
it('shows no share control to a viewer who cannot manage the acceptance', () => {
diff --git a/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx b/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx
index 41ef1c11329..fe94da3d6ee 100644
--- a/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx
+++ b/src/features/Acceptance/Viewer/Header/AcceptanceShare.tsx
@@ -1,5 +1,7 @@
-import { Button, confirmModal, DropdownMenu, toast } from '@lobehub/ui';
-import { Share2 } from 'lucide-react';
+import type { AcceptanceVisibility } from '@lobechat/const/verify';
+import type { DropdownItem } from '@lobehub/ui';
+import { Button, confirmModal, DropdownMenu, Icon, toast } from '@lobehub/ui';
+import { Check, Share2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useAppOrigin } from '@/hooks/useAppOrigin';
@@ -11,27 +13,65 @@ import { useAcceptanceScope } from '../AcceptanceScope';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
import { canReviewAcceptance } from '../visibility';
+const checkIcon = (checked: boolean) => <Icon icon={Check} style={{ opacity: checked ? 1 : 0 }} />;
+
+const OWNER_ONLY = {
+ hintKey: 'acceptance.share.ownerHint',
+ labelKey: 'acceptance.share.access.owner',
+} as const;
+const WORKSPACE = {
+ hintKey: 'acceptance.share.privateHint',
+ labelKey: 'acceptance.share.access.workspace',
+} as const;
+const LINK = {
+ hintKey: 'acceptance.share.publicHint',
+ labelKey: 'acceptance.share.access.public',
+} as const;
+
+type ShareAccessOption = (typeof OWNER_ONLY | typeof WORKSPACE | typeof LINK) & {
+ visibility: AcceptanceVisibility;
+};
+
+/**
+ * The access levels offered for this acceptance, narrowest first. A workspace
+ * delivery is shared with the team by default (`private`); its creator may keep
+ * it to themselves (`owner`). A personal one has no team, so `private` already
+ * means "only me".
+ */
+const shareAccessOptions = ({
+ inWorkspace,
+ isOwner,
+}: {
+ inWorkspace: boolean;
+ isOwner: boolean;
+}): ShareAccessOption[] => [
+ ...(inWorkspace
+ ? [
+ ...(isOwner ? [{ ...OWNER_ONLY, visibility: 'owner' as const }] : []),
+ { ...WORKSPACE, visibility: 'private' as const },
+ ]
+ : [{ ...OWNER_ONLY, visibility: 'private' as const }]),
+ { ...LINK, visibility: 'public' as const },
+];
+
/** A write capability: read-only hosts never mount sharing controls. */
const AcceptanceShare = () => {
const { t } = useTranslation('verify');
const { acceptanceId } = useAcceptanceScope();
const { data, mutate } = useAcceptanceBundle(acceptanceId);
const appOrigin = useAppOrigin();
- if (!canReviewAcceptance(data)) return null;
+ if (!data || !canReviewAcceptance(data)) return null;
- const isPublic = data?.acceptance.visibility === 'public';
- const changeVisibility = () =>
+ const current = data.acceptance.visibility;
+ const changeVisibility = ({ hintKey, labelKey, visibility }: ShareAccessOption) =>
confirmModal({
cancelText: t('actions.cancel'),
- content: t(isPublic ? 'acceptance.share.privateHint' : 'acceptance.share.publicHint'),
- okText: t(isPublic ? 'acceptance.share.makePrivate' : 'acceptance.share.makePublic'),
- title: t(isPublic ? 'acceptance.share.makePrivate' : 'acceptance.share.makePublic'),
+ content: t(hintKey),
+ okText: t(labelKey),
+ title: t(labelKey),
onOk: async () => {
try {
- await verifyService.setAcceptanceVisibility(
- acceptanceId,
- isPublic ? 'private' : 'public',
- );
+ await verifyService.setAcceptanceVisibility(acceptanceId, visibility);
await mutate();
void globalMutate(isAcceptanceListKey);
toast.success(t('acceptance.share.saved'));
@@ -42,14 +82,28 @@ const AcceptanceShare = () => {
},
});
+ const accessGroup: DropdownItem = {
+ children: shareAccessOptions({
+ inWorkspace: Boolean(data.acceptance.workspaceId),
+ isOwner: data.isOwner,
+ }).map((option) => ({
+ icon: checkIcon(current === option.visibility),
+ key: `visibility-${option.visibility}`,
+ label: t(option.labelKey),
+ onClick: () => {
+ if (current !== option.visibility) changeVisibility(option);
+ },
+ })),
+ key: 'visibility',
+ label: t('acceptance.share.access.title'),
+ type: 'group',
+ };
+
return (
<DropdownMenu
items={[
- {
- key: 'visibility',
- label: t(isPublic ? 'acceptance.share.makePrivate' : 'acceptance.share.makePublic'),
- onClick: changeVisibility,
- },
+ accessGroup,
+ { type: 'divider' },
{
key: 'copy',
label: t('report.actions.copyLink'),
diff --git a/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts b/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts
index c620497822e..09fd2621e48 100644
--- a/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts
+++ b/src/features/Acceptance/Workspace/acceptanceListFilter.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
acceptanceListEmptyVariant,
acceptanceProjectScopeKey,
+ DEFAULT_ACCEPTANCE_LIST_FACETS,
effectiveAcceptanceListFacets,
isAcceptanceListFacetsNarrowed,
normalizeAcceptanceListFacets,
@@ -56,12 +57,12 @@ describe('normalizeAcceptanceListFacets', () => {
expect(normalizeAcceptanceListFacets(null)).toEqual({
projectId: undefined,
projectScope: 'personal',
- scope: 'all',
+ scope: 'created',
source: 'all',
});
expect(
normalizeAcceptanceListFacets({ projectId: 3, scope: 'mine', source: 'document' }),
- ).toEqual({ projectId: undefined, projectScope: 'personal', scope: 'all', source: 'all' });
+ ).toEqual({ projectId: undefined, projectScope: 'personal', scope: 'created', source: 'all' });
});
it('drops a project choice made in another workspace but keeps scope and source', () => {
@@ -85,6 +86,25 @@ describe('normalizeAcceptanceListFacets', () => {
});
});
+describe('default facets', () => {
+ it('opens on the caller own acceptances', () => {
+ expect(DEFAULT_ACCEPTANCE_LIST_FACETS.scope).toBe('created');
+ expect(normalizeAcceptanceListFacets(undefined).scope).toBe('created');
+ });
+
+ it('keeps a stored all scope', () => {
+ expect(normalizeAcceptanceListFacets({ scope: 'all', source: 'all' }).scope).toBe('all');
+ });
+
+ it('resets "show all" past the default to the whole scope', () => {
+ expect(resetAcceptanceListFacets(DEFAULT_ACCEPTANCE_LIST_FACETS)).toEqual({
+ scope: 'all',
+ source: 'all',
+ });
+ expect(isAcceptanceListFacetsNarrowed(DEFAULT_ACCEPTANCE_LIST_FACETS)).toBe(true);
+ });
+});
+
describe('isAcceptanceListFacetsNarrowed', () => {
it('treats any non-default facet as a narrowing', () => {
expect(isAcceptanceListFacetsNarrowed({ scope: 'all', source: 'all' })).toBe(false);
diff --git a/src/features/Acceptance/Workspace/acceptanceListFilter.ts b/src/features/Acceptance/Workspace/acceptanceListFilter.ts
index 6e5d9a74165..652a4df6da8 100644
--- a/src/features/Acceptance/Workspace/acceptanceListFilter.ts
+++ b/src/features/Acceptance/Workspace/acceptanceListFilter.ts
@@ -29,7 +29,14 @@ export interface AcceptanceListFacets {
/** The key a project choice is scoped to: the active workspace, or `personal`. */
export const acceptanceProjectScopeKey = (workspaceId?: string | null) => workspaceId ?? 'personal';
-export const DEFAULT_ACCEPTANCE_LIST_FACETS: AcceptanceListFacets = { scope: 'all', source: 'all' };
+/** A list opens on the caller's own deliveries; `all` widens to the whole scope. */
+export const DEFAULT_ACCEPTANCE_LIST_FACETS: AcceptanceListFacets = {
+ scope: 'created',
+ source: 'all',
+};
+
+/** What "show all" resets to — every facet open, unlike the default. */
+const SHOW_ALL_ACCEPTANCE_LIST_FACETS: AcceptanceListFacets = { scope: 'all', source: 'all' };
/**
* Persisted facets are untrusted — a stale or hand-edited value falls back per
@@ -40,7 +47,9 @@ export const normalizeAcceptanceListFacets = (
projectScope: string = acceptanceProjectScopeKey(),
): AcceptanceListFacets => {
const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
- const scope = ACCEPTANCE_LIST_SCOPES.find((item) => item === raw.scope) ?? 'all';
+ const scope =
+ ACCEPTANCE_LIST_SCOPES.find((item) => item === raw.scope) ??
+ DEFAULT_ACCEPTANCE_LIST_FACETS.scope;
const source = ACCEPTANCE_LIST_SOURCES.find((item) => item === raw.source) ?? 'all';
const sameScope = (raw.projectScope ?? acceptanceProjectScopeKey()) === projectScope;
const projectId = !sameScope
@@ -73,11 +82,11 @@ export const resetAcceptanceListFacets = (
): AcceptanceListFacets =>
hostProjectId
? {
- ...DEFAULT_ACCEPTANCE_LIST_FACETS,
+ ...SHOW_ALL_ACCEPTANCE_LIST_FACETS,
projectId: facets.projectId,
projectScope: facets.projectScope,
}
- : DEFAULT_ACCEPTANCE_LIST_FACETS;
+ : SHOW_ALL_ACCEPTANCE_LIST_FACETS;
/** Whether the facets narrow the list beyond what its host already fixes. */
export const isAcceptanceListFacetsNarrowed = (
diff --git a/src/services/verify.ts b/src/services/verify.ts
index d5ca82c17d7..68cb93e9a26 100644
--- a/src/services/verify.ts
+++ b/src/services/verify.ts
@@ -1,4 +1,5 @@
import { DEFAULT_VERIFY_PLAN_PROVIDER } from '@lobechat/business-const';
+import type { AcceptanceVisibility } from '@lobechat/const/verify';
import type {
AcceptanceChecklistItem,
AcceptanceCheckReviewAction,
@@ -187,7 +188,7 @@ export class VerifyService {
getAcceptanceBundle = (id: string): Promise<AcceptanceBundle> =>
lambdaClient.acceptance.getBundle.query({ id });
- setAcceptanceVisibility = (id: string, visibility: 'private' | 'public') =>
+ setAcceptanceVisibility = (id: string, visibility: AcceptanceVisibility) =>
lambdaClient.acceptance.setVisibility.mutate({ id, visibility });
/** The acceptance aggregate for a subject (topic/task/document), or null. */