🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: support workspace document comments (#18750)
Rdmclin24fa47ad10635
diff --git a/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.tsnew file mode 100644index 00000000000..661f6820c3f--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/documentComment.integration.test.ts@@ -0,0 +1,390 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import {+ documentCommentMentions,+ documentComments,+ documents,+ workspaceMembers,+ workspaces,+} from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { RbacModel } from '@/database/models/rbac';++import { documentCommentRouter } from '../../documentComment';+import { cleanupTestUser, createTestUser } from './setup';++let testDB: LobeChatDatabase;+const notifyDocumentCommentActivity = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => testDB) }));+vi.mock('@/business/server/document-comment/notifyActivity', () => ({+ notifyDocumentCommentActivity,+}));+const publishResourceEvent = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent }));+const afterResponseTasks = vi.hoisted(() => [] as Promise<unknown>[]);+vi.mock('@/server/utils/scheduleAfterResponse', () => ({+ after: (work: () => unknown) => void afterResponseTasks.push(Promise.resolve().then(work)),+}));++const flushAfterResponse = async () => {+ while (afterResponseTasks.length > 0) await Promise.all(afterResponseTasks.splice(0));+};++const context = (userId: string, workspaceId?: string) => ({+ jwtPayload: { userId },+ userId,+ workspaceId,+});++const mentionEditorData = (...userIds: string[]) => ({+ root: {+ children: userIds.map((id) => ({+ children: [],+ metadata: { id, type: 'member' },+ type: 'mention',+ })),+ type: 'root',+ },+});++describe('documentCommentRouter integration', () => {+ const getWorkspaceUsersPermissions = vi.spyOn(RbacModel, 'getWorkspaceUsersPermissions');+ let adminId: string;+ let db: LobeChatDatabase;+ let documentId: string;+ let memberId: string;+ let ownerId: string;+ let viewerId: string;+ let workspaceId: string;++ beforeEach(async () => {+ getWorkspaceUsersPermissions.mockClear();+ notifyDocumentCommentActivity.mockReset();+ notifyDocumentCommentActivity.mockResolvedValue(undefined);+ publishResourceEvent.mockReset();+ publishResourceEvent.mockResolvedValue(undefined);+ db = await getTestDB();+ testDB = db;+ [ownerId, adminId, memberId, viewerId] = await Promise.all([+ createTestUser(db),+ createTestUser(db),+ createTestUser(db),+ createTestUser(db),+ ]);+ const [workspace] = await db+ .insert(workspaces)+ .values({ name: 'Document comments', primaryOwnerId: ownerId, slug: `dc-${ownerId}` })+ .returning();+ workspaceId = workspace.id;+ await db.insert(workspaceMembers).values([+ { role: 'owner', userId: ownerId, workspaceId },+ { role: 'admin', userId: adminId, workspaceId },+ { role: 'member', userId: memberId, workspaceId },+ { role: 'viewer', userId: viewerId, workspaceId },+ ]);+ const [document] = await db+ .insert(documents)+ .values({+ fileType: 'custom',+ source: `document-${ownerId}`,+ sourceType: 'api',+ title: 'Commentable document',+ totalCharCount: 0,+ totalLineCount: 0,+ userId: ownerId,+ workspaceId,+ })+ .returning();+ documentId = document.id;+ });++ afterEach(async () => {+ await flushAfterResponse();+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await Promise.all([ownerId, adminId, memberId, viewerId].map((id) => cleanupTestUser(db, id)));+ });++ afterAll(() => getWorkspaceUsersPermissions.mockRestore());++ it('allows members to discuss, viewers to read, and admins to delete any comment', async () => {+ const admin = documentCommentRouter.createCaller(context(adminId, workspaceId));+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));+ const viewer = documentCommentRouter.createCaller(context(viewerId, workspaceId));+ const created = await member.create({+ clientId: 'member-comment',+ content: 'hello',+ documentId,+ });+ await flushAfterResponse();++ expect(notifyDocumentCommentActivity).toHaveBeenCalledWith({+ actorUserId: memberId,+ commentId: created.comment.id,+ documentId,+ kind: 'commented',+ recipientUserId: ownerId,+ rootCommentId: created.comment.id,+ workspaceId,+ });++ expect(created.comment).toMatchObject({+ author: { id: memberId, status: 'active' },+ canDelete: true,+ canEdit: true,+ });+ await expect(+ viewer.create({ clientId: 'viewer-comment', content: 'no', documentId }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect((await viewer.listThreads({ documentId })).items[0].root).toMatchObject({+ canDelete: false,+ canEdit: false,+ content: 'hello',+ });+ expect((await admin.delete({ id: created.comment.id })).mode).toBe('hard');+ });++ it('preserves a root tombstone while replies remain and keeps counts consistent', async () => {+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = documentCommentRouter.createCaller(context(ownerId, workspaceId));+ const root = await member.create({ clientId: 'root', content: 'root', documentId });+ const reply = await owner.create({+ clientId: 'reply',+ content: 'reply',+ documentId,+ parentCommentId: root.comment.id,+ });+ const nestedReply = await member.create({+ clientId: 'nested-reply',+ content: 'nested reply',+ documentId,+ parentCommentId: reply.comment.id,+ });++ expect(nestedReply.comment).toMatchObject({+ parentCommentId: root.comment.id,+ replyTo: { author: { id: ownerId }, id: reply.comment.id },+ replyToCommentId: reply.comment.id,+ });+ expect((await owner.listReplies({ rootCommentId: root.comment.id })).items).toMatchObject([+ { id: reply.comment.id, replyTo: null },+ { id: nestedReply.comment.id, replyTo: { author: { id: ownerId } } },+ ]);++ expect((await member.delete({ id: root.comment.id })).mode).toBe('soft');+ expect(await owner.summary({ documentId })).toEqual({ total: 2 });+ expect((await owner.listThreads({ documentId })).items[0]).toMatchObject({+ replyCount: 2,+ root: { content: '', deletedAt: expect.any(Date) },+ });+ });++ it('does not expose a private document to another workspace member', async () => {+ await db.update(documents).set({ visibility: 'private' }).where(eq(documents.id, documentId));+ const owner = documentCommentRouter.createCaller(context(ownerId, workspaceId));+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));++ await expect(owner.summary({ documentId })).resolves.toEqual({ total: 0 });+ await expect(member.summary({ documentId })).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(await db.select().from(documentComments)).toEqual([]);+ });++ it('accepts attachment-only comments and rejects incomplete uploads', async () => {+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));+ const completedFile = {+ root: {+ children: [+ {+ fileUrl: 'https://files.example.com/report.pdf',+ name: 'report.pdf',+ status: 'uploaded',+ type: 'file',+ },+ ],+ type: 'root',+ },+ };+ const created = await member.create({+ clientId: 'attachment-only',+ content: '',+ documentId,+ editorData: completedFile,+ });+ expect(created.comment.content).toBe('');++ const textComment = await member.create({+ clientId: 'replace-with-attachment',+ content: 'replace me',+ documentId,+ });+ const updated = await member.update({+ content: '',+ editorData: completedFile,+ id: textComment.comment.id,+ });+ expect(updated.content).toBe('');++ await expect(+ member.create({+ clientId: 'pending-attachment',+ content: 'do not publish yet',+ documentId,+ editorData: {+ root: {+ children: [{ name: 'large.zip', status: 'pending', type: 'file' }],+ type: 'root',+ },+ },+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ await expect(+ member.create({ clientId: 'empty-comment', content: '', documentId }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('publishes one realtime invalidation after each committed mutation', async () => {+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));+ const created = await member.create({ clientId: 'event-root', content: 'root', documentId });+ await flushAfterResponse();++ expect(publishResourceEvent).toHaveBeenCalledOnce();+ expect(publishResourceEvent).toHaveBeenLastCalledWith(+ { id: documentId, type: 'document' },+ {+ actorId: memberId,+ data: { rootCommentId: created.comment.id },+ type: 'document.commentsChanged',+ },+ );++ await member.create({ clientId: 'event-root', content: 'duplicate', documentId });+ await flushAfterResponse();+ expect(publishResourceEvent).toHaveBeenCalledOnce();++ await member.update({ content: 'updated', id: created.comment.id });+ await flushAfterResponse();+ expect(publishResourceEvent).toHaveBeenCalledTimes(2);++ await member.delete({ id: created.comment.id });+ await flushAfterResponse();+ expect(publishResourceEvent).toHaveBeenCalledTimes(3);+ });++ it('notifies the direct reply target once and skips self or stale-access recipients', async () => {+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));+ const owner = documentCommentRouter.createCaller(context(ownerId, workspaceId));++ const root = await owner.create({ clientId: 'owner-root', content: 'root', documentId });+ await flushAfterResponse();+ expect(notifyDocumentCommentActivity).not.toHaveBeenCalled();++ const reply = await member.create({+ clientId: 'member-reply',+ content: 'reply',+ documentId,+ parentCommentId: root.comment.id,+ });+ await flushAfterResponse();+ expect(notifyDocumentCommentActivity).toHaveBeenLastCalledWith({+ actorUserId: memberId,+ commentId: reply.comment.id,+ documentId,+ kind: 'replied',+ recipientUserId: ownerId,+ rootCommentId: root.comment.id,+ workspaceId,+ });++ await member.create({+ clientId: 'member-reply',+ content: 'duplicate retry',+ documentId,+ parentCommentId: root.comment.id,+ });+ await flushAfterResponse();+ expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(1);++ await db.update(documents).set({ visibility: 'private' }).where(eq(documents.id, documentId));+ const privateReply = await owner.create({+ clientId: 'private-reply',+ content: 'no leaked notification',+ documentId,+ parentCommentId: reply.comment.id,+ });+ await flushAfterResponse();+ expect(privateReply.comment.replyTo?.author.id).toBe(memberId);+ expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(1);+ });++ it('notifies valid mentions once, prefers mention copy, and only sends newly added mentions', async () => {+ const member = documentCommentRouter.createCaller(context(memberId, workspaceId));+ const created = await member.create({+ clientId: 'mentions',+ content: '@owner @viewer @self @outsider',+ documentId,+ editorData: mentionEditorData(ownerId, viewerId, memberId, 'outside-workspace'),+ });+ await flushAfterResponse();++ const recipientAccessLookups = getWorkspaceUsersPermissions.mock.calls.filter(+ ([{ userIds }]) => userIds.includes(ownerId) || userIds.includes(viewerId),+ );+ expect(recipientAccessLookups).toHaveLength(1);+ expect(recipientAccessLookups[0][0].userIds).toEqual(+ expect.arrayContaining([ownerId, viewerId]),+ );+ expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(2);+ expect(notifyDocumentCommentActivity).toHaveBeenCalledWith(+ expect.objectContaining({+ commentId: created.comment.id,+ kind: 'mentioned',+ recipientUserId: ownerId,+ }),+ );+ expect(notifyDocumentCommentActivity).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'mentioned', recipientUserId: viewerId }),+ );+ expect(+ (+ await db+ .select({ mentionedUserId: documentCommentMentions.mentionedUserId })+ .from(documentCommentMentions)+ .where(eq(documentCommentMentions.commentId, created.comment.id))+ )+ .map(({ mentionedUserId }) => mentionedUserId)+ .sort(),+ ).toEqual([ownerId, viewerId].sort());++ notifyDocumentCommentActivity.mockClear();+ await member.update({+ content: '@owner @viewer @admin',+ editorData: mentionEditorData(ownerId, viewerId, adminId),+ id: created.comment.id,+ });+ await flushAfterResponse();+ expect(notifyDocumentCommentActivity).toHaveBeenCalledTimes(1);+ expect(notifyDocumentCommentActivity).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'mentioned', recipientUserId: adminId }),+ );+ expect(+ (+ await db+ .select({ mentionedUserId: documentCommentMentions.mentionedUserId })+ .from(documentCommentMentions)+ .where(eq(documentCommentMentions.commentId, created.comment.id))+ )+ .map(({ mentionedUserId }) => mentionedUserId)+ .sort(),+ ).toEqual([adminId, ownerId, viewerId].sort());++ notifyDocumentCommentActivity.mockClear();+ await member.update({+ editorData: mentionEditorData(ownerId, viewerId, adminId),+ id: created.comment.id,+ });+ await flushAfterResponse();+ expect(notifyDocumentCommentActivity).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/documentComment.ts b/apps/server/src/routers/lambda/documentComment.tsnew file mode 100644index 00000000000..0fd3dbf269b--- /dev/null+++ b/apps/server/src/routers/lambda/documentComment.ts@@ -0,0 +1,577 @@+import type { DocumentCommentItem as DocumentCommentDTO } from '@lobechat/types';+import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';+import { TRPCError } from '@trpc/server';+import { and, eq, inArray, isNull } from 'drizzle-orm';+import { z } from 'zod';++import type { NotifyDocumentCommentActivityParams } from '@/business/server/document-comment/notifyActivity';+import { notifyDocumentCommentActivity } from '@/business/server/document-comment/notifyActivity';+import { wsProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import {+ DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND,+ DOCUMENT_COMMENT_PARENT_NOT_FOUND,+ DocumentCommentModel,+} from '@/database/models/documentComment';+import { RbacModel } from '@/database/models/rbac';+import { documentComments, users, workspaceMembers } from '@/database/schemas';+import type { DocumentCommentItem } from '@/database/schemas/documentComment';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { publishResourceEvent } from '@/server/services/resourceEvents';+import {+ assertCanPerformResourceAction,+ canPerformResourceAction,+ getResourceMeta,+} from '@/server/services/resourcePermission';+import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';+import { after } from '@/server/utils/scheduleAfterResponse';++const MAX_EDITOR_DATA_BYTES = 128 * 1024;+const idSchema = z.string().trim().min(1).max(255);+const contentSchema = z.string().trim().max(10_000);+const editorDataSchema = z+ .json()+ .refine((value) => Buffer.byteLength(JSON.stringify(value), 'utf8') <= MAX_EDITOR_DATA_BYTES, {+ message: 'editorData must not exceed 128 KiB',+ });+const pageSchema = z.object({+ cursor: z.string().min(1).optional(),+ limit: z.number().int().min(1).max(50).optional(),+});++const getAttachmentState = (editorData: unknown) => {+ const root = toRecord(editorData)?.root;+ const pending: unknown[] = root === undefined ? [] : [root];+ let hasCompletedAttachments = false;+ let hasIncompleteAttachments = false;++ while (pending.length > 0) {+ const node = toRecord(pending.pop());+ if (!node) continue;++ const isFile = node.type === 'file';+ const isImage = node.type === 'image' || node.type === 'block-image';+ if (isFile || isImage) {+ const url = isFile ? node.fileUrl : node.src;+ if (node.status === 'uploaded' && typeof url === 'string' && url.length > 0) {+ hasCompletedAttachments = true;+ } else {+ hasIncompleteAttachments = true;+ }+ }++ if (Array.isArray(node.children)) pending.push(...node.children);+ }++ return { hasCompletedAttachments, hasIncompleteAttachments };+};++const validateCommentBody = (+ value: { content?: string; editorData?: unknown },+ ctx: z.RefinementCtx,+) => {+ const attachmentState = getAttachmentState(value.editorData);+ if (attachmentState.hasIncompleteAttachments) {+ ctx.addIssue({+ code: 'custom',+ message: 'Attachments must finish uploading successfully',+ path: ['editorData'],+ });+ }+ if (value.content !== undefined && !value.content && !attachmentState.hasCompletedAttachments) {+ ctx.addIssue({+ code: 'custom',+ message: 'Comment content or a completed attachment is required',+ path: ['content'],+ });+ }+};++const extractMentionedUserIds = (editorData: unknown): string[] => {+ const root = toRecord(editorData)?.root;+ const pending: unknown[] = root === undefined ? [] : [root];+ const userIds = new Set<string>();++ while (pending.length > 0) {+ const node = toRecord(pending.pop());+ if (!node) continue;++ const metadata = toRecord(node.metadata);+ if (node.type === 'mention' && metadata?.type === 'member') {+ const userId = pickNonEmptyString(metadata.id);+ if (userId) userIds.add(userId);+ }++ if (Array.isArray(node.children)) pending.push(...node.children);+ }++ return [...userIds];+};++const documentCommentProcedure = wsProcedure.use(serverDatabase).use(async ({ ctx, next }) => {+ let permissionCodes: Promise<string[]> | undefined;+ const getPermissionCodes = () => {+ permissionCodes ??= Promise.all([+ ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ eq(workspaceMembers.userId, ctx.userId),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ .limit(1),+ new RbacModel(ctx.serverDB, ctx.userId).getUserPermissions({ workspaceId: ctx.workspaceId }),+ ]).then(([membership, codes]) => (membership[0] ? codes : []));+ return permissionCodes;+ };++ return next({+ ctx: {+ documentCommentModel: new DocumentCommentModel(ctx.serverDB, ctx.userId, ctx.workspaceId),+ getDocumentCommentPermissionCodes: getPermissionCodes,+ },+ });+});++interface PermissionContext {+ getDocumentCommentPermissionCodes: () => Promise<string[]>;+ serverDB: Parameters<typeof getWorkspaceScopedPermissionMatches>[0]['db'];+ userId: string;+ workspaceId: string;+}++type DocumentCommentAction =+ | 'DOCUMENT_COMMENT_CREATE'+ | 'DOCUMENT_COMMENT_DELETE'+ | 'DOCUMENT_COMMENT_READ'+ | 'DOCUMENT_COMMENT_UPDATE';++const assertPermission = async (ctx: PermissionContext, action: DocumentCommentAction) => {+ const grantedPermissions = await ctx.getDocumentCommentPermissionCodes();+ const matches = await getWorkspaceScopedPermissionMatches({+ action,+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ if (!matches.hasAllScope && !matches.hasOwnerScope) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Insufficient document comment permission',+ });+ }+ return { grantedPermissions, matches };+};++const assertDocumentView = async (+ ctx: PermissionContext,+ documentId: string,+ grantedPermissions: readonly string[],+) =>+ assertCanPerformResourceAction({+ action: 'view',+ db: ctx.serverDB,+ grantedPermissions,+ resourceId: documentId,+ resourceType: 'document',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });++const validateMentionedUserIds = async (+ ctx: PermissionContext,+ editorData: unknown,+): Promise<string[]> => {+ const candidateIds = extractMentionedUserIds(editorData).filter((id) => id !== ctx.userId);+ if (candidateIds.length === 0) return [];++ const activeMemberships = await ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ inArray(workspaceMembers.userId, candidateIds),+ isNull(workspaceMembers.deletedAt),+ ),+ );+ const activeUserIds = new Set(activeMemberships.map(({ userId }) => userId));+ return candidateIds.filter((id) => activeUserIds.has(id));+};++const notifyActivitiesBestEffort = (+ ctx: PermissionContext,+ activities: NotifyDocumentCommentActivityParams[],+) => {+ const pending = activities.filter(({ recipientUserId }) => recipientUserId !== ctx.userId);+ if (pending.length === 0) return;++ after(async () => {+ try {+ const documentId = pending[0].documentId;+ const recipientUserIds = [...new Set(pending.map(({ recipientUserId }) => recipientUserId))];+ const [meta, permissionsByUserId] = await Promise.all([+ getResourceMeta(ctx.serverDB, 'document', documentId),+ RbacModel.getWorkspaceUsersPermissions({+ db: ctx.serverDB,+ requireMembership: true,+ userIds: recipientUserIds,+ workspaceId: ctx.workspaceId,+ }),+ ]);+ if (!meta) return;++ const accessibleUserIds = new Set(+ (+ await Promise.all(+ recipientUserIds.map(async (userId) => {+ const grantedPermissions = permissionsByUserId.get(userId);+ if (!grantedPermissions) return null;++ const canView = await canPerformResourceAction({+ action: 'view',+ db: ctx.serverDB,+ effectiveAccessLevel: 'view',+ grantedPermissions,+ meta,+ resourceId: documentId,+ resourceType: 'document',+ userId,+ workspaceId: ctx.workspaceId,+ });+ return canView ? userId : null;+ }),+ )+ ).filter((userId): userId is string => Boolean(userId)),+ );++ await Promise.all(+ pending+ .filter(({ recipientUserId }) => accessibleUserIds.has(recipientUserId))+ .map((params) => notifyDocumentCommentActivity(params)),+ );+ } catch (error) {+ console.error('[document-comment] Failed to send activity notification', error);+ }+ });+};++const publishCommentsChanged = (+ ctx: Pick<PermissionContext, 'userId'>,+ documentId: string,+ rootCommentId: string,+) => {+ after(() =>+ publishResourceEvent(+ { id: documentId, type: 'document' },+ {+ actorId: ctx.userId,+ data: { rootCommentId },+ type: 'document.commentsChanged',+ },+ ),+ );+};++const toNotFound = (error: unknown): never => {+ if (+ error instanceof Error &&+ [DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND, DOCUMENT_COMMENT_PARENT_NOT_FOUND].includes(error.message)+ ) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Document comment resource not found' });+ }+ throw error;+};++const getMutationPermissions = async (ctx: PermissionContext) => {+ const grantedPermissions = await ctx.getDocumentCommentPermissionCodes();+ const [update, remove] = await Promise.all([+ getWorkspaceScopedPermissionMatches({+ action: 'DOCUMENT_COMMENT_UPDATE',+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ getWorkspaceScopedPermissionMatches({+ action: 'DOCUMENT_COMMENT_DELETE',+ db: ctx.serverDB,+ grantedPermissions,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ }),+ ]);+ return { delete: remove, update };+};++const enrich = async (+ ctx: PermissionContext,+ items: DocumentCommentItem[],+): Promise<DocumentCommentDTO[]> => {+ const replyToIds = [+ ...new Set(+ items.flatMap(({ replyToCommentId }) => (replyToCommentId ? [replyToCommentId] : [])),+ ),+ ];+ const [replyTargets, permissions] = await Promise.all([+ replyToIds.length+ ? ctx.serverDB+ .select({ authorUserId: documentComments.authorUserId, id: documentComments.id })+ .from(documentComments)+ .where(inArray(documentComments.id, replyToIds))+ : [],+ getMutationPermissions(ctx),+ ]);+ const authorIds = [+ ...new Set(+ [...items, ...replyTargets].flatMap(({ authorUserId }) =>+ authorUserId ? [authorUserId] : [],+ ),+ ),+ ];+ const [profiles, memberships] = await Promise.all([+ authorIds.length+ ? ctx.serverDB+ .select({+ avatar: users.avatar,+ fullName: users.fullName,+ id: users.id,+ username: users.username,+ })+ .from(users)+ .where(inArray(users.id, authorIds))+ : [],+ authorIds.length+ ? ctx.serverDB+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, ctx.workspaceId),+ inArray(workspaceMembers.userId, authorIds),+ isNull(workspaceMembers.deletedAt),+ ),+ )+ : [],+ ]);+ const profileById = new Map(profiles.map((profile) => [profile.id, profile]));+ const activeIds = new Set(memberships.map(({ userId }) => userId));+ const replyTargetById = new Map(replyTargets.map((target) => [target.id, target]));+ const getAuthor = (authorUserId: string | null) => {+ const profile = authorUserId ? profileById.get(authorUserId) : undefined;+ return profile+ ? {+ ...profile,+ status: activeIds.has(profile.id) ? ('active' as const) : ('former' as const),+ }+ : {+ avatar: null,+ fullName: null,+ id: null,+ status: 'deactivated' as const,+ username: null,+ };+ };++ return items.map((item) => {+ const own = item.authorUserId === ctx.userId;+ const replyTarget = item.replyToCommentId+ ? replyTargetById.get(item.replyToCommentId)+ : undefined;+ return {+ ...item,+ author: getAuthor(item.authorUserId),+ canDelete:+ !item.deletedAt &&+ (permissions.delete.hasAllScope || (permissions.delete.hasOwnerScope && own)),+ canEdit:+ !item.deletedAt &&+ own &&+ (permissions.update.hasAllScope || permissions.update.hasOwnerScope),+ replyTo: replyTarget+ ? { author: getAuthor(replyTarget.authorUserId), id: replyTarget.id }+ : null,+ } as DocumentCommentDTO;+ });+};++export const documentCommentRouter = router({+ create: documentCommentProcedure+ .input(+ z+ .object({+ clientId: idSchema,+ content: contentSchema,+ documentId: idSchema,+ editorData: editorDataSchema.optional(),+ parentCommentId: idSchema.optional(),+ })+ .superRefine(validateCommentBody),+ )+ .mutation(async ({ ctx, input }) => {+ const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_CREATE');+ await assertDocumentView(ctx, input.documentId, grantedPermissions);+ try {+ const mentionedUserIds = await validateMentionedUserIds(ctx, input.editorData);+ const result = await ctx.documentCommentModel.create({ ...input, mentionedUserIds });+ if (!result.isDuplicate) {+ const recipientsByUserId = new Map<string, NotifyDocumentCommentActivityParams['kind']>();+ const recipientUserId = input.parentCommentId+ ? result.parentAuthorUserId+ : result.documentAuthorUserId;+ if (recipientUserId && recipientUserId !== ctx.userId) {+ recipientsByUserId.set(+ recipientUserId,+ input.parentCommentId ? 'replied' : 'commented',+ );+ }+ for (const userId of result.addedMentionUserIds) {+ recipientsByUserId.set(userId, 'mentioned');+ }++ notifyActivitiesBestEffort(+ ctx,+ [...recipientsByUserId].map(([recipientUserId, kind]) => ({+ actorUserId: ctx.userId,+ commentId: result.comment.id,+ documentId: result.comment.documentId,+ kind,+ recipientUserId,+ rootCommentId: result.comment.parentCommentId ?? result.comment.id,+ workspaceId: ctx.workspaceId,+ })),+ );+ publishCommentsChanged(+ ctx,+ result.comment.documentId,+ result.comment.parentCommentId ?? result.comment.id,+ );+ }+ const [comment] = await enrich(ctx, [result.comment]);+ return { comment, isDuplicate: result.isDuplicate };+ } catch (error) {+ return toNotFound(error);+ }+ }),++ delete: documentCommentProcedure+ .input(z.object({ id: idSchema }))+ .mutation(async ({ ctx, input }) => {+ const current = await ctx.documentCommentModel.findById(input.id);+ if (!current) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Document comment not found' });+ }+ const { grantedPermissions, matches } = await assertPermission(+ ctx,+ 'DOCUMENT_COMMENT_DELETE',+ );+ await assertDocumentView(ctx, current.documentId, grantedPermissions);+ const mode = await ctx.documentCommentModel.delete(input.id, {+ overrideAuthorScope: matches.hasAllScope,+ });+ if (!mode) throw new TRPCError({ code: 'FORBIDDEN', message: 'Cannot delete comment' });+ publishCommentsChanged(ctx, current.documentId, current.parentCommentId ?? current.id);+ return { mode };+ }),++ get: documentCommentProcedure.input(z.object({ id: idSchema })).query(async ({ ctx, input }) => {+ const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_READ');+ const comment = await ctx.documentCommentModel.findById(input.id);+ if (!comment) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Document comment not found' });+ }+ await assertDocumentView(ctx, comment.documentId, grantedPermissions);+ return (await enrich(ctx, [comment]))[0];+ }),++ listReplies: documentCommentProcedure+ .input(pageSchema.extend({ rootCommentId: idSchema }))+ .query(async ({ ctx, input }) => {+ const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_READ');+ const root = await ctx.documentCommentModel.findById(input.rootCommentId);+ if (!root || root.parentCommentId) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Document comment thread not found' });+ }+ await assertDocumentView(ctx, root.documentId, grantedPermissions);+ const page = await ctx.documentCommentModel.listReplies(input);+ return { ...page, items: await enrich(ctx, page.items) };+ }),++ listThreads: documentCommentProcedure+ .input(pageSchema.extend({ documentId: idSchema }))+ .query(async ({ ctx, input }) => {+ const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_READ');+ await assertDocumentView(ctx, input.documentId, grantedPermissions);+ const page = await ctx.documentCommentModel.listThreads(input);+ const roots = await enrich(+ ctx,+ page.items.map(({ root }) => root),+ );+ return {+ ...page,+ items: page.items.map((thread, index) => ({ ...thread, root: roots[index] })),+ };+ }),++ summary: documentCommentProcedure+ .input(z.object({ documentId: idSchema }))+ .query(async ({ ctx, input }) => {+ const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_READ');+ await assertDocumentView(ctx, input.documentId, grantedPermissions);+ return ctx.documentCommentModel.summary(input.documentId);+ }),++ update: documentCommentProcedure+ .input(+ z+ .object({+ content: contentSchema.optional(),+ editorData: editorDataSchema.optional(),+ id: idSchema,+ })+ .refine((value) => value.content !== undefined || value.editorData !== undefined, {+ message: 'At least one field must be provided',+ })+ .superRefine(validateCommentBody),+ )+ .mutation(async ({ ctx, input }) => {+ const current = await ctx.documentCommentModel.findById(input.id);+ if (!current) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Document comment not found' });+ }+ const { grantedPermissions } = await assertPermission(ctx, 'DOCUMENT_COMMENT_UPDATE');+ await assertDocumentView(ctx, current.documentId, grantedPermissions);+ const { id, ...updates } = input;+ const nextMentionedUserIds =+ input.editorData === undefined+ ? undefined+ : await validateMentionedUserIds(ctx, input.editorData);+ const result = await ctx.documentCommentModel.update(id, updates, {+ mentionedUserIds: nextMentionedUserIds,+ });+ if (!result) throw new TRPCError({ code: 'FORBIDDEN', message: 'Cannot edit comment' });++ notifyActivitiesBestEffort(+ ctx,+ result.addedMentionUserIds.map((recipientUserId) => ({+ actorUserId: ctx.userId,+ commentId: result.comment.id,+ documentId: result.comment.documentId,+ kind: 'mentioned',+ recipientUserId,+ rootCommentId: result.comment.parentCommentId ?? result.comment.id,+ workspaceId: ctx.workspaceId,+ })),+ );+ publishCommentsChanged(+ ctx,+ result.comment.documentId,+ result.comment.parentCommentId ?? result.comment.id,+ );+ return (await enrich(ctx, [result.comment]))[0];+ }),+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 0e18fc8cd8d..21e1be578c9 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -48,6 +48,7 @@ import { configRouter } from './config';import { connectorRouter } from './connector';import { deviceRouter } from './device';import { documentRouter } from './document';+import { documentCommentRouter } from './documentComment';import { expertiseRouter } from './expertise';import { exporterRouter } from './exporter';import { fileRouter } from './file';@@ -124,6 +125,7 @@ export const lambdaRouter = router({connector: connectorRouter,device: deviceRouter,document: documentRouter,+ documentComment: documentCommentRouter,exporter: exporterRouter,file: fileRouter,followUpAction: followUpActionRouter,diff --git a/apps/server/src/services/resourceEvents/types.ts b/apps/server/src/services/resourceEvents/types.tsindex 7b2aa0cfca3..a0266111d21 100644--- a/apps/server/src/services/resourceEvents/types.ts+++ b/apps/server/src/services/resourceEvents/types.ts@@ -6,7 +6,8 @@ export interface ResourceRef {type: ResourceType;}-export type ResourceEventType = 'doc.updated' | 'lock.changed' | 'topic.commentsChanged';+export type ResourceEventType =+ 'doc.updated' | 'document.commentsChanged' | 'lock.changed' | 'topic.commentsChanged';export interface ResourceEvent {/** User id that triggered the event; allows subscriber-side attribution or filtering. */diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex 980172c77ba..3df2a52b3e1 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "تم الاستنفاد — يعاد التعيين {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "بالمعدل الحالي، تنتهي هذه النافذة حوالي {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "بالمعدل الحالي، تنفد الحصة حوالي {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "السعة المستخدمة","heteroAgent.claudeQuota.calendar.currentWindow": "النافذة الحالية","heteroAgent.claudeQuota.calendar.dayShare": "تم استخدام {{percent}}% من هذه النافذة","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} رموز · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "التاريخ غير مسجل","heteroAgent.claudeQuota.calendar.pace": "وتيرة متساوية","heteroAgent.claudeQuota.calendar.partialCost": "على الأقل {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "النافذة الأخيرة الملاحظة","heteroAgent.claudeQuota.calendar.rateLimited": "محدود السرعة","heteroAgent.claudeQuota.calendar.resetAt": "إعادة تعيين النافذة عند {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "إعادة المحاولة","input.inputCompletionError.settings": "الإعدادات","input.inputCompletionError.title": "توقفت اقتراحات الإدخال",+ "input.modelDisabled": "النموذج الحالي معطل",+ "input.modelDisabled.action": "تفعيل",+ "input.modelDisabled.actionFailed": "فشل في تفعيل النموذج. يرجى المحاولة مرة أخرى.",+ "input.modelDisabled.selectionFailed": "تم تفعيل النموذج، ولكن فشل التبديل بين المزودين. يرجى تحديده مرة أخرى للمتابعة.","input.modelFixedTip": "تم تثبيت النموذج في ملف تعريف الوكيل ولا يمكن تغييره أثناء الدردشة.","input.modelUnavailable": "النموذج الحالي لم يعد متاحًا. اختر نموذجًا آخر للمتابعة.","input.more": "المزيد",diff --git a/locales/ar/file.json b/locales/ar/file.jsonindex 10b133be2a5..c888490d0e8 100644--- a/locales/ar/file.json+++ b/locales/ar/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "إضافة أيقونة","pageEditor.autoSaveMessage": "يتم حفظ صفحتك تلقائيًا. لا حاجة للحفظ يدويًا.","pageEditor.chooseIcon": "اختر أيقونة",+ "pageEditor.comments.attachments.add": "إضافة",+ "pageEditor.comments.attachments.chooseLibrary": "اختر من المكتبة",+ "pageEditor.comments.author.deactivated": "مستخدم معطل",+ "pageEditor.comments.author.former": "عضو سابق",+ "pageEditor.comments.cancel": "إلغاء",+ "pageEditor.comments.createFailed": "فشل نشر التعليق. لا يزال المسودة موجودة هنا.",+ "pageEditor.comments.delete": "حذف",+ "pageEditor.comments.deleteConfirm.content": "هل تريد حذف هذا التعليق؟ ستظل الردود مرئية إذا كان لهذا التعليق سلسلة.",+ "pageEditor.comments.deleteConfirm.title": "حذف التعليق",+ "pageEditor.comments.deleteFailed": "فشل حذف التعليق. حاول مرة أخرى.",+ "pageEditor.comments.deleted": "تم حذف هذا التعليق.",+ "pageEditor.comments.edit": "تعديل",+ "pageEditor.comments.edited": "(تم التعديل)",+ "pageEditor.comments.empty": "لا توجد تعليقات حتى الآن. ابدأ المحادثة أدناه.",+ "pageEditor.comments.hideReplies": "إخفاء الردود",+ "pageEditor.comments.loadMore": "تحميل المزيد من التعليقات",+ "pageEditor.comments.loadMoreReplies": "تحميل المزيد من الردود",+ "pageEditor.comments.moreActions": "إجراءات إضافية",+ "pageEditor.comments.placeholder": "أضف تعليقًا...",+ "pageEditor.comments.publish": "تعليق",+ "pageEditor.comments.replies_one": "{{count}} رد",+ "pageEditor.comments.replies_other": "{{count}} ردود",+ "pageEditor.comments.replyAction": "رد",+ "pageEditor.comments.replyPlaceholder": "اكتب ردًا...",+ "pageEditor.comments.save": "حفظ",+ "pageEditor.comments.title": "التعليقات",+ "pageEditor.comments.updateFailed": "فشل تحديث التعليق. حاول مرة أخرى.","pageEditor.deleteConfirm.content": "سيتم حذف هذه الصفحة ولا يمكن استعادتها. يرجى المتابعة بحذر.","pageEditor.deleteConfirm.title": "حذف الصفحة","pageEditor.deleteError": "فشل في حذف الصفحة",diff --git a/locales/ar/notification.json b/locales/ar/notification.jsonindex ef34401d07b..95112fb0b4d 100644--- a/locales/ar/notification.json+++ b/locales/ar/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "تم إيقاف المهمة المجدولة \"{{jobName}}\" بعد {{count}} من حالات الفشل المتتالية. يرجى مراجعة الخطأ واستئنافها عند الاستعداد.","agent_cron_job_failed_paused_title": "تم إيقاف المهمة المجدولة","agent_cron_job_failed_title": "فشل المهمة المجدولة",+ "agent_intervention_required": "{{agent}} يحتاج إلى مدخلاتك: {{summary}}",+ "agent_intervention_required_title": "{{agent}} يحتاج إلى مراجعتك","agent_run_completed": "{{preview}}","agent_run_completed_title": "اكتملت مهمة الوكيل","agent_transfer_reassigned": "قام مالك مساحة العمل بنقل وكيلك \"{{agentTitle}}\" إلى {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "رصيدك الائتماني منخفض — يتبقى حوالي {{balance}} من الرصيد. قم بتفعيل إعادة التعبئة التلقائية حتى يتم تجديد رصيدك تلقائيًا ولا يتعطل عملك.","credit_balance_low_action": "قم بإعداد إعادة التعبئة التلقائية","credit_balance_low_title": "رصيدك الائتماني منخفض",+ "document_comment_activity": "{{actorLabel}} علق على مستندك \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} رد على تعليقك في \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "رد جديد على تعليقك",+ "document_comment_activity_title": "تعليق جديد على مستندك",+ "document_comment_mentioned": "{{actorLabel}} أشار إليك في تعليق على \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "تم الإشارة إليك في تعليق على مستند","email.footer.contactSupport": "اتصل بالدعم","email.footer.joinDiscord": "انضم إلى Discord","email.footer.manage": "إدارة الإشعارات",diff --git a/locales/ar/portal.json b/locales/ar/portal.jsonindex 0ea65c48438..fd103883c89 100644--- a/locales/ar/portal.json+++ b/locales/ar/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "نسخ الرابط","artifacts.deploy.copySuccess": "تم نسخ رابط النشر","artifacts.deploy.failed": "فشل النشر",+ "artifacts.deploy.highestPlanCapacityLimitReached": "تم الوصول إلى الحد الأقصى لسعة النشر الذاتي الحالية. قم بإدارة المشاريع المنشورة أو تقليل استخدام النشر.","artifacts.deploy.highestPlanLimitReached": "تم الوصول إلى الحد الأقصى للنشر العام ({{used}} / {{limit}}). قم بإلغاء نشر مشروع لتحرير مساحة.",+ "artifacts.deploy.highestPlanSizeLimitReached": "هذا الموقع هو {{actual}}، وهو أعلى من الحد الذاتي {{limit}}. قم بتقليل أصوله قبل النشر.","artifacts.deploy.history": "تاريخ المراجعات","artifacts.deploy.limitReached": "تم الوصول إلى الحد الأقصى للنشر العام ({{used}} / {{limit}}). قم بإلغاء نشر مشروع أو قم بترقية خطتك.","artifacts.deploy.open": "فتح النشر",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "نشر","artifacts.deploy.publishNewVersion": "نشر هذا الإصدار","artifacts.deploy.quotaUnavailable": "التحقق من حصة النشر غير متاح مؤقتًا. حاول مرة أخرى لاحقًا.",+ "artifacts.deploy.serviceOverloaded": "استضافة العناصر مؤقتًا محملة بشكل زائد. حاول النشر مرة أخرى قريبًا.","artifacts.deploy.success": "تم النشر","artifacts.deploy.writeInProgress": "هناك تغيير آخر في النشر قيد التنفيذ. حاول مرة أخرى قريبًا.","artifacts.display.code": "الشفرة",diff --git a/locales/ar/subscription.json b/locales/ar/subscription.jsonindex dc45cf0389e..466014282d8 100644--- a/locales/ar/subscription.json+++ b/locales/ar/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "فشل الترقية","payment.upgradeSuccess.desc": "تم ترقية خطة الاشتراك بنجاح","payment.upgradeSuccess.title": "تمت الترقية بنجاح",+ "plans.artifactHosting.deployments": "حتى {{count}} مواقع الأرتيفاكت النشطة",+ "plans.artifactHosting.siteSize": "حتى {{size}} لكل موقع منشور",+ "plans.artifactHosting.title": "استضافة الأرتيفاكت","plans.btn.contact": "اتصل بنا","plans.btn.noAction": "الخطة مقفلة","plans.btn.payment": "شراء",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex 27137bb1306..7ef938a961d 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Изчерпано — нулира се {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "С текущото темпо този прозорец завършва около {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "С текущото темпо квотата ще се изчерпи около {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Използван капацитет","heteroAgent.claudeQuota.calendar.currentWindow": "Текущ прозорец","heteroAgent.claudeQuota.calendar.dayShare": "Използвани {{percent}}% от този прозорец","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} токена · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Историята не е записана","heteroAgent.claudeQuota.calendar.pace": "Равномерно темпо","heteroAgent.claudeQuota.calendar.partialCost": "поне {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Последно наблюдаван прозорец","heteroAgent.claudeQuota.calendar.rateLimited": "Ограничено по скорост","heteroAgent.claudeQuota.calendar.resetAt": "Прозорецът се нулира в {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Опитай отново","input.inputCompletionError.settings": "Настройки","input.inputCompletionError.title": "Предложенията за въвеждане са паузирани",+ "input.modelDisabled": "Текущият модел е деактивиран",+ "input.modelDisabled.action": "Активиране",+ "input.modelDisabled.actionFailed": "Неуспешно активиране на модела. Моля, опитайте отново.",+ "input.modelDisabled.selectionFailed": "Моделът беше активиран, но превключването на доставчиците не успя. Изберете го отново, за да продължите.","input.modelFixedTip": "Моделът е фиксиран в профила на агента и не може да бъде сменен по време на чат.","input.modelUnavailable": "Текущият модел вече не е наличен. Изберете друг модел, за да продължите.","input.more": "Още",diff --git a/locales/bg-BG/file.json b/locales/bg-BG/file.jsonindex 2bed01c865b..73f589b30fa 100644--- a/locales/bg-BG/file.json+++ b/locales/bg-BG/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Добави икона","pageEditor.autoSaveMessage": "Страницата се запазва автоматично. Не е нужно ръчно запазване.","pageEditor.chooseIcon": "Избери икона",+ "pageEditor.comments.attachments.add": "Добави",+ "pageEditor.comments.attachments.chooseLibrary": "Избери от библиотеката",+ "pageEditor.comments.author.deactivated": "Деактивиран потребител",+ "pageEditor.comments.author.former": "Бивш член",+ "pageEditor.comments.cancel": "Отказ",+ "pageEditor.comments.createFailed": "Неуспешно публикуване на коментар. Вашият чернови все още е тук.",+ "pageEditor.comments.delete": "Изтрий",+ "pageEditor.comments.deleteConfirm.content": "Да изтрия ли този коментар? Отговорите ще останат видими, ако този коментар има нишка.",+ "pageEditor.comments.deleteConfirm.title": "Изтриване на коментар",+ "pageEditor.comments.deleteFailed": "Неуспешно изтриване на коментар. Опитайте отново.",+ "pageEditor.comments.deleted": "Този коментар беше изтрит.",+ "pageEditor.comments.edit": "Редактирай",+ "pageEditor.comments.edited": "(редактирано)",+ "pageEditor.comments.empty": "Все още няма коментари. Започнете разговора по-долу.",+ "pageEditor.comments.hideReplies": "Скрий отговорите",+ "pageEditor.comments.loadMore": "Зареди още коментари",+ "pageEditor.comments.loadMoreReplies": "Зареди още отговори",+ "pageEditor.comments.moreActions": "Още действия",+ "pageEditor.comments.placeholder": "Добавете коментар…",+ "pageEditor.comments.publish": "Коментар",+ "pageEditor.comments.replies_one": "{{count}} отговор",+ "pageEditor.comments.replies_other": "{{count}} отговори",+ "pageEditor.comments.replyAction": "Отговори",+ "pageEditor.comments.replyPlaceholder": "Напишете отговор…",+ "pageEditor.comments.save": "Запази",+ "pageEditor.comments.title": "Коментари",+ "pageEditor.comments.updateFailed": "Неуспешно обновяване на коментар. Опитайте отново.","pageEditor.deleteConfirm.content": "Тази страница ще бъде изтрита и не може да бъде възстановена. Моля, бъдете внимателни.","pageEditor.deleteConfirm.title": "Изтриване на страница","pageEditor.deleteError": "Неуспешно изтриване на страницата",diff --git a/locales/bg-BG/notification.json b/locales/bg-BG/notification.jsonindex ca9974f4dc2..25a6535b444 100644--- a/locales/bg-BG/notification.json+++ b/locales/bg-BG/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Вашата планирана задача \"{{jobName}}\" беше спряна след {{count}} последователни неуспеха. Прегледайте грешката и я възобновете, когато сте готови.","agent_cron_job_failed_paused_title": "Планираната задача е спряна","agent_cron_job_failed_title": "Планираната задача се провали",+ "agent_intervention_required": "{{agent}} се нуждае от вашето съдействие: {{summary}}",+ "agent_intervention_required_title": "{{agent}} се нуждае от вашия преглед","agent_run_completed": "{{preview}}","agent_run_completed_title": "Задачата на агента е завършена","agent_transfer_reassigned": "Собственик на работно пространство прехвърли вашия агент \"{{agentTitle}}\" на {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Вашият кредитен баланс е нисък — остават около {{balance}} кредита. Включете автоматично зареждане, за да се попълва балансът ви автоматично и работата ви да не бъде прекъсвана.","credit_balance_low_action": "Настройте автоматично зареждане","credit_balance_low_title": "Вашият кредитен баланс е нисък",+ "document_comment_activity": "{{actorLabel}} коментира вашия документ \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} отговори на вашия коментар в \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Нов отговор на вашия коментар",+ "document_comment_activity_title": "Нов коментар във вашия документ",+ "document_comment_mentioned": "{{actorLabel}} ви спомена в коментар на \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Бяхте споменати в коментар на документ","email.footer.contactSupport": "Свържете се с поддръжката","email.footer.joinDiscord": "Присъединете се към Discord","email.footer.manage": "Управление на известията",diff --git a/locales/bg-BG/portal.json b/locales/bg-BG/portal.jsonindex bf710432bf4..69d560ba456 100644--- a/locales/bg-BG/portal.json+++ b/locales/bg-BG/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Копирай URL","artifacts.deploy.copySuccess": "URL за разгръщане е копиран","artifacts.deploy.failed": "Разгръщането не успя",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Достигнат е текущият лимит за капацитет на самообслужващо разгръщане. Управлявайте публикуваните проекти или намалете използването на разгръщане.","artifacts.deploy.highestPlanLimitReached": "Достигнат е лимитът за публично разгръщане ({{used}} / {{limit}}). Премахнете публикуването на проект, за да освободите място.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Този сайт е {{actual}}, над {{limit}} лимита за самообслужване. Намалете неговите ресурси преди публикуване.","artifacts.deploy.history": "История на ревизиите","artifacts.deploy.limitReached": "Достигнат е лимитът за публично разгръщане ({{used}} / {{limit}}). Премахнете публикуването на проект или надградете плана си.","artifacts.deploy.open": "Отвори разгръщането",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Публикувай","artifacts.deploy.publishNewVersion": "Публикувай тази версия","artifacts.deploy.quotaUnavailable": "Проверката на квотата за разгръщане временно не е налична. Опитайте отново по-късно.",+ "artifacts.deploy.serviceOverloaded": "Хостингът на артефакти временно е претоварен. Опитайте да публикувате отново след малко.","artifacts.deploy.success": "Публикувано","artifacts.deploy.writeInProgress": "Друга промяна в разгръщането е в процес. Опитайте отново след малко.","artifacts.display.code": "Код",diff --git a/locales/bg-BG/subscription.json b/locales/bg-BG/subscription.jsonindex 8a9c7abaf13..1d90daad7ab 100644--- a/locales/bg-BG/subscription.json+++ b/locales/bg-BG/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Неуспешна надстройка","payment.upgradeSuccess.desc": "Твоят абонаментен план е надстроен успешно","payment.upgradeSuccess.title": "Успешна надстройка",+ "plans.artifactHosting.deployments": "До {{count}} активни артефактни сайтове",+ "plans.artifactHosting.siteSize": "До {{size}} на публикуван сайт",+ "plans.artifactHosting.title": "Хостинг на артефакти","plans.btn.contact": "Свържи се с нас","plans.btn.noAction": "Планът е заключен","plans.btn.payment": "Закупи",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex c3e0fd6a90a..84f3732b39f 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Erschöpft — wird zurückgesetzt {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "Bei aktuellem Tempo endet dieses Fenster bei etwa {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "Bei aktuellem Tempo läuft die Quote etwa um {{time}} aus",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Kapazität genutzt","heteroAgent.claudeQuota.calendar.currentWindow": "Aktuelles Fenster","heteroAgent.claudeQuota.calendar.dayShare": "{{percent}}% dieses Fensters genutzt","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} Tokens · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Historie nicht aufgezeichnet","heteroAgent.claudeQuota.calendar.pace": "Gleichmäßiges Tempo","heteroAgent.claudeQuota.calendar.partialCost": "mindestens {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Zuletzt beobachtetes Fenster","heteroAgent.claudeQuota.calendar.rateLimited": "Rate begrenzt","heteroAgent.claudeQuota.calendar.resetAt": "Fenster wird zurückgesetzt um {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Wiederholen","input.inputCompletionError.settings": "Einstellungen","input.inputCompletionError.title": "Eingabevorschläge pausiert",+ "input.modelDisabled": "Das aktuelle Modell ist deaktiviert",+ "input.modelDisabled.action": "Aktivieren",+ "input.modelDisabled.actionFailed": "Das Aktivieren des Modells ist fehlgeschlagen. Bitte versuchen Sie es erneut.",+ "input.modelDisabled.selectionFailed": "Das Modell wurde aktiviert, aber das Wechseln des Anbieters ist fehlgeschlagen. Wählen Sie es erneut aus, um fortzufahren.","input.modelFixedTip": "Das Modell ist im Agentenprofil festgelegt und kann während des Chats nicht gewechselt werden.","input.modelUnavailable": "Das aktuelle Modell ist nicht mehr verfügbar. Wählen Sie ein anderes Modell, um fortzufahren.","input.more": "Mehr",diff --git a/locales/de-DE/file.json b/locales/de-DE/file.jsonindex 2a92eafb7a9..9db87e4c0a9 100644--- a/locales/de-DE/file.json+++ b/locales/de-DE/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Symbol hinzufügen","pageEditor.autoSaveMessage": "Ihre Seite wird automatisch gespeichert. Ein manuelles Speichern ist nicht erforderlich.","pageEditor.chooseIcon": "Symbol auswählen",+ "pageEditor.comments.attachments.add": "Hinzufügen",+ "pageEditor.comments.attachments.chooseLibrary": "Aus der Bibliothek auswählen",+ "pageEditor.comments.author.deactivated": "Deaktivierter Benutzer",+ "pageEditor.comments.author.former": "Ehemaliges Mitglied",+ "pageEditor.comments.cancel": "Abbrechen",+ "pageEditor.comments.createFailed": "Kommentar konnte nicht veröffentlicht werden. Ihr Entwurf ist noch vorhanden.",+ "pageEditor.comments.delete": "Löschen",+ "pageEditor.comments.deleteConfirm.content": "Diesen Kommentar löschen? Antworten bleiben sichtbar, wenn dieser Kommentar einen Thread hat.",+ "pageEditor.comments.deleteConfirm.title": "Kommentar löschen",+ "pageEditor.comments.deleteFailed": "Kommentar konnte nicht gelöscht werden. Versuchen Sie es erneut.",+ "pageEditor.comments.deleted": "Dieser Kommentar wurde gelöscht.",+ "pageEditor.comments.edit": "Bearbeiten",+ "pageEditor.comments.edited": "(bearbeitet)",+ "pageEditor.comments.empty": "Noch keine Kommentare. Beginnen Sie unten das Gespräch.",+ "pageEditor.comments.hideReplies": "Antworten ausblenden",+ "pageEditor.comments.loadMore": "Mehr Kommentare laden",+ "pageEditor.comments.loadMoreReplies": "Mehr Antworten laden",+ "pageEditor.comments.moreActions": "Weitere Aktionen",+ "pageEditor.comments.placeholder": "Einen Kommentar hinzufügen…",+ "pageEditor.comments.publish": "Kommentieren",+ "pageEditor.comments.replies_one": "{{count}} Antwort",+ "pageEditor.comments.replies_other": "{{count}} Antworten",+ "pageEditor.comments.replyAction": "Antworten",+ "pageEditor.comments.replyPlaceholder": "Eine Antwort schreiben…",+ "pageEditor.comments.save": "Speichern",+ "pageEditor.comments.title": "Kommentare",+ "pageEditor.comments.updateFailed": "Kommentar konnte nicht aktualisiert werden. Versuchen Sie es erneut.","pageEditor.deleteConfirm.content": "Diese Seite wird gelöscht und kann nicht wiederhergestellt werden. Bitte seien Sie vorsichtig.","pageEditor.deleteConfirm.title": "Seite löschen","pageEditor.deleteError": "Fehler beim Löschen der Seite",diff --git a/locales/de-DE/notification.json b/locales/de-DE/notification.jsonindex 2ce21e47173..edeef4633bf 100644--- a/locales/de-DE/notification.json+++ b/locales/de-DE/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Ihre geplante Aufgabe \"{{jobName}}\" wurde nach {{count}} aufeinanderfolgenden Fehlern pausiert. Überprüfen Sie den Fehler und setzen Sie die Aufgabe fort, wenn Sie bereit sind.","agent_cron_job_failed_paused_title": "Geplante Aufgabe pausiert","agent_cron_job_failed_title": "Geplante Aufgabe fehlgeschlagen",+ "agent_intervention_required": "{{agent}} benötigt Ihre Eingabe: {{summary}}",+ "agent_intervention_required_title": "{{agent}} benötigt Ihre Überprüfung","agent_run_completed": "{{preview}}","agent_run_completed_title": "Agentenaufgabe abgeschlossen","agent_transfer_reassigned": "Ein Workspace-Besitzer hat Ihren Agenten \"{{agentTitle}}\" an {{recipientLabel}} übertragen.",@@ -32,6 +34,12 @@"credit_balance_low": "Ihr Guthaben ist fast aufgebraucht — es sind nur noch etwa {{balance}} Credits übrig. Aktivieren Sie die automatische Aufladung, damit Ihr Guthaben automatisch aufgefüllt wird und Ihre Arbeit nicht unterbrochen wird.","credit_balance_low_action": "Automatische Aufladung einrichten","credit_balance_low_title": "Ihr Guthaben ist fast aufgebraucht",+ "document_comment_activity": "{{actorLabel}} hat einen Kommentar zu Ihrem Dokument \"{{documentTitle}}\" hinterlassen.",+ "document_comment_activity_replied": "{{actorLabel}} hat auf Ihren Kommentar in \"{{documentTitle}}\" geantwortet.",+ "document_comment_activity_replied_title": "Neue Antwort auf Ihren Kommentar",+ "document_comment_activity_title": "Neuer Kommentar zu Ihrem Dokument",+ "document_comment_mentioned": "{{actorLabel}} hat Sie in einem Kommentar zu \"{{documentTitle}}\" erwähnt.",+ "document_comment_mentioned_title": "Sie wurden in einem Dokumentkommentar erwähnt","email.footer.contactSupport": "Support kontaktieren","email.footer.joinDiscord": "Discord beitreten","email.footer.manage": "Benachrichtigungen verwalten",diff --git a/locales/de-DE/portal.json b/locales/de-DE/portal.jsonindex c263b40ed5e..9553456f279 100644--- a/locales/de-DE/portal.json+++ b/locales/de-DE/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "URL kopieren","artifacts.deploy.copySuccess": "Bereitstellungs-URL kopiert","artifacts.deploy.failed": "Bereitstellung fehlgeschlagen",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Die aktuelle Kapazitätsgrenze für die Selbstbedienungsbereitstellung wurde erreicht. Verwalten Sie veröffentlichte Projekte oder reduzieren Sie die Bereitstellungsnutzung.","artifacts.deploy.highestPlanLimitReached": "Öffentliches Bereitstellungslimit erreicht ({{used}} / {{limit}}). Heben Sie die Veröffentlichung eines Projekts auf, um einen Slot freizugeben.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Diese Website ist {{actual}}, über dem Selbstbedienungslimit von {{limit}}. Reduzieren Sie ihre Assets, bevor Sie sie veröffentlichen.","artifacts.deploy.history": "Versionsverlauf","artifacts.deploy.limitReached": "Öffentliches Bereitstellungslimit erreicht ({{used}} / {{limit}}). Heben Sie die Veröffentlichung eines Projekts auf oder aktualisieren Sie Ihren Plan.","artifacts.deploy.open": "Bereitstellung öffnen",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Veröffentlichen","artifacts.deploy.publishNewVersion": "Diese Version veröffentlichen","artifacts.deploy.quotaUnavailable": "Die Validierung des Bereitstellungskontingents ist vorübergehend nicht verfügbar. Versuchen Sie es später erneut.",+ "artifacts.deploy.serviceOverloaded": "Das Hosting von Artefakten ist vorübergehend überlastet. Versuchen Sie, in Kürze erneut zu veröffentlichen.","artifacts.deploy.success": "Veröffentlicht","artifacts.deploy.writeInProgress": "Eine andere Bereitstellungsänderung ist gerade in Bearbeitung. Versuchen Sie es in Kürze erneut.","artifacts.display.code": "Code",diff --git a/locales/de-DE/subscription.json b/locales/de-DE/subscription.jsonindex 17039631ca8..24fdabc6b24 100644--- a/locales/de-DE/subscription.json+++ b/locales/de-DE/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Upgrade fehlgeschlagen","payment.upgradeSuccess.desc": "Ihr Abonnement wurde erfolgreich aktualisiert","payment.upgradeSuccess.title": "Upgrade erfolgreich",+ "plans.artifactHosting.deployments": "Bis zu {{count}} aktive Artifact-Seiten",+ "plans.artifactHosting.siteSize": "Bis zu {{size}} pro veröffentlichter Seite",+ "plans.artifactHosting.title": "Artifact-Hosting","plans.btn.contact": "Kontaktieren Sie uns","plans.btn.noAction": "Plan gesperrt","plans.btn.payment": "Kaufen",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex d87b8846b36..0e35188dfbd 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Add Icon","pageEditor.autoSaveMessage": "Your page is saved automatically. No need to save manually.","pageEditor.chooseIcon": "Choose Icon",+ "pageEditor.comments.attachments.add": "Add",+ "pageEditor.comments.attachments.chooseLibrary": "Choose from Library",+ "pageEditor.comments.author.deactivated": "Deactivated user",+ "pageEditor.comments.author.former": "Former member",+ "pageEditor.comments.cancel": "Cancel",+ "pageEditor.comments.createFailed": "Failed to publish comment. Your draft is still here.",+ "pageEditor.comments.delete": "Delete",+ "pageEditor.comments.deleteConfirm.content": "Delete this comment? Replies will remain visible if this comment has a thread.",+ "pageEditor.comments.deleteConfirm.title": "Delete comment",+ "pageEditor.comments.deleteFailed": "Failed to delete comment. Try again.",+ "pageEditor.comments.deleted": "This comment was deleted.",+ "pageEditor.comments.edit": "Edit",+ "pageEditor.comments.edited": "(edited)",+ "pageEditor.comments.empty": "No comments yet. Start the conversation below.",+ "pageEditor.comments.hideReplies": "Hide replies",+ "pageEditor.comments.loadMore": "Load more comments",+ "pageEditor.comments.loadMoreReplies": "Load more replies",+ "pageEditor.comments.moreActions": "More actions",+ "pageEditor.comments.placeholder": "Add a comment…",+ "pageEditor.comments.publish": "Comment",+ "pageEditor.comments.replies_one": "{{count}} reply",+ "pageEditor.comments.replies_other": "{{count}} replies",+ "pageEditor.comments.replyAction": "Reply",+ "pageEditor.comments.replyPlaceholder": "Write a reply…",+ "pageEditor.comments.save": "Save",+ "pageEditor.comments.title": "Comments",+ "pageEditor.comments.updateFailed": "Failed to update comment. Try again.","pageEditor.deleteConfirm.content": "This page will be deleted and cannot be recovered. Please proceed with caution.","pageEditor.deleteConfirm.title": "Delete Page","pageEditor.deleteError": "Failed to delete the page",diff --git a/locales/en-US/notification.json b/locales/en-US/notification.jsonindex 3f25d7f9bff..d06c6a7ec66 100644--- a/locales/en-US/notification.json+++ b/locales/en-US/notification.json@@ -34,6 +34,12 @@"credit_balance_low": "Your credit balance is running low — about {{balance}} in credits remaining. Turn on auto top-up so your balance refills automatically and your work is never interrupted.","credit_balance_low_action": "Set up auto top-up","credit_balance_low_title": "Your credit balance is running low",+ "document_comment_activity": "{{actorLabel}} commented on your document \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} replied to your comment in \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "New reply to your comment",+ "document_comment_activity_title": "New comment on your document",+ "document_comment_mentioned": "{{actorLabel}} mentioned you in a comment on \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "You were mentioned in a document comment","email.footer.contactSupport": "Contact support","email.footer.joinDiscord": "Join Discord","email.footer.manage": "Manage notifications",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex b69a52cbcc8..9a15d18ee3c 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Agotado — se reinicia {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "A este ritmo, esta ventana termina alrededor del {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "A este ritmo, la cuota se agotará alrededor de {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Capacidad utilizada","heteroAgent.claudeQuota.calendar.currentWindow": "Ventana actual","heteroAgent.claudeQuota.calendar.dayShare": "Usado {{percent}}% de esta ventana","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} tokens · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Historial no registrado","heteroAgent.claudeQuota.calendar.pace": "Ritmo uniforme","heteroAgent.claudeQuota.calendar.partialCost": "al menos {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Última ventana observada","heteroAgent.claudeQuota.calendar.rateLimited": "Limitado por tasa","heteroAgent.claudeQuota.calendar.resetAt": "La ventana se reinicia a las {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Reintentar","input.inputCompletionError.settings": "Configuración","input.inputCompletionError.title": "Sugerencias de entrada pausadas",+ "input.modelDisabled": "El modelo actual está deshabilitado",+ "input.modelDisabled.action": "Habilitar",+ "input.modelDisabled.actionFailed": "No se pudo habilitar el modelo. Por favor, inténtalo de nuevo.",+ "input.modelDisabled.selectionFailed": "El modelo fue habilitado, pero el cambio de proveedores falló. Selecciónalo nuevamente para continuar.","input.modelFixedTip": "El modelo está fijado en el perfil del agente y no se puede cambiar durante la conversación.","input.modelUnavailable": "El modelo actual ya no está disponible. Elige otro modelo para continuar.","input.more": "Más",diff --git a/locales/es-ES/file.json b/locales/es-ES/file.jsonindex 38f7020e61b..fbd7715f7a2 100644--- a/locales/es-ES/file.json+++ b/locales/es-ES/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Agregar ícono","pageEditor.autoSaveMessage": "Tu página se guarda automáticamente. No es necesario guardar manualmente.","pageEditor.chooseIcon": "Elegir ícono",+ "pageEditor.comments.attachments.add": "Agregar",+ "pageEditor.comments.attachments.chooseLibrary": "Elegir de la biblioteca",+ "pageEditor.comments.author.deactivated": "Usuario desactivado",+ "pageEditor.comments.author.former": "Miembro anterior",+ "pageEditor.comments.cancel": "Cancelar",+ "pageEditor.comments.createFailed": "No se pudo publicar el comentario. Tu borrador sigue aquí.",+ "pageEditor.comments.delete": "Eliminar",+ "pageEditor.comments.deleteConfirm.content": "¿Eliminar este comentario? Las respuestas seguirán siendo visibles si este comentario tiene un hilo.",+ "pageEditor.comments.deleteConfirm.title": "Eliminar comentario",+ "pageEditor.comments.deleteFailed": "No se pudo eliminar el comentario. Inténtalo de nuevo.",+ "pageEditor.comments.deleted": "Este comentario fue eliminado.",+ "pageEditor.comments.edit": "Editar",+ "pageEditor.comments.edited": "(editado)",+ "pageEditor.comments.empty": "Aún no hay comentarios. Comienza la conversación abajo.",+ "pageEditor.comments.hideReplies": "Ocultar respuestas",+ "pageEditor.comments.loadMore": "Cargar más comentarios",+ "pageEditor.comments.loadMoreReplies": "Cargar más respuestas",+ "pageEditor.comments.moreActions": "Más acciones",+ "pageEditor.comments.placeholder": "Añadir un comentario…",+ "pageEditor.comments.publish": "Comentar",+ "pageEditor.comments.replies_one": "{{count}} respuesta",+ "pageEditor.comments.replies_other": "{{count}} respuestas",+ "pageEditor.comments.replyAction": "Responder",+ "pageEditor.comments.replyPlaceholder": "Escribe una respuesta…",+ "pageEditor.comments.save": "Guardar",+ "pageEditor.comments.title": "Comentarios",+ "pageEditor.comments.updateFailed": "No se pudo actualizar el comentario. Inténtalo de nuevo.","pageEditor.deleteConfirm.content": "Esta página se eliminará y no se podrá recuperar. Procede con precaución.","pageEditor.deleteConfirm.title": "Eliminar página","pageEditor.deleteError": "Error al eliminar la página",diff --git a/locales/es-ES/notification.json b/locales/es-ES/notification.jsonindex 38c39955f45..8e1fb79ce17 100644--- a/locales/es-ES/notification.json+++ b/locales/es-ES/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Tu tarea programada \"{{jobName}}\" se pausó después de {{count}} fallos consecutivos. Revisa el error y reanúdala cuando estés listo.","agent_cron_job_failed_paused_title": "Tarea programada pausada","agent_cron_job_failed_title": "Fallo en la tarea programada",+ "agent_intervention_required": "{{agent}} necesita tu intervención: {{summary}}",+ "agent_intervention_required_title": "{{agent}} necesita tu revisión","agent_run_completed": "{{preview}}","agent_run_completed_title": "Tarea del agente completada","agent_transfer_reassigned": "Un propietario del espacio de trabajo transfirió tu agente \"{{agentTitle}}\" a {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Tu saldo de crédito está bajo — te quedan aproximadamente {{balance}} en créditos. Activa la recarga automática para que tu saldo se reponga automáticamente y tu trabajo nunca se interrumpa.","credit_balance_low_action": "Configurar recarga automática","credit_balance_low_title": "Tu saldo de crédito está bajo",+ "document_comment_activity": "{{actorLabel}} comentó en tu documento \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} respondió a tu comentario en \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Nueva respuesta a tu comentario",+ "document_comment_activity_title": "Nuevo comentario en tu documento",+ "document_comment_mentioned": "{{actorLabel}} te mencionó en un comentario en \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Fuiste mencionado en un comentario de un documento","email.footer.contactSupport": "Contactar soporte","email.footer.joinDiscord": "Unirse a Discord","email.footer.manage": "Gestionar notificaciones",diff --git a/locales/es-ES/portal.json b/locales/es-ES/portal.jsonindex dadba0021d8..84f6788d391 100644--- a/locales/es-ES/portal.json+++ b/locales/es-ES/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Copiar URL","artifacts.deploy.copySuccess": "URL de despliegue copiada","artifacts.deploy.failed": "Despliegue fallido",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Se ha alcanzado la capacidad máxima de implementación de autoservicio actual. Administra los proyectos publicados o reduce el uso de implementación.","artifacts.deploy.highestPlanLimitReached": "Se alcanzó el límite de despliegues públicos ({{used}} / {{limit}}). Despublica un proyecto para liberar un espacio.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Este sitio tiene un tamaño de {{actual}}, que supera el límite de autoservicio de {{limit}}. Reduce sus activos antes de publicar.","artifacts.deploy.history": "Historial de revisiones","artifacts.deploy.limitReached": "Se alcanzó el límite de despliegues públicos ({{used}} / {{limit}}). Despublica un proyecto o mejora tu plan.","artifacts.deploy.open": "Abrir despliegue",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Publicar","artifacts.deploy.publishNewVersion": "Publicar esta versión","artifacts.deploy.quotaUnavailable": "La validación de la cuota de despliegue no está disponible temporalmente. Intenta nuevamente más tarde.",+ "artifacts.deploy.serviceOverloaded": "El alojamiento de artefactos está temporalmente sobrecargado. Intenta publicar nuevamente en breve.","artifacts.deploy.success": "Publicado","artifacts.deploy.writeInProgress": "Otro cambio de despliegue está en progreso. Intenta nuevamente en breve.","artifacts.display.code": "Código",diff --git a/locales/es-ES/subscription.json b/locales/es-ES/subscription.jsonindex 04d6be7d627..93c71aaa5f4 100644--- a/locales/es-ES/subscription.json+++ b/locales/es-ES/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Actualización Fallida","payment.upgradeSuccess.desc": "Tu plan de suscripción se ha actualizado correctamente","payment.upgradeSuccess.title": "Actualización Exitosa",+ "plans.artifactHosting.deployments": "Hasta {{count}} sitios de artefactos activos",+ "plans.artifactHosting.siteSize": "Hasta {{size}} por sitio publicado",+ "plans.artifactHosting.title": "Alojamiento de Artefactos","plans.btn.contact": "Contáctanos","plans.btn.noAction": "Plan Bloqueado","plans.btn.payment": "Comprar",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 16604e94946..c951cdcb4e1 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "تمام شده — بازنشانی {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "با سرعت فعلی این پنجره حدود {{percent}}% پایان مییابد","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "با سرعت فعلی، سهمیه حدود {{time}} تمام میشود",- "heteroAgent.claudeQuota.calendar.capacityUsed": "ظرفیت استفاده شده","heteroAgent.claudeQuota.calendar.currentWindow": "پنجره فعلی","heteroAgent.claudeQuota.calendar.dayShare": "{{percent}}% از این پنجره استفاده شده","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} توکن · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "تاریخچه ثبت نشده","heteroAgent.claudeQuota.calendar.pace": "سرعت یکنواخت","heteroAgent.claudeQuota.calendar.partialCost": "حداقل {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "پنجره مشاهده شده قبلی","heteroAgent.claudeQuota.calendar.rateLimited": "محدودیت نرخ","heteroAgent.claudeQuota.calendar.resetAt": "پنجره در {{time}} بازنشانی میشود",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "تلاش مجدد","input.inputCompletionError.settings": "تنظیمات","input.inputCompletionError.title": "پیشنهادات ورودی متوقف شدند",+ "input.modelDisabled": "مدل فعلی غیرفعال است",+ "input.modelDisabled.action": "فعال کردن",+ "input.modelDisabled.actionFailed": "فعال کردن مدل با شکست مواجه شد. لطفاً دوباره تلاش کنید.",+ "input.modelDisabled.selectionFailed": "مدل فعال شد، اما تغییر ارائهدهندگان با شکست مواجه شد. دوباره آن را انتخاب کنید تا ادامه دهید.","input.modelFixedTip": "مدل در پروفایل نماینده ثابت است و نمیتوان آن را هنگام چت تغییر داد.","input.modelUnavailable": "مدل فعلی دیگر در دسترس نیست. برای ادامه مدل دیگری را انتخاب کنید.","input.more": "بیشتر",diff --git a/locales/fa-IR/file.json b/locales/fa-IR/file.jsonindex 6d354321102..217ae3c56f8 100644--- a/locales/fa-IR/file.json+++ b/locales/fa-IR/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "افزودن آیکون","pageEditor.autoSaveMessage": "صفحه شما بهصورت خودکار ذخیره میشود. نیازی به ذخیره دستی نیست.","pageEditor.chooseIcon": "انتخاب آیکون",+ "pageEditor.comments.attachments.add": "افزودن",+ "pageEditor.comments.attachments.chooseLibrary": "انتخاب از کتابخانه",+ "pageEditor.comments.author.deactivated": "کاربر غیرفعال",+ "pageEditor.comments.author.former": "عضو سابق",+ "pageEditor.comments.cancel": "لغو",+ "pageEditor.comments.createFailed": "انتشار نظر ناموفق بود. پیشنویس شما هنوز موجود است.",+ "pageEditor.comments.delete": "حذف",+ "pageEditor.comments.deleteConfirm.content": "آیا این نظر حذف شود؟ پاسخها همچنان قابل مشاهده خواهند بود اگر این نظر دارای رشتهای باشد.",+ "pageEditor.comments.deleteConfirm.title": "حذف نظر",+ "pageEditor.comments.deleteFailed": "حذف نظر ناموفق بود. دوباره تلاش کنید.",+ "pageEditor.comments.deleted": "این نظر حذف شده است.",+ "pageEditor.comments.edit": "ویرایش",+ "pageEditor.comments.edited": "(ویرایش شده)",+ "pageEditor.comments.empty": "هنوز نظری وجود ندارد. مکالمه را در زیر شروع کنید.",+ "pageEditor.comments.hideReplies": "پنهان کردن پاسخها",+ "pageEditor.comments.loadMore": "بارگذاری نظرات بیشتر",+ "pageEditor.comments.loadMoreReplies": "بارگذاری پاسخهای بیشتر",+ "pageEditor.comments.moreActions": "اقدامات بیشتر",+ "pageEditor.comments.placeholder": "یک نظر اضافه کنید...",+ "pageEditor.comments.publish": "نظر دهید",+ "pageEditor.comments.replies_one": "{{count}} پاسخ",+ "pageEditor.comments.replies_other": "{{count}} پاسخها",+ "pageEditor.comments.replyAction": "پاسخ دهید",+ "pageEditor.comments.replyPlaceholder": "یک پاسخ بنویسید...",+ "pageEditor.comments.save": "ذخیره",+ "pageEditor.comments.title": "نظرات",+ "pageEditor.comments.updateFailed": "بهروزرسانی نظر ناموفق بود. دوباره تلاش کنید.","pageEditor.deleteConfirm.content": "این صفحه حذف خواهد شد و قابل بازیابی نیست. لطفاً با احتیاط ادامه دهید.","pageEditor.deleteConfirm.title": "حذف صفحه","pageEditor.deleteError": "حذف صفحه ناموفق بود",diff --git a/locales/fa-IR/notification.json b/locales/fa-IR/notification.jsonindex f86ec28eb28..c265f1e1db6 100644--- a/locales/fa-IR/notification.json+++ b/locales/fa-IR/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "وظیفه زمانبندی شده شما \"{{jobName}}\" پس از {{count}} شکست متوالی متوقف شد. خطا را بررسی کنید و زمانی که آماده بودید آن را از سر بگیرید.","agent_cron_job_failed_paused_title": "وظیفه زمانبندی شده متوقف شد","agent_cron_job_failed_title": "خطا در وظیفه زمانبندیشده",+ "agent_intervention_required": "{{agent}} به ورودی شما نیاز دارد: {{summary}}",+ "agent_intervention_required_title": "{{agent}} به بررسی شما نیاز دارد","agent_run_completed": "{{preview}}","agent_run_completed_title": "وظیفه عامل به پایان رسید","agent_transfer_reassigned": "یک مالک فضای کاری نماینده شما \"{{agentTitle}}\" را به {{recipientLabel}} منتقل کرد.",@@ -32,6 +34,12 @@"credit_balance_low": "اعتبار شما در حال کاهش است — حدود {{balance}} اعتبار باقی مانده است. شارژ خودکار را فعال کنید تا اعتبار شما به صورت خودکار شارژ شود و کار شما هرگز متوقف نشود.","credit_balance_low_action": "تنظیم شارژ خودکار","credit_balance_low_title": "اعتبار شما در حال کاهش است",+ "document_comment_activity": "{{actorLabel}} روی سند شما \"{{documentTitle}}\" نظر داد.",+ "document_comment_activity_replied": "{{actorLabel}} به نظر شما در \"{{documentTitle}}\" پاسخ داد.",+ "document_comment_activity_replied_title": "پاسخ جدید به نظر شما",+ "document_comment_activity_title": "نظر جدید روی سند شما",+ "document_comment_mentioned": "{{actorLabel}} شما را در نظری روی \"{{documentTitle}}\" ذکر کرد.",+ "document_comment_mentioned_title": "شما در یک نظر سند ذکر شدید","email.footer.contactSupport": "تماس با پشتیبانی","email.footer.joinDiscord": "به دیسکورد بپیوندید","email.footer.manage": "مدیریت اعلانها",diff --git a/locales/fa-IR/portal.json b/locales/fa-IR/portal.jsonindex fad5ba6fb99..57611d0d832 100644--- a/locales/fa-IR/portal.json+++ b/locales/fa-IR/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "کپی کردن آدرس","artifacts.deploy.copySuccess": "آدرس انتشار کپی شد","artifacts.deploy.failed": "انتشار ناموفق بود",+ "artifacts.deploy.highestPlanCapacityLimitReached": "ظرفیت فعلی استقرار خودکار به حداکثر رسیده است. پروژههای منتشر شده را مدیریت کنید یا استفاده از استقرار را کاهش دهید.","artifacts.deploy.highestPlanLimitReached": "حد مجاز انتشار عمومی به پایان رسید ({{used}} / {{limit}}). یک پروژه را لغو انتشار کنید تا یک جایگاه آزاد شود.",+ "artifacts.deploy.highestPlanSizeLimitReached": "این سایت {{actual}} است، که بالاتر از محدودیت خودکار {{limit}} است. داراییهای آن را قبل از انتشار کاهش دهید.","artifacts.deploy.history": "تاریخچه نسخهها","artifacts.deploy.limitReached": "حد مجاز انتشار عمومی به پایان رسید ({{used}} / {{limit}}). یک پروژه را لغو انتشار کنید یا طرح خود را ارتقا دهید.","artifacts.deploy.open": "باز کردن انتشار",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "انتشار","artifacts.deploy.publishNewVersion": "انتشار این نسخه","artifacts.deploy.quotaUnavailable": "اعتبارسنجی سهمیه انتشار به طور موقت در دسترس نیست. بعداً دوباره تلاش کنید.",+ "artifacts.deploy.serviceOverloaded": "میزبانی مصنوعات به طور موقت بیش از حد بارگذاری شده است. کمی بعد دوباره تلاش کنید.","artifacts.deploy.success": "منتشر شد","artifacts.deploy.writeInProgress": "تغییر دیگری در حال انتشار است. کمی بعد دوباره تلاش کنید.","artifacts.display.code": "کد",diff --git a/locales/fa-IR/subscription.json b/locales/fa-IR/subscription.jsonindex d39f4bb34ca..30a62b3e612 100644--- a/locales/fa-IR/subscription.json+++ b/locales/fa-IR/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "ارتقاء ناموفق","payment.upgradeSuccess.desc": "طرح اشتراک شما با موفقیت ارتقاء یافت","payment.upgradeSuccess.title": "ارتقاء موفق",+ "plans.artifactHosting.deployments": "تا {{count}} سایت فعال Artifact",+ "plans.artifactHosting.siteSize": "تا {{size}} برای هر سایت منتشر شده",+ "plans.artifactHosting.title": "میزبانی Artifact","plans.btn.contact": "تماس با ما","plans.btn.noAction": "طرح قفل شده","plans.btn.payment": "خرید",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex a042281e42c..a43b3969a6a 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Épuisé — réinitialisation {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "À ce rythme, cette fenêtre se termine autour de {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "À ce rythme, le quota sera épuisé autour de {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Capacité utilisée","heteroAgent.claudeQuota.calendar.currentWindow": "Fenêtre actuelle","heteroAgent.claudeQuota.calendar.dayShare": "Utilisé {{percent}}% de cette fenêtre","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} jetons · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Historique non enregistré","heteroAgent.claudeQuota.calendar.pace": "Rythme régulier","heteroAgent.claudeQuota.calendar.partialCost": "au moins {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Dernière fenêtre observée","heteroAgent.claudeQuota.calendar.rateLimited": "Limité par le taux","heteroAgent.claudeQuota.calendar.resetAt": "Réinitialisation de la fenêtre à {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Réessayer","input.inputCompletionError.settings": "Paramètres","input.inputCompletionError.title": "Suggestions d'entrée en pause",+ "input.modelDisabled": "Le modèle actuel est désactivé",+ "input.modelDisabled.action": "Activer",+ "input.modelDisabled.actionFailed": "Échec de l'activation du modèle. Veuillez réessayer.",+ "input.modelDisabled.selectionFailed": "Le modèle a été activé, mais le changement de fournisseur a échoué. Sélectionnez-le à nouveau pour continuer.","input.modelFixedTip": "Le modèle est fixé dans le profil de l'agent et ne peut pas être changé pendant la conversation.","input.modelUnavailable": "Le modèle actuel n'est plus disponible. Choisissez un autre modèle pour continuer.","input.more": "Plus",diff --git a/locales/fr-FR/file.json b/locales/fr-FR/file.jsonindex d5dd3bbb27b..666933254f6 100644--- a/locales/fr-FR/file.json+++ b/locales/fr-FR/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Ajouter une icône","pageEditor.autoSaveMessage": "Votre page est enregistrée automatiquement. Aucun enregistrement manuel nécessaire.","pageEditor.chooseIcon": "Choisir une icône",+ "pageEditor.comments.attachments.add": "Ajouter",+ "pageEditor.comments.attachments.chooseLibrary": "Choisir depuis la bibliothèque",+ "pageEditor.comments.author.deactivated": "Utilisateur désactivé",+ "pageEditor.comments.author.former": "Ancien membre",+ "pageEditor.comments.cancel": "Annuler",+ "pageEditor.comments.createFailed": "Échec de la publication du commentaire. Votre brouillon est toujours là.",+ "pageEditor.comments.delete": "Supprimer",+ "pageEditor.comments.deleteConfirm.content": "Supprimer ce commentaire ? Les réponses resteront visibles si ce commentaire a un fil de discussion.",+ "pageEditor.comments.deleteConfirm.title": "Supprimer le commentaire",+ "pageEditor.comments.deleteFailed": "Échec de la suppression du commentaire. Réessayez.",+ "pageEditor.comments.deleted": "Ce commentaire a été supprimé.",+ "pageEditor.comments.edit": "Modifier",+ "pageEditor.comments.edited": "(modifié)",+ "pageEditor.comments.empty": "Aucun commentaire pour le moment. Lancez la conversation ci-dessous.",+ "pageEditor.comments.hideReplies": "Masquer les réponses",+ "pageEditor.comments.loadMore": "Charger plus de commentaires",+ "pageEditor.comments.loadMoreReplies": "Charger plus de réponses",+ "pageEditor.comments.moreActions": "Plus d'actions",+ "pageEditor.comments.placeholder": "Ajouter un commentaire…",+ "pageEditor.comments.publish": "Commenter",+ "pageEditor.comments.replies_one": "{{count}} réponse",+ "pageEditor.comments.replies_other": "{{count}} réponses",+ "pageEditor.comments.replyAction": "Répondre",+ "pageEditor.comments.replyPlaceholder": "Écrire une réponse…",+ "pageEditor.comments.save": "Enregistrer",+ "pageEditor.comments.title": "Commentaires",+ "pageEditor.comments.updateFailed": "Échec de la mise à jour du commentaire. Réessayez.","pageEditor.deleteConfirm.content": "Cette page sera supprimée de façon définitive. Veuillez confirmer.","pageEditor.deleteConfirm.title": "Supprimer la page","pageEditor.deleteError": "Échec de la suppression de la page",diff --git a/locales/fr-FR/notification.json b/locales/fr-FR/notification.jsonindex fa2f948a832..c9d7ae7e93b 100644--- a/locales/fr-FR/notification.json+++ b/locales/fr-FR/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Votre tâche planifiée \"{{jobName}}\" a été mise en pause après {{count}} échecs consécutifs. Veuillez examiner l'erreur et la reprendre lorsque vous serez prêt.","agent_cron_job_failed_paused_title": "Tâche planifiée mise en pause","agent_cron_job_failed_title": "Échec de la tâche planifiée",+ "agent_intervention_required": "{{agent}} a besoin de votre contribution : {{summary}}",+ "agent_intervention_required_title": "{{agent}} a besoin de votre révision","agent_run_completed": "{{preview}}","agent_run_completed_title": "Tâche de l'agent terminée","agent_transfer_reassigned": "Un propriétaire de l'espace de travail a transféré votre agent \"{{agentTitle}}\" à {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Votre solde de crédits est faible — il vous reste environ {{balance}} crédits. Activez le rechargement automatique pour que votre solde se remplisse automatiquement et que votre travail ne soit jamais interrompu.","credit_balance_low_action": "Configurer le rechargement automatique","credit_balance_low_title": "Votre solde de crédits est faible",+ "document_comment_activity": "{{actorLabel}} a commenté votre document \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} a répondu à votre commentaire dans \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Nouvelle réponse à votre commentaire",+ "document_comment_activity_title": "Nouveau commentaire sur votre document",+ "document_comment_mentioned": "{{actorLabel}} vous a mentionné dans un commentaire sur \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Vous avez été mentionné dans un commentaire de document","email.footer.contactSupport": "Contacter le support","email.footer.joinDiscord": "Rejoindre Discord","email.footer.manage": "Gérer les notifications",diff --git a/locales/fr-FR/portal.json b/locales/fr-FR/portal.jsonindex 6ecd2006226..d1ac489f6fc 100644--- a/locales/fr-FR/portal.json+++ b/locales/fr-FR/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Copier l'URL","artifacts.deploy.copySuccess": "URL de déploiement copiée","artifacts.deploy.failed": "Échec du déploiement",+ "artifacts.deploy.highestPlanCapacityLimitReached": "La capacité actuelle de déploiement en libre-service a été atteinte. Gérez les projets publiés ou réduisez l'utilisation du déploiement.","artifacts.deploy.highestPlanLimitReached": "Limite de déploiement public atteinte ({{used}} / {{limit}}). Dépubliez un projet pour libérer un emplacement.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Ce site est {{actual}}, au-dessus de la limite de {{limit}} en libre-service. Réduisez ses ressources avant de le publier.","artifacts.deploy.history": "Historique des révisions","artifacts.deploy.limitReached": "Limite de déploiement public atteinte ({{used}} / {{limit}}). Dépubliez un projet ou améliorez votre plan.","artifacts.deploy.open": "Ouvrir le déploiement",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Publier","artifacts.deploy.publishNewVersion": "Publier cette version","artifacts.deploy.quotaUnavailable": "La validation du quota de déploiement est temporairement indisponible. Réessayez plus tard.",+ "artifacts.deploy.serviceOverloaded": "L'hébergement des artefacts est temporairement surchargé. Essayez de publier à nouveau sous peu.","artifacts.deploy.success": "Publié","artifacts.deploy.writeInProgress": "Une autre modification de déploiement est en cours. Réessayez sous peu.","artifacts.display.code": "Code",diff --git a/locales/fr-FR/subscription.json b/locales/fr-FR/subscription.jsonindex fade66fd263..7691528d7be 100644--- a/locales/fr-FR/subscription.json+++ b/locales/fr-FR/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Échec de la mise à niveau","payment.upgradeSuccess.desc": "Votre abonnement a été mis à niveau avec succès","payment.upgradeSuccess.title": "Mise à niveau réussie",+ "plans.artifactHosting.deployments": "Jusqu'à {{count}} sites d'artefacts actifs",+ "plans.artifactHosting.siteSize": "Jusqu'à {{size}} par site publié",+ "plans.artifactHosting.title": "Hébergement d'Artefacts","plans.btn.contact": "Nous contacter","plans.btn.noAction": "Plan verrouillé","plans.btn.payment": "Acheter",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex d0cb9aab25c..2b793b035c9 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Esaurito — si resetta {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "A questo ritmo, questa finestra termina intorno al {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "A questo ritmo, la quota si esaurisce intorno a {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Capacità utilizzata","heteroAgent.claudeQuota.calendar.currentWindow": "Finestra corrente","heteroAgent.claudeQuota.calendar.dayShare": "Utilizzato {{percent}}% di questa finestra","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} token · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Cronologia non registrata","heteroAgent.claudeQuota.calendar.pace": "Ritmo uniforme","heteroAgent.claudeQuota.calendar.partialCost": "almeno {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Ultima finestra osservata","heteroAgent.claudeQuota.calendar.rateLimited": "Limitato dalla velocità","heteroAgent.claudeQuota.calendar.resetAt": "La finestra si resetta a {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Riprova","input.inputCompletionError.settings": "Impostazioni","input.inputCompletionError.title": "Suggerimenti di input sospesi",+ "input.modelDisabled": "Il modello corrente è disabilitato",+ "input.modelDisabled.action": "Abilita",+ "input.modelDisabled.actionFailed": "Impossibile abilitare il modello. Riprova.",+ "input.modelDisabled.selectionFailed": "Il modello è stato abilitato, ma il cambio di provider non è riuscito. Selezionalo di nuovo per continuare.","input.modelFixedTip": "Il modello è fisso nel Profilo Agente e non può essere cambiato durante la chat.","input.modelUnavailable": "Il modello attuale non è più disponibile. Scegli un altro modello per continuare.","input.more": "Altro",diff --git a/locales/it-IT/file.json b/locales/it-IT/file.jsonindex 587e3c17097..96c7f224fa6 100644--- a/locales/it-IT/file.json+++ b/locales/it-IT/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Aggiungi icona","pageEditor.autoSaveMessage": "La tua pagina viene salvata automaticamente. Non è necessario salvare manualmente.","pageEditor.chooseIcon": "Scegli icona",+ "pageEditor.comments.attachments.add": "Aggiungi",+ "pageEditor.comments.attachments.chooseLibrary": "Scegli dalla libreria",+ "pageEditor.comments.author.deactivated": "Utente disattivato",+ "pageEditor.comments.author.former": "Ex membro",+ "pageEditor.comments.cancel": "Annulla",+ "pageEditor.comments.createFailed": "Impossibile pubblicare il commento. La tua bozza è ancora qui.",+ "pageEditor.comments.delete": "Elimina",+ "pageEditor.comments.deleteConfirm.content": "Eliminare questo commento? Le risposte rimarranno visibili se questo commento ha un thread.",+ "pageEditor.comments.deleteConfirm.title": "Elimina commento",+ "pageEditor.comments.deleteFailed": "Impossibile eliminare il commento. Riprova.",+ "pageEditor.comments.deleted": "Questo commento è stato eliminato.",+ "pageEditor.comments.edit": "Modifica",+ "pageEditor.comments.edited": "(modificato)",+ "pageEditor.comments.empty": "Ancora nessun commento. Inizia la conversazione qui sotto.",+ "pageEditor.comments.hideReplies": "Nascondi risposte",+ "pageEditor.comments.loadMore": "Carica più commenti",+ "pageEditor.comments.loadMoreReplies": "Carica più risposte",+ "pageEditor.comments.moreActions": "Altre azioni",+ "pageEditor.comments.placeholder": "Aggiungi un commento…",+ "pageEditor.comments.publish": "Commenta",+ "pageEditor.comments.replies_one": "{{count}} risposta",+ "pageEditor.comments.replies_other": "{{count}} risposte",+ "pageEditor.comments.replyAction": "Rispondi",+ "pageEditor.comments.replyPlaceholder": "Scrivi una risposta…",+ "pageEditor.comments.save": "Salva",+ "pageEditor.comments.title": "Commenti",+ "pageEditor.comments.updateFailed": "Impossibile aggiornare il commento. Riprova.","pageEditor.deleteConfirm.content": "Questa pagina verrà eliminata e non potrà essere recuperata. Procedi con cautela.","pageEditor.deleteConfirm.title": "Elimina pagina","pageEditor.deleteError": "Eliminazione della pagina non riuscita",diff --git a/locales/it-IT/notification.json b/locales/it-IT/notification.jsonindex e5150b46242..84630a52269 100644--- a/locales/it-IT/notification.json+++ b/locales/it-IT/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Il tuo compito programmato \"{{jobName}}\" è stato messo in pausa dopo {{count}} fallimenti consecutivi. Esamina l'errore e riprendi quando sei pronto.","agent_cron_job_failed_paused_title": "Compito programmato in pausa","agent_cron_job_failed_title": "Attività programmata non riuscita",+ "agent_intervention_required": "{{agent}} ha bisogno del tuo input: {{summary}}",+ "agent_intervention_required_title": "{{agent}} ha bisogno della tua revisione","agent_run_completed": "{{preview}}","agent_run_completed_title": "Attività dell'agente completata","agent_transfer_reassigned": "Un proprietario dello spazio di lavoro ha trasferito il tuo agente \"{{agentTitle}}\" a {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Il tuo saldo crediti sta per esaurirsi — circa {{balance}} crediti rimanenti. Attiva il ricaricamento automatico così il tuo saldo si ricarica automaticamente e il tuo lavoro non viene mai interrotto.","credit_balance_low_action": "Configura il ricaricamento automatico","credit_balance_low_title": "Il tuo saldo crediti sta per esaurirsi",+ "document_comment_activity": "{{actorLabel}} ha commentato il tuo documento \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} ha risposto al tuo commento in \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Nuova risposta al tuo commento",+ "document_comment_activity_title": "Nuovo commento sul tuo documento",+ "document_comment_mentioned": "{{actorLabel}} ti ha menzionato in un commento su \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Sei stato menzionato in un commento sul documento","email.footer.contactSupport": "Contatta il supporto","email.footer.joinDiscord": "Unisciti a Discord","email.footer.manage": "Gestisci notifiche",diff --git a/locales/it-IT/portal.json b/locales/it-IT/portal.jsonindex ec1a449f173..bd515678083 100644--- a/locales/it-IT/portal.json+++ b/locales/it-IT/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Copia URL","artifacts.deploy.copySuccess": "URL di distribuzione copiato","artifacts.deploy.failed": "Distribuzione fallita",+ "artifacts.deploy.highestPlanCapacityLimitReached": "La capacità di distribuzione self-service attuale è stata raggiunta. Gestisci i progetti pubblicati o riduci l'utilizzo della distribuzione.","artifacts.deploy.highestPlanLimitReached": "Limite di distribuzione pubblica raggiunto ({{used}} / {{limit}}). Annulla la pubblicazione di un progetto per liberare uno slot.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Questo sito è {{actual}}, sopra il limite self-service di {{limit}}. Riduci le sue risorse prima di pubblicarlo.","artifacts.deploy.history": "Cronologia delle revisioni","artifacts.deploy.limitReached": "Limite di distribuzione pubblica raggiunto ({{used}} / {{limit}}). Annulla la pubblicazione di un progetto o aggiorna il tuo piano.","artifacts.deploy.open": "Apri distribuzione",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Pubblica","artifacts.deploy.publishNewVersion": "Pubblica questa versione","artifacts.deploy.quotaUnavailable": "La validazione della quota di distribuzione è temporaneamente non disponibile. Riprova più tardi.",+ "artifacts.deploy.serviceOverloaded": "L'hosting degli artefatti è temporaneamente sovraccarico. Riprova a pubblicare tra poco.","artifacts.deploy.success": "Pubblicato","artifacts.deploy.writeInProgress": "Un'altra modifica di distribuzione è in corso. Riprova tra poco.","artifacts.display.code": "Codice",diff --git a/locales/it-IT/subscription.json b/locales/it-IT/subscription.jsonindex e37af376181..a78161333d8 100644--- a/locales/it-IT/subscription.json+++ b/locales/it-IT/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Aggiornamento fallito","payment.upgradeSuccess.desc": "Il tuo piano di abbonamento è stato aggiornato con successo","payment.upgradeSuccess.title": "Aggiornamento riuscito",+ "plans.artifactHosting.deployments": "Fino a {{count}} siti Artifact attivi",+ "plans.artifactHosting.siteSize": "Fino a {{size}} per sito pubblicato",+ "plans.artifactHosting.title": "Hosting Artifact","plans.btn.contact": "Contattaci","plans.btn.noAction": "Piano bloccato","plans.btn.payment": "Acquista",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex 7b0bee7f316..31ed5420790 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "消耗済み — リセット {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "現在のペースではこのウィンドウは約{{percent}}%で終了します","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "現在のペースでは、クォータは約{{time}}で尽きます",- "heteroAgent.claudeQuota.calendar.capacityUsed": "使用済み容量","heteroAgent.claudeQuota.calendar.currentWindow": "現在のウィンドウ","heteroAgent.claudeQuota.calendar.dayShare": "このウィンドウの{{percent}}%を使用","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} トークン · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "履歴未記録","heteroAgent.claudeQuota.calendar.pace": "均等ペース","heteroAgent.claudeQuota.calendar.partialCost": "少なくとも{{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "最後に観測されたウィンドウ","heteroAgent.claudeQuota.calendar.rateLimited": "レート制限","heteroAgent.claudeQuota.calendar.resetAt": "ウィンドウは{{time}}にリセットされます",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "再試行","input.inputCompletionError.settings": "設定","input.inputCompletionError.title": "入力候補が一時停止しました",+ "input.modelDisabled": "現在のモデルは無効になっています",+ "input.modelDisabled.action": "有効化",+ "input.modelDisabled.actionFailed": "モデルの有効化に失敗しました。もう一度お試しください。",+ "input.modelDisabled.selectionFailed": "モデルは有効化されましたが、プロバイダーの切り替えに失敗しました。続行するには再度選択してください。","input.modelFixedTip": "モデルはエージェントプロファイルで固定されており、チャット中に切り替えることはできません。","input.modelUnavailable": "現在のモデルは利用できなくなりました。続行するには別のモデルを選択してください。","input.more": "もっと見る",diff --git a/locales/ja-JP/file.json b/locales/ja-JP/file.jsonindex 2f550b1b9cc..eda585b96bd 100644--- a/locales/ja-JP/file.json+++ b/locales/ja-JP/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "アイコンを追加","pageEditor.autoSaveMessage": "ドキュメントは自動的に保存されます。手動で保存する必要はありません。","pageEditor.chooseIcon": "アイコンを選択",+ "pageEditor.comments.attachments.add": "追加",+ "pageEditor.comments.attachments.chooseLibrary": "ライブラリから選択",+ "pageEditor.comments.author.deactivated": "無効化されたユーザー",+ "pageEditor.comments.author.former": "元メンバー",+ "pageEditor.comments.cancel": "キャンセル",+ "pageEditor.comments.createFailed": "コメントの投稿に失敗しました。下書きはそのまま残っています。",+ "pageEditor.comments.delete": "削除",+ "pageEditor.comments.deleteConfirm.content": "このコメントを削除しますか?スレッドがある場合、返信は表示されたままになります。",+ "pageEditor.comments.deleteConfirm.title": "コメントを削除",+ "pageEditor.comments.deleteFailed": "コメントの削除に失敗しました。再試行してください。",+ "pageEditor.comments.deleted": "このコメントは削除されました。",+ "pageEditor.comments.edit": "編集",+ "pageEditor.comments.edited": "(編集済み)",+ "pageEditor.comments.empty": "まだコメントがありません。以下に会話を始めてください。",+ "pageEditor.comments.hideReplies": "返信を非表示",+ "pageEditor.comments.loadMore": "さらにコメントを読み込む",+ "pageEditor.comments.loadMoreReplies": "さらに返信を読み込む",+ "pageEditor.comments.moreActions": "その他の操作",+ "pageEditor.comments.placeholder": "コメントを追加…",+ "pageEditor.comments.publish": "コメントする",+ "pageEditor.comments.replies_one": "{{count}} 件の返信",+ "pageEditor.comments.replies_other": "{{count}} 件の返信",+ "pageEditor.comments.replyAction": "返信",+ "pageEditor.comments.replyPlaceholder": "返信を書く…",+ "pageEditor.comments.save": "保存",+ "pageEditor.comments.title": "コメント",+ "pageEditor.comments.updateFailed": "コメントの更新に失敗しました。再試行してください。","pageEditor.deleteConfirm.content": "このドキュメントを削除しようとしています。削除後は元に戻せませんので、慎重に操作してください。","pageEditor.deleteConfirm.title": "ドキュメントの削除","pageEditor.deleteError": "ドキュメントの削除に失敗しました",diff --git a/locales/ja-JP/notification.json b/locales/ja-JP/notification.jsonindex 0da08a1153e..42bc6cd4d13 100644--- a/locales/ja-JP/notification.json+++ b/locales/ja-JP/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "スケジュールされたタスク「{{jobName}}」は{{count}}回連続で失敗した後、一時停止されました。エラーを確認し、準備が整ったら再開してください。","agent_cron_job_failed_paused_title": "スケジュールされたタスクが一時停止されました","agent_cron_job_failed_title": "スケジュールされたタスクが失敗しました",+ "agent_intervention_required": "{{agent}}があなたの入力を必要としています: {{summary}}",+ "agent_intervention_required_title": "{{agent}}があなたの確認を必要としています","agent_run_completed": "{{preview}}","agent_run_completed_title": "エージェントのタスクが完了しました","agent_transfer_reassigned": "ワークスペースの所有者があなたのエージェント「{{agentTitle}}」を{{recipientLabel}}に移管しました。",@@ -32,6 +34,12 @@"credit_balance_low": "クレジット残高が少なくなっています — 残り約{{balance}}クレジットです。自動チャージをオンにして、残高を自動的に補充し、作業が中断されないようにしましょう。","credit_balance_low_action": "自動チャージを設定する","credit_balance_low_title": "クレジット残高が少なくなっています",+ "document_comment_activity": "{{actorLabel}}があなたのドキュメント「{{documentTitle}}」にコメントしました。",+ "document_comment_activity_replied": "{{actorLabel}}が「{{documentTitle}}」内のあなたのコメントに返信しました。",+ "document_comment_activity_replied_title": "あなたのコメントへの新しい返信",+ "document_comment_activity_title": "あなたのドキュメントへの新しいコメント",+ "document_comment_mentioned": "{{actorLabel}}が「{{documentTitle}}」のコメントであなたに言及しました。",+ "document_comment_mentioned_title": "ドキュメントのコメントで言及されました","email.footer.contactSupport": "サポートに連絡する","email.footer.joinDiscord": "Discordに参加する","email.footer.manage": "通知を管理する",diff --git a/locales/ja-JP/portal.json b/locales/ja-JP/portal.jsonindex 67839c9ab84..d940178d4ee 100644--- a/locales/ja-JP/portal.json+++ b/locales/ja-JP/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "URLをコピー","artifacts.deploy.copySuccess": "デプロイメントURLをコピーしました","artifacts.deploy.failed": "デプロイメントに失敗しました",+ "artifacts.deploy.highestPlanCapacityLimitReached": "現在のセルフサービス展開容量の上限に達しました。公開済みプロジェクトを管理するか、展開の使用量を減らしてください。","artifacts.deploy.highestPlanLimitReached": "公開デプロイの上限に達しました({{used}} / {{limit}})。プロジェクトを非公開にしてスロットを空けてください。",+ "artifacts.deploy.highestPlanSizeLimitReached": "このサイトは{{actual}}で、セルフサービスの制限である{{limit}}を超えています。公開する前にアセットを減らしてください。","artifacts.deploy.history": "リビジョン履歴","artifacts.deploy.limitReached": "公開デプロイの上限に達しました({{used}} / {{limit}})。プロジェクトを非公開にするか、プランをアップグレードしてください。","artifacts.deploy.open": "デプロイメントを開く",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "公開","artifacts.deploy.publishNewVersion": "このバージョンを公開","artifacts.deploy.quotaUnavailable": "デプロイのクォータ検証が一時的に利用できません。後でもう一度お試しください。",+ "artifacts.deploy.serviceOverloaded": "アーティファクトホスティングが一時的に過負荷状態です。少し時間を置いて再度公開を試みてください。","artifacts.deploy.success": "公開しました","artifacts.deploy.writeInProgress": "別のデプロイ変更が進行中です。少し待ってから再試行してください。","artifacts.display.code": "コード",diff --git a/locales/ja-JP/subscription.json b/locales/ja-JP/subscription.jsonindex b8215365365..bae2450e297 100644--- a/locales/ja-JP/subscription.json+++ b/locales/ja-JP/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "アップグレード失敗","payment.upgradeSuccess.desc": "サブスクリプションプランが正常にアップグレードされました","payment.upgradeSuccess.title": "アップグレード成功",+ "plans.artifactHosting.deployments": "最大 {{count}} 個のアクティブなアーティファクトサイト",+ "plans.artifactHosting.siteSize": "公開されたサイトごとに最大 {{size}}",+ "plans.artifactHosting.title": "アーティファクトホスティング","plans.btn.contact": "お問い合わせ","plans.btn.noAction": "プランロック中","plans.btn.payment": "購入する",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 7cce81b42f8..c980fc9fb80 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "소진됨 — {{time}}에 재설정","heteroAgent.claudeQuota.calendar.burnout.safe": "현재 속도로 이 창은 약 {{percent}}%에서 종료됩니다","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "현재 속도로 할당량이 {{time}}에 소진됩니다",- "heteroAgent.claudeQuota.calendar.capacityUsed": "사용된 용량","heteroAgent.claudeQuota.calendar.currentWindow": "현재 창","heteroAgent.claudeQuota.calendar.dayShare": "이 창의 {{percent}}% 사용됨","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} 토큰 · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "기록되지 않은 기록","heteroAgent.claudeQuota.calendar.pace": "균등한 속도","heteroAgent.claudeQuota.calendar.partialCost": "최소 {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "마지막 관찰된 창","heteroAgent.claudeQuota.calendar.rateLimited": "속도 제한됨","heteroAgent.claudeQuota.calendar.resetAt": "창이 {{time}}에 재설정됩니다",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "재시도","input.inputCompletionError.settings": "설정","input.inputCompletionError.title": "입력 제안 일시 중지됨",+ "input.modelDisabled": "현재 모델이 비활성화되었습니다",+ "input.modelDisabled.action": "활성화",+ "input.modelDisabled.actionFailed": "모델을 활성화하지 못했습니다. 다시 시도해 주세요.",+ "input.modelDisabled.selectionFailed": "모델이 활성화되었지만 공급자 전환에 실패했습니다. 계속하려면 다시 선택하세요.","input.modelFixedTip": "모델은 에이전트 프로필에서 고정되어 있으며 채팅 중에는 변경할 수 없습니다.","input.modelUnavailable": "현재 모델은 더 이상 사용할 수 없습니다. 계속하려면 다른 모델을 선택하세요.","input.more": "더 보기",diff --git a/locales/ko-KR/file.json b/locales/ko-KR/file.jsonindex 15a688f769f..16ff8863f62 100644--- a/locales/ko-KR/file.json+++ b/locales/ko-KR/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "아이콘 추가","pageEditor.autoSaveMessage": "문서는 자동으로 저장되며, 수동 저장이 필요하지 않습니다","pageEditor.chooseIcon": "아이콘 선택",+ "pageEditor.comments.attachments.add": "추가",+ "pageEditor.comments.attachments.chooseLibrary": "라이브러리에서 선택",+ "pageEditor.comments.author.deactivated": "비활성화된 사용자",+ "pageEditor.comments.author.former": "이전 멤버",+ "pageEditor.comments.cancel": "취소",+ "pageEditor.comments.createFailed": "댓글 게시에 실패했습니다. 작성 중인 초안은 여전히 남아 있습니다.",+ "pageEditor.comments.delete": "삭제",+ "pageEditor.comments.deleteConfirm.content": "이 댓글을 삭제하시겠습니까? 댓글에 스레드가 있는 경우 답글은 계속 표시됩니다.",+ "pageEditor.comments.deleteConfirm.title": "댓글 삭제",+ "pageEditor.comments.deleteFailed": "댓글 삭제에 실패했습니다. 다시 시도하세요.",+ "pageEditor.comments.deleted": "이 댓글은 삭제되었습니다.",+ "pageEditor.comments.edit": "편집",+ "pageEditor.comments.edited": "(편집됨)",+ "pageEditor.comments.empty": "아직 댓글이 없습니다. 아래에서 대화를 시작하세요.",+ "pageEditor.comments.hideReplies": "답글 숨기기",+ "pageEditor.comments.loadMore": "댓글 더 보기",+ "pageEditor.comments.loadMoreReplies": "답글 더 보기",+ "pageEditor.comments.moreActions": "더 많은 작업",+ "pageEditor.comments.placeholder": "댓글 추가…",+ "pageEditor.comments.publish": "댓글 작성",+ "pageEditor.comments.replies_one": "{{count}}개의 답글",+ "pageEditor.comments.replies_other": "{{count}}개의 답글",+ "pageEditor.comments.replyAction": "답글",+ "pageEditor.comments.replyPlaceholder": "답글 작성…",+ "pageEditor.comments.save": "저장",+ "pageEditor.comments.title": "댓글",+ "pageEditor.comments.updateFailed": "댓글 업데이트에 실패했습니다. 다시 시도하세요.","pageEditor.deleteConfirm.content": "이 문서를 삭제하려고 합니다. 삭제 후에는 복구할 수 없으니 신중히 진행해 주세요.","pageEditor.deleteConfirm.title": "문서 삭제","pageEditor.deleteError": "문서 삭제에 실패했습니다",diff --git a/locales/ko-KR/notification.json b/locales/ko-KR/notification.jsonindex ee21b7cafea..33d9f32dd78 100644--- a/locales/ko-KR/notification.json+++ b/locales/ko-KR/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "예약된 작업 \"{{jobName}}\"이(가) {{count}}번 연속 실패한 후 일시 중지되었습니다. 오류를 검토하고 준비가 되면 다시 시작하세요.","agent_cron_job_failed_paused_title": "예약된 작업 일시 중지","agent_cron_job_failed_title": "예약된 작업 실패",+ "agent_intervention_required": "{{agent}}님이 귀하의 입력이 필요합니다: {{summary}}",+ "agent_intervention_required_title": "{{agent}}님이 귀하의 검토가 필요합니다","agent_run_completed": "{{preview}}","agent_run_completed_title": "에이전트 작업 완료","agent_transfer_reassigned": "워크스페이스 소유자가 에이전트 \"{{agentTitle}}\"을(를) {{recipientLabel}}에게 이전했습니다.",@@ -32,6 +34,12 @@"credit_balance_low": "귀하의 크레딧 잔액이 부족합니다 — 약 {{balance}} 크레딧이 남아 있습니다. 자동 충전을 활성화하여 잔액이 자동으로 충전되고 작업이 중단되지 않도록 하세요.","credit_balance_low_action": "자동 충전 설정","credit_balance_low_title": "크레딧 잔액이 부족합니다",+ "document_comment_activity": "{{actorLabel}}님이 귀하의 문서 \"{{documentTitle}}\"에 댓글을 남겼습니다.",+ "document_comment_activity_replied": "{{actorLabel}}님이 \"{{documentTitle}}\"에서 귀하의 댓글에 답글을 남겼습니다.",+ "document_comment_activity_replied_title": "귀하의 댓글에 대한 새 답글",+ "document_comment_activity_title": "귀하의 문서에 대한 새 댓글",+ "document_comment_mentioned": "{{actorLabel}}님이 \"{{documentTitle}}\"의 댓글에서 귀하를 언급했습니다.",+ "document_comment_mentioned_title": "문서 댓글에서 귀하가 언급되었습니다","email.footer.contactSupport": "지원팀에 문의하기","email.footer.joinDiscord": "디스코드에 참여하기","email.footer.manage": "알림 관리",diff --git a/locales/ko-KR/portal.json b/locales/ko-KR/portal.jsonindex 28e8f0237c4..bb88599d4f2 100644--- a/locales/ko-KR/portal.json+++ b/locales/ko-KR/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "URL 복사","artifacts.deploy.copySuccess": "배포 URL이 복사되었습니다","artifacts.deploy.failed": "배포 실패",+ "artifacts.deploy.highestPlanCapacityLimitReached": "현재 셀프 서비스 배포 용량이 초과되었습니다. 게시된 프로젝트를 관리하거나 배포 사용량을 줄이십시오.","artifacts.deploy.highestPlanLimitReached": "공개 배포 한도에 도달했습니다 ({{used}} / {{limit}}). 프로젝트를 비공개로 전환하여 슬롯을 확보하세요.",+ "artifacts.deploy.highestPlanSizeLimitReached": "이 사이트는 {{actual}}로, {{limit}} 셀프 서비스 제한을 초과했습니다. 게시하기 전에 자산을 줄이십시오.","artifacts.deploy.history": "수정 내역","artifacts.deploy.limitReached": "공개 배포 한도에 도달했습니다 ({{used}} / {{limit}}). 프로젝트를 비공개로 전환하거나 플랜을 업그레이드하세요.","artifacts.deploy.open": "배포 열기",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "게시","artifacts.deploy.publishNewVersion": "이 버전 게시","artifacts.deploy.quotaUnavailable": "배포 할당량 검증이 일시적으로 사용할 수 없습니다. 나중에 다시 시도하세요.",+ "artifacts.deploy.serviceOverloaded": "아티팩트 호스팅이 일시적으로 과부하 상태입니다. 잠시 후 다시 게시를 시도하십시오.","artifacts.deploy.success": "게시 완료","artifacts.deploy.writeInProgress": "다른 배포 변경 작업이 진행 중입니다. 잠시 후 다시 시도하세요.","artifacts.display.code": "코드",diff --git a/locales/ko-KR/subscription.json b/locales/ko-KR/subscription.jsonindex 556d966447d..39e700de47c 100644--- a/locales/ko-KR/subscription.json+++ b/locales/ko-KR/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "업그레이드 실패","payment.upgradeSuccess.desc": "구독 플랜이 성공적으로 업그레이드되었습니다.","payment.upgradeSuccess.title": "업그레이드 완료",+ "plans.artifactHosting.deployments": "최대 {{count}}개의 활성 아티팩트 사이트",+ "plans.artifactHosting.siteSize": "게시된 사이트당 최대 {{size}}",+ "plans.artifactHosting.title": "아티팩트 호스팅","plans.btn.contact": "문의하기","plans.btn.noAction": "플랜 잠김","plans.btn.payment": "구매하기",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 051fe5a234e..693ce892438 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Uitgeput — reset {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "Op het huidige tempo eindigt dit venster rond {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "Op het huidige tempo raakt het quotum op rond {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Capaciteit gebruikt","heteroAgent.claudeQuota.calendar.currentWindow": "Huidig venster","heteroAgent.claudeQuota.calendar.dayShare": "Gebruikt {{percent}}% van dit venster","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} tokens · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Geschiedenis niet geregistreerd","heteroAgent.claudeQuota.calendar.pace": "Gelijkmatig tempo","heteroAgent.claudeQuota.calendar.partialCost": "minimaal {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Laatst waargenomen venster","heteroAgent.claudeQuota.calendar.rateLimited": "Snelheidslimiet bereikt","heteroAgent.claudeQuota.calendar.resetAt": "Venster reset om {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Opnieuw proberen","input.inputCompletionError.settings": "Instellingen","input.inputCompletionError.title": "Invoersuggesties gepauzeerd",+ "input.modelDisabled": "Het huidige model is uitgeschakeld",+ "input.modelDisabled.action": "Inschakelen",+ "input.modelDisabled.actionFailed": "Het inschakelen van het model is mislukt. Probeer het opnieuw.",+ "input.modelDisabled.selectionFailed": "Het model is ingeschakeld, maar het wisselen van providers is mislukt. Selecteer het opnieuw om verder te gaan.","input.modelFixedTip": "Het model is vastgelegd in het agentprofiel en kan niet worden gewijzigd tijdens het chatten.","input.modelUnavailable": "Het huidige model is niet langer beschikbaar. Kies een ander model om door te gaan.","input.more": "Meer",diff --git a/locales/nl-NL/file.json b/locales/nl-NL/file.jsonindex 0fd1a12adf4..a7a9d874a98 100644--- a/locales/nl-NL/file.json+++ b/locales/nl-NL/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Icoon toevoegen","pageEditor.autoSaveMessage": "Je pagina wordt automatisch opgeslagen. Handmatig opslaan is niet nodig.","pageEditor.chooseIcon": "Icoon kiezen",+ "pageEditor.comments.attachments.add": "Toevoegen",+ "pageEditor.comments.attachments.chooseLibrary": "Kies uit bibliotheek",+ "pageEditor.comments.author.deactivated": "Gedeactiveerde gebruiker",+ "pageEditor.comments.author.former": "Voormalig lid",+ "pageEditor.comments.cancel": "Annuleren",+ "pageEditor.comments.createFailed": "Reactie plaatsen mislukt. Je concept is nog steeds hier.",+ "pageEditor.comments.delete": "Verwijderen",+ "pageEditor.comments.deleteConfirm.content": "Deze reactie verwijderen? Antwoorden blijven zichtbaar als deze reactie een thread heeft.",+ "pageEditor.comments.deleteConfirm.title": "Reactie verwijderen",+ "pageEditor.comments.deleteFailed": "Reactie verwijderen mislukt. Probeer opnieuw.",+ "pageEditor.comments.deleted": "Deze reactie is verwijderd.",+ "pageEditor.comments.edit": "Bewerken",+ "pageEditor.comments.edited": "(bewerkt)",+ "pageEditor.comments.empty": "Nog geen reacties. Begin hieronder met het gesprek.",+ "pageEditor.comments.hideReplies": "Antwoorden verbergen",+ "pageEditor.comments.loadMore": "Meer reacties laden",+ "pageEditor.comments.loadMoreReplies": "Meer antwoorden laden",+ "pageEditor.comments.moreActions": "Meer acties",+ "pageEditor.comments.placeholder": "Voeg een reactie toe…",+ "pageEditor.comments.publish": "Reageren",+ "pageEditor.comments.replies_one": "{{count}} antwoord",+ "pageEditor.comments.replies_other": "{{count}} antwoorden",+ "pageEditor.comments.replyAction": "Antwoorden",+ "pageEditor.comments.replyPlaceholder": "Schrijf een antwoord…",+ "pageEditor.comments.save": "Opslaan",+ "pageEditor.comments.title": "Reacties",+ "pageEditor.comments.updateFailed": "Reactie bijwerken mislukt. Probeer opnieuw.","pageEditor.deleteConfirm.content": "Deze pagina wordt verwijderd en kan niet worden hersteld. Wees voorzichtig.","pageEditor.deleteConfirm.title": "Pagina verwijderen","pageEditor.deleteError": "Verwijderen van pagina mislukt",diff --git a/locales/nl-NL/notification.json b/locales/nl-NL/notification.jsonindex a5a982d3d65..ba38bfbcabe 100644--- a/locales/nl-NL/notification.json+++ b/locales/nl-NL/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Uw geplande taak \"{{jobName}}\" is gepauzeerd na {{count}} opeenvolgende fouten. Controleer de fout en hervat de taak wanneer u er klaar voor bent.","agent_cron_job_failed_paused_title": "Geplande taak gepauzeerd","agent_cron_job_failed_title": "Geplande taak mislukt",+ "agent_intervention_required": "{{agent}} heeft uw input nodig: {{summary}}",+ "agent_intervention_required_title": "{{agent}} heeft uw beoordeling nodig","agent_run_completed": "{{preview}}","agent_run_completed_title": "Agenttaak voltooid","agent_transfer_reassigned": "Een werkruimte-eigenaar heeft jouw agent \"{{agentTitle}}\" overgedragen aan {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Uw kredietsaldo raakt bijna op — ongeveer {{balance}} aan resterende credits. Schakel automatisch opwaarderen in zodat uw saldo automatisch wordt aangevuld en uw werk nooit wordt onderbroken.","credit_balance_low_action": "Automatisch opwaarderen instellen","credit_balance_low_title": "Uw kredietsaldo raakt bijna op",+ "document_comment_activity": "{{actorLabel}} heeft een opmerking gemaakt over uw document \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} heeft gereageerd op uw opmerking in \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Nieuwe reactie op uw opmerking",+ "document_comment_activity_title": "Nieuwe opmerking over uw document",+ "document_comment_mentioned": "{{actorLabel}} heeft u genoemd in een opmerking over \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "U bent genoemd in een documentopmerking","email.footer.contactSupport": "Neem contact op met ondersteuning","email.footer.joinDiscord": "Word lid van Discord","email.footer.manage": "Beheer meldingen",diff --git a/locales/nl-NL/portal.json b/locales/nl-NL/portal.jsonindex 761576bb255..16bbbfb5d16 100644--- a/locales/nl-NL/portal.json+++ b/locales/nl-NL/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "URL kopiëren","artifacts.deploy.copySuccess": "URL van de deployment gekopieerd","artifacts.deploy.failed": "Deployment mislukt",+ "artifacts.deploy.highestPlanCapacityLimitReached": "De huidige capaciteit voor zelfservice-implementatie is bereikt. Beheer gepubliceerde projecten of verminder het gebruik van implementatie.","artifacts.deploy.highestPlanLimitReached": "Limiet voor openbare implementaties bereikt ({{used}} / {{limit}}). Maak een project ongedaan om een slot vrij te maken.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Deze site is {{actual}}, boven de zelfservicelimiet van {{limit}}. Verminder de assets voordat u publiceert.","artifacts.deploy.history": "Revisiegeschiedenis","artifacts.deploy.limitReached": "Limiet voor openbare implementaties bereikt ({{used}} / {{limit}}). Maak een project ongedaan of upgrade uw abonnement.","artifacts.deploy.open": "Deployment openen",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Publiceren","artifacts.deploy.publishNewVersion": "Deze versie publiceren","artifacts.deploy.quotaUnavailable": "Validatie van implementatiequota is tijdelijk niet beschikbaar. Probeer het later opnieuw.",+ "artifacts.deploy.serviceOverloaded": "De hosting van artefacten is tijdelijk overbelast. Probeer het publiceren binnenkort opnieuw.","artifacts.deploy.success": "Gepubliceerd","artifacts.deploy.writeInProgress": "Er wordt momenteel een andere implementatiewijziging uitgevoerd. Probeer het binnenkort opnieuw.","artifacts.display.code": "Code",diff --git a/locales/nl-NL/subscription.json b/locales/nl-NL/subscription.jsonindex babd894cdbe..731f39fa884 100644--- a/locales/nl-NL/subscription.json+++ b/locales/nl-NL/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Upgrade Mislukt","payment.upgradeSuccess.desc": "Je abonnement is succesvol geüpgraded","payment.upgradeSuccess.title": "Upgrade Geslaagd",+ "plans.artifactHosting.deployments": "Tot {{count}} actieve Artifact-sites",+ "plans.artifactHosting.siteSize": "Tot {{size}} per gepubliceerde site",+ "plans.artifactHosting.title": "Artifact Hosting","plans.btn.contact": "Neem Contact Op","plans.btn.noAction": "Plan Vergrendeld","plans.btn.payment": "Aanschaffen",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 7ed3b932dab..5288a33a390 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Wyczerpane — resetuje się {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "Przy obecnym tempie to okno kończy się około {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "Przy obecnym tempie kwota wyczerpie się około {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Wykorzystana pojemność","heteroAgent.claudeQuota.calendar.currentWindow": "Obecne okno","heteroAgent.claudeQuota.calendar.dayShare": "Wykorzystano {{percent}}% tego okna","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} tokenów · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Historia nie została zarejestrowana","heteroAgent.claudeQuota.calendar.pace": "Równomierne tempo","heteroAgent.claudeQuota.calendar.partialCost": "co najmniej {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Ostatnie obserwowane okno","heteroAgent.claudeQuota.calendar.rateLimited": "Ograniczone tempo","heteroAgent.claudeQuota.calendar.resetAt": "Okno resetuje się o {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Spróbuj ponownie","input.inputCompletionError.settings": "Ustawienia","input.inputCompletionError.title": "Sugestie dla wpisu wstrzymane",+ "input.modelDisabled": "Obecny model jest wyłączony",+ "input.modelDisabled.action": "Włącz",+ "input.modelDisabled.actionFailed": "Nie udało się włączyć modelu. Spróbuj ponownie.",+ "input.modelDisabled.selectionFailed": "Model został włączony, ale przełączenie dostawców nie powiodło się. Wybierz go ponownie, aby kontynuować.","input.modelFixedTip": "Model jest ustalony w profilu agenta i nie można go zmienić podczas rozmowy.","input.modelUnavailable": "Obecny model nie jest już dostępny. Wybierz inny model, aby kontynuować.","input.more": "Więcej",diff --git a/locales/pl-PL/file.json b/locales/pl-PL/file.jsonindex 9431a6126bd..f91b1814e9c 100644--- a/locales/pl-PL/file.json+++ b/locales/pl-PL/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Dodaj ikonę","pageEditor.autoSaveMessage": "Twoja strona jest zapisywana automatycznie. Nie musisz zapisywać ręcznie.","pageEditor.chooseIcon": "Wybierz ikonę",+ "pageEditor.comments.attachments.add": "Dodaj",+ "pageEditor.comments.attachments.chooseLibrary": "Wybierz z biblioteki",+ "pageEditor.comments.author.deactivated": "Dezaktywowany użytkownik",+ "pageEditor.comments.author.former": "Były członek",+ "pageEditor.comments.cancel": "Anuluj",+ "pageEditor.comments.createFailed": "Nie udało się opublikować komentarza. Twój szkic nadal tutaj jest.",+ "pageEditor.comments.delete": "Usuń",+ "pageEditor.comments.deleteConfirm.content": "Usunąć ten komentarz? Odpowiedzi pozostaną widoczne, jeśli ten komentarz ma wątek.",+ "pageEditor.comments.deleteConfirm.title": "Usuń komentarz",+ "pageEditor.comments.deleteFailed": "Nie udało się usunąć komentarza. Spróbuj ponownie.",+ "pageEditor.comments.deleted": "Ten komentarz został usunięty.",+ "pageEditor.comments.edit": "Edytuj",+ "pageEditor.comments.edited": "(edytowano)",+ "pageEditor.comments.empty": "Brak komentarzy. Rozpocznij rozmowę poniżej.",+ "pageEditor.comments.hideReplies": "Ukryj odpowiedzi",+ "pageEditor.comments.loadMore": "Załaduj więcej komentarzy",+ "pageEditor.comments.loadMoreReplies": "Załaduj więcej odpowiedzi",+ "pageEditor.comments.moreActions": "Więcej akcji",+ "pageEditor.comments.placeholder": "Dodaj komentarz…",+ "pageEditor.comments.publish": "Skomentuj",+ "pageEditor.comments.replies_one": "{{count}} odpowiedź",+ "pageEditor.comments.replies_other": "{{count}} odpowiedzi",+ "pageEditor.comments.replyAction": "Odpowiedz",+ "pageEditor.comments.replyPlaceholder": "Napisz odpowiedź…",+ "pageEditor.comments.save": "Zapisz",+ "pageEditor.comments.title": "Komentarze",+ "pageEditor.comments.updateFailed": "Nie udało się zaktualizować komentarza. Spróbuj ponownie.","pageEditor.deleteConfirm.content": "Ta strona zostanie usunięta i nie będzie można jej odzyskać. Proszę zachować ostrożność.","pageEditor.deleteConfirm.title": "Usuń stronę","pageEditor.deleteError": "Nie udało się usunąć strony",diff --git a/locales/pl-PL/notification.json b/locales/pl-PL/notification.jsonindex 3aa7ef5c566..a57bc3361b1 100644--- a/locales/pl-PL/notification.json+++ b/locales/pl-PL/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Twoje zaplanowane zadanie \"{{jobName}}\" zostało wstrzymane po {{count}} kolejnych niepowodzeniach. Przejrzyj błąd i wznow je, gdy będziesz gotowy.","agent_cron_job_failed_paused_title": "Zaplanowane zadanie wstrzymane","agent_cron_job_failed_title": "Błąd zaplanowanego zadania",+ "agent_intervention_required": "{{agent}} potrzebuje Twojej opinii: {{summary}}",+ "agent_intervention_required_title": "{{agent}} potrzebuje Twojej recenzji","agent_run_completed": "{{preview}}","agent_run_completed_title": "Zadanie agenta zakończone","agent_transfer_reassigned": "Właściciel przestrzeni roboczej przeniósł Twojego agenta \"{{agentTitle}}\" do {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Twój stan kredytowy jest niski — pozostało około {{balance}} kredytów. Włącz automatyczne doładowanie, aby saldo uzupełniało się automatycznie i Twoja praca nie była przerywana.","credit_balance_low_action": "Ustaw automatyczne doładowanie","credit_balance_low_title": "Twój stan kredytowy jest niski",+ "document_comment_activity": "{{actorLabel}} skomentował Twój dokument \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} odpowiedział na Twój komentarz w \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Nowa odpowiedź na Twój komentarz",+ "document_comment_activity_title": "Nowy komentarz do Twojego dokumentu",+ "document_comment_mentioned": "{{actorLabel}} wspomniał Cię w komentarzu do \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Zostałeś wspomniany w komentarzu do dokumentu","email.footer.contactSupport": "Skontaktuj się z pomocą techniczną","email.footer.joinDiscord": "Dołącz do Discorda","email.footer.manage": "Zarządzaj powiadomieniami",diff --git a/locales/pl-PL/portal.json b/locales/pl-PL/portal.jsonindex fee0a2f493b..45da585d837 100644--- a/locales/pl-PL/portal.json+++ b/locales/pl-PL/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Skopiuj URL","artifacts.deploy.copySuccess": "URL wdrożenia skopiowany","artifacts.deploy.failed": "Wdrożenie nie powiodło się",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Osiągnięto maksymalną pojemność wdrożeń w ramach obecnego planu samoobsługowego. Zarządzaj opublikowanymi projektami lub zmniejsz wykorzystanie wdrożeń.","artifacts.deploy.highestPlanLimitReached": "Osiągnięto limit publicznych wdrożeń ({{used}} / {{limit}}). Cofnij publikację projektu, aby zwolnić miejsce.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Ta witryna ma rozmiar {{actual}}, co przekracza limit samoobsługowy wynoszący {{limit}}. Zmniejsz jej zasoby przed publikacją.","artifacts.deploy.history": "Historia wersji","artifacts.deploy.limitReached": "Osiągnięto limit publicznych wdrożeń ({{used}} / {{limit}}). Cofnij publikację projektu lub zaktualizuj swój plan.","artifacts.deploy.open": "Otwórz wdrożenie",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Opublikuj","artifacts.deploy.publishNewVersion": "Opublikuj tę wersję","artifacts.deploy.quotaUnavailable": "Weryfikacja limitu wdrożeń jest tymczasowo niedostępna. Spróbuj ponownie później.",+ "artifacts.deploy.serviceOverloaded": "Hosting artefaktów jest tymczasowo przeciążony. Spróbuj opublikować ponownie za chwilę.","artifacts.deploy.success": "Opublikowano","artifacts.deploy.writeInProgress": "Trwa inna zmiana wdrożenia. Spróbuj ponownie za chwilę.","artifacts.display.code": "Kod",diff --git a/locales/pl-PL/subscription.json b/locales/pl-PL/subscription.jsonindex d3930b32601..a38e26ad886 100644--- a/locales/pl-PL/subscription.json+++ b/locales/pl-PL/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Aktualizacja nieudana","payment.upgradeSuccess.desc": "Twój plan subskrypcyjny został pomyślnie zaktualizowany","payment.upgradeSuccess.title": "Aktualizacja zakończona sukcesem",+ "plans.artifactHosting.deployments": "Do {{count}} aktywnych witryn Artifact",+ "plans.artifactHosting.siteSize": "Do {{size}} na opublikowaną witrynę",+ "plans.artifactHosting.title": "Hosting Artifact","plans.btn.contact": "Skontaktuj się z nami","plans.btn.noAction": "Plan zablokowany","plans.btn.payment": "Kup",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex d8519681940..45ce8ed7cb2 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Esgotado — reinicia {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "No ritmo atual, esta janela termina em cerca de {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "No ritmo atual, a cota se esgota por volta de {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Capacidade usada","heteroAgent.claudeQuota.calendar.currentWindow": "Janela atual","heteroAgent.claudeQuota.calendar.dayShare": "Usado {{percent}}% desta janela","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} tokens · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Histórico não registrado","heteroAgent.claudeQuota.calendar.pace": "Ritmo constante","heteroAgent.claudeQuota.calendar.partialCost": "pelo menos {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Última janela observada","heteroAgent.claudeQuota.calendar.rateLimited": "Limitado por taxa","heteroAgent.claudeQuota.calendar.resetAt": "Janela reinicia em {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Tentar novamente","input.inputCompletionError.settings": "Configurações","input.inputCompletionError.title": "Sugestões de entrada pausadas",+ "input.modelDisabled": "O modelo atual está desativado",+ "input.modelDisabled.action": "Ativar",+ "input.modelDisabled.actionFailed": "Falha ao ativar o modelo. Por favor, tente novamente.",+ "input.modelDisabled.selectionFailed": "O modelo foi ativado, mas a troca de provedores falhou. Selecione-o novamente para continuar.","input.modelFixedTip": "O modelo está fixado no Perfil do Agente e não pode ser alterado durante a conversa.","input.modelUnavailable": "O modelo atual não está mais disponível. Escolha outro modelo para continuar.","input.more": "Mais",diff --git a/locales/pt-BR/file.json b/locales/pt-BR/file.jsonindex 0c8f2bb3add..dac08d76cb1 100644--- a/locales/pt-BR/file.json+++ b/locales/pt-BR/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Adicionar Ícone","pageEditor.autoSaveMessage": "Sua página é salva automaticamente. Não é necessário salvar manualmente.","pageEditor.chooseIcon": "Escolher Ícone",+ "pageEditor.comments.attachments.add": "Adicionar",+ "pageEditor.comments.attachments.chooseLibrary": "Escolher da Biblioteca",+ "pageEditor.comments.author.deactivated": "Usuário desativado",+ "pageEditor.comments.author.former": "Ex-membro",+ "pageEditor.comments.cancel": "Cancelar",+ "pageEditor.comments.createFailed": "Falha ao publicar o comentário. Seu rascunho ainda está aqui.",+ "pageEditor.comments.delete": "Excluir",+ "pageEditor.comments.deleteConfirm.content": "Excluir este comentário? As respostas permanecerão visíveis se este comentário tiver um encadeamento.",+ "pageEditor.comments.deleteConfirm.title": "Excluir comentário",+ "pageEditor.comments.deleteFailed": "Falha ao excluir o comentário. Tente novamente.",+ "pageEditor.comments.deleted": "Este comentário foi excluído.",+ "pageEditor.comments.edit": "Editar",+ "pageEditor.comments.edited": "(editado)",+ "pageEditor.comments.empty": "Ainda não há comentários. Inicie a conversa abaixo.",+ "pageEditor.comments.hideReplies": "Ocultar respostas",+ "pageEditor.comments.loadMore": "Carregar mais comentários",+ "pageEditor.comments.loadMoreReplies": "Carregar mais respostas",+ "pageEditor.comments.moreActions": "Mais ações",+ "pageEditor.comments.placeholder": "Adicione um comentário…",+ "pageEditor.comments.publish": "Comentar",+ "pageEditor.comments.replies_one": "{{count}} resposta",+ "pageEditor.comments.replies_other": "{{count}} respostas",+ "pageEditor.comments.replyAction": "Responder",+ "pageEditor.comments.replyPlaceholder": "Escreva uma resposta…",+ "pageEditor.comments.save": "Salvar",+ "pageEditor.comments.title": "Comentários",+ "pageEditor.comments.updateFailed": "Falha ao atualizar o comentário. Tente novamente.","pageEditor.deleteConfirm.content": "Esta página será excluída e não poderá ser recuperada. Prossiga com cautela.","pageEditor.deleteConfirm.title": "Excluir Página","pageEditor.deleteError": "Falha ao excluir a página",diff --git a/locales/pt-BR/notification.json b/locales/pt-BR/notification.jsonindex 81a87bd4537..4fa26f23e4d 100644--- a/locales/pt-BR/notification.json+++ b/locales/pt-BR/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Sua tarefa agendada \"{{jobName}}\" foi pausada após {{count}} falhas consecutivas. Revise o erro e retome-a quando estiver pronto.","agent_cron_job_failed_paused_title": "Tarefa agendada pausada","agent_cron_job_failed_title": "Falha na tarefa agendada",+ "agent_intervention_required": "{{agent}} precisa da sua entrada: {{summary}}",+ "agent_intervention_required_title": "{{agent}} precisa da sua revisão","agent_run_completed": "{{preview}}","agent_run_completed_title": "Tarefa do agente concluída","agent_transfer_reassigned": "Um proprietário do workspace transferiu seu agente \"{{agentTitle}}\" para {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Seu saldo de créditos está baixo — cerca de {{balance}} em créditos restantes. Ative a recarga automática para que seu saldo seja preenchido automaticamente e seu trabalho nunca seja interrompido.","credit_balance_low_action": "Configurar recarga automática","credit_balance_low_title": "Seu saldo de créditos está baixo",+ "document_comment_activity": "{{actorLabel}} comentou no seu documento \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} respondeu ao seu comentário em \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Nova resposta ao seu comentário",+ "document_comment_activity_title": "Novo comentário no seu documento",+ "document_comment_mentioned": "{{actorLabel}} mencionou você em um comentário no \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Você foi mencionado em um comentário de documento","email.footer.contactSupport": "Entrar em contato com o suporte","email.footer.joinDiscord": "Participar do Discord","email.footer.manage": "Gerenciar notificações",diff --git a/locales/pt-BR/portal.json b/locales/pt-BR/portal.jsonindex 5b2dec1b7b8..a903d68418f 100644--- a/locales/pt-BR/portal.json+++ b/locales/pt-BR/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Copiar URL","artifacts.deploy.copySuccess": "URL de implantação copiada","artifacts.deploy.failed": "Falha na implantação",+ "artifacts.deploy.highestPlanCapacityLimitReached": "A capacidade atual de implantação de autoatendimento foi atingida. Gerencie os projetos publicados ou reduza o uso de implantação.","artifacts.deploy.highestPlanLimitReached": "Limite de implantação pública atingido ({{used}} / {{limit}}). Despublique um projeto para liberar um espaço.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Este site é {{actual}}, acima do limite de autoatendimento de {{limit}}. Reduza seus ativos antes de publicar.","artifacts.deploy.history": "Histórico de revisões","artifacts.deploy.limitReached": "Limite de implantação pública atingido ({{used}} / {{limit}}). Despublique um projeto ou atualize seu plano.","artifacts.deploy.open": "Abrir implantação",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Publicar","artifacts.deploy.publishNewVersion": "Publicar esta versão","artifacts.deploy.quotaUnavailable": "A validação da cota de implantação está temporariamente indisponível. Tente novamente mais tarde.",+ "artifacts.deploy.serviceOverloaded": "O serviço de hospedagem de artefatos está temporariamente sobrecarregado. Tente publicar novamente em breve.","artifacts.deploy.success": "Publicado","artifacts.deploy.writeInProgress": "Outra alteração de implantação está em andamento. Tente novamente em breve.","artifacts.display.code": "Código",diff --git a/locales/pt-BR/subscription.json b/locales/pt-BR/subscription.jsonindex 7964f727d24..5338fd9fa7d 100644--- a/locales/pt-BR/subscription.json+++ b/locales/pt-BR/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Falha na Atualização","payment.upgradeSuccess.desc": "Seu plano de assinatura foi atualizado com sucesso","payment.upgradeSuccess.title": "Atualização Bem-sucedida",+ "plans.artifactHosting.deployments": "Até {{count}} sites de Artefato ativos",+ "plans.artifactHosting.siteSize": "Até {{size}} por site publicado",+ "plans.artifactHosting.title": "Hospedagem de Artefatos","plans.btn.contact": "Fale Conosco","plans.btn.noAction": "Plano Bloqueado","plans.btn.payment": "Comprar",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex 2588283b46c..4c4ee23dfec 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Исчерпано — сброс {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "При текущем темпе это окно завершится примерно на {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "При текущем темпе квота закончится примерно в {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Использовано емкости","heteroAgent.claudeQuota.calendar.currentWindow": "Текущее окно","heteroAgent.claudeQuota.calendar.dayShare": "Использовано {{percent}}% этого окна","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} токенов · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "История не зафиксирована","heteroAgent.claudeQuota.calendar.pace": "Равномерный темп","heteroAgent.claudeQuota.calendar.partialCost": "по крайней мере {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Последнее наблюдаемое окно","heteroAgent.claudeQuota.calendar.rateLimited": "Ограничение скорости","heteroAgent.claudeQuota.calendar.resetAt": "Сброс окна в {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Повторить","input.inputCompletionError.settings": "Настройки","input.inputCompletionError.title": "Предложения ввода приостановлены",+ "input.modelDisabled": "Текущая модель отключена",+ "input.modelDisabled.action": "Включить",+ "input.modelDisabled.actionFailed": "Не удалось включить модель. Пожалуйста, попробуйте снова.",+ "input.modelDisabled.selectionFailed": "Модель была включена, но переключение провайдеров не удалось. Выберите её снова, чтобы продолжить.","input.modelFixedTip": "Модель закреплена в профиле агента и не может быть изменена во время общения.","input.modelUnavailable": "Текущая модель больше недоступна. Выберите другую модель, чтобы продолжить.","input.more": "Ещё",diff --git a/locales/ru-RU/file.json b/locales/ru-RU/file.jsonindex 3ae0937b05a..f52d6e31aae 100644--- a/locales/ru-RU/file.json+++ b/locales/ru-RU/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Добавить иконку","pageEditor.autoSaveMessage": "Страница сохраняется автоматически. Сохранять вручную не требуется.","pageEditor.chooseIcon": "Выбрать иконку",+ "pageEditor.comments.attachments.add": "Добавить",+ "pageEditor.comments.attachments.chooseLibrary": "Выбрать из библиотеки",+ "pageEditor.comments.author.deactivated": "Деактивированный пользователь",+ "pageEditor.comments.author.former": "Бывший участник",+ "pageEditor.comments.cancel": "Отмена",+ "pageEditor.comments.createFailed": "Не удалось опубликовать комментарий. Ваш черновик все еще здесь.",+ "pageEditor.comments.delete": "Удалить",+ "pageEditor.comments.deleteConfirm.content": "Удалить этот комментарий? Ответы останутся видимыми, если у этого комментария есть ветка.",+ "pageEditor.comments.deleteConfirm.title": "Удалить комментарий",+ "pageEditor.comments.deleteFailed": "Не удалось удалить комментарий. Попробуйте снова.",+ "pageEditor.comments.deleted": "Этот комментарий был удален.",+ "pageEditor.comments.edit": "Редактировать",+ "pageEditor.comments.edited": "(отредактировано)",+ "pageEditor.comments.empty": "Пока нет комментариев. Начните разговор ниже.",+ "pageEditor.comments.hideReplies": "Скрыть ответы",+ "pageEditor.comments.loadMore": "Загрузить больше комментариев",+ "pageEditor.comments.loadMoreReplies": "Загрузить больше ответов",+ "pageEditor.comments.moreActions": "Дополнительные действия",+ "pageEditor.comments.placeholder": "Добавить комментарий…",+ "pageEditor.comments.publish": "Комментировать",+ "pageEditor.comments.replies_one": "{{count}} ответ",+ "pageEditor.comments.replies_other": "{{count}} ответов",+ "pageEditor.comments.replyAction": "Ответить",+ "pageEditor.comments.replyPlaceholder": "Написать ответ…",+ "pageEditor.comments.save": "Сохранить",+ "pageEditor.comments.title": "Комментарии",+ "pageEditor.comments.updateFailed": "Не удалось обновить комментарий. Попробуйте снова.","pageEditor.deleteConfirm.content": "Эта страница будет удалена без возможности восстановления. Пожалуйста, будьте осторожны.","pageEditor.deleteConfirm.title": "Удалить страницу","pageEditor.deleteError": "Не удалось удалить страницу",diff --git a/locales/ru-RU/notification.json b/locales/ru-RU/notification.jsonindex 895d06976ad..7c1d4c17b57 100644--- a/locales/ru-RU/notification.json+++ b/locales/ru-RU/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Ваш запланированный задачa \"{{jobName}}\" была приостановлена после {{count}} последовательных ошибок. Проверьте ошибку и возобновите выполнение, когда будете готовы.","agent_cron_job_failed_paused_title": "Запланированная задача приостановлена","agent_cron_job_failed_title": "Сбой запланированной задачи",+ "agent_intervention_required": "{{agent}} нуждается в вашем участии: {{summary}}",+ "agent_intervention_required_title": "{{agent}} нуждается в вашем рассмотрении","agent_run_completed": "{{preview}}","agent_run_completed_title": "Задача агента выполнена","agent_transfer_reassigned": "Владелец рабочего пространства передал вашего агента \"{{agentTitle}}\" пользователю {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Ваш баланс кредитов заканчивается — осталось примерно {{balance}} кредитов. Включите автоматическое пополнение, чтобы ваш баланс пополнялся автоматически и ваша работа не прерывалась.","credit_balance_low_action": "Настроить автоматическое пополнение","credit_balance_low_title": "Ваш баланс кредитов заканчивается",+ "document_comment_activity": "{{actorLabel}} оставил комментарий к вашему документу \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} ответил на ваш комментарий в \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Новый ответ на ваш комментарий",+ "document_comment_activity_title": "Новый комментарий к вашему документу",+ "document_comment_mentioned": "{{actorLabel}} упомянул вас в комментарии к \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Вы были упомянуты в комментарии к документу","email.footer.contactSupport": "Связаться с поддержкой","email.footer.joinDiscord": "Присоединиться к Discord","email.footer.manage": "Управление уведомлениями",diff --git a/locales/ru-RU/portal.json b/locales/ru-RU/portal.jsonindex f5a43ffc7bd..5e231729f73 100644--- a/locales/ru-RU/portal.json+++ b/locales/ru-RU/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Скопировать URL","artifacts.deploy.copySuccess": "URL развертывания скопирован","artifacts.deploy.failed": "Ошибка развертывания",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Достигнут предел текущей емкости для самостоятельного развертывания. Управляйте опубликованными проектами или уменьшите использование развертывания.","artifacts.deploy.highestPlanLimitReached": "Достигнут лимит публичных развертываний ({{used}} / {{limit}}). Отмените публикацию проекта, чтобы освободить место.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Этот сайт имеет размер {{actual}}, что превышает предел {{limit}} для самостоятельного развертывания. Уменьшите его ресурсы перед публикацией.","artifacts.deploy.history": "История версий","artifacts.deploy.limitReached": "Достигнут лимит публичных развертываний ({{used}} / {{limit}}). Отмените публикацию проекта или обновите ваш план.","artifacts.deploy.open": "Открыть развертывание",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Опубликовать","artifacts.deploy.publishNewVersion": "Опубликовать эту версию","artifacts.deploy.quotaUnavailable": "Проверка квоты на развертывание временно недоступна. Попробуйте позже.",+ "artifacts.deploy.serviceOverloaded": "Хостинг артефактов временно перегружен. Попробуйте опубликовать снова через некоторое время.","artifacts.deploy.success": "Опубликовано","artifacts.deploy.writeInProgress": "В настоящее время выполняется другое изменение развертывания. Попробуйте снова через некоторое время.","artifacts.display.code": "Код",diff --git a/locales/ru-RU/subscription.json b/locales/ru-RU/subscription.jsonindex 7632a53fc9a..17251da097f 100644--- a/locales/ru-RU/subscription.json+++ b/locales/ru-RU/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Ошибка обновления","payment.upgradeSuccess.desc": "Ваш тарифный план успешно обновлён","payment.upgradeSuccess.title": "Обновление успешно",+ "plans.artifactHosting.deployments": "До {{count}} активных сайтов артефактов",+ "plans.artifactHosting.siteSize": "До {{size}} на опубликованный сайт",+ "plans.artifactHosting.title": "Хостинг артефактов","plans.btn.contact": "Связаться с нами","plans.btn.noAction": "План заблокирован","plans.btn.payment": "Купить",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 299c66a948e..d60e98297b2 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Tükendi — {{time}}'de sıfırlanacak","heteroAgent.claudeQuota.calendar.burnout.safe": "Mevcut hızda bu pencere yaklaşık {{percent}}% ile sona eriyor","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "Mevcut hızda, kota yaklaşık {{time}}'de tükeniyor",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Kapasite kullanıldı","heteroAgent.claudeQuota.calendar.currentWindow": "Mevcut pencere","heteroAgent.claudeQuota.calendar.dayShare": "Bu pencerenin {{percent}}%'i kullanıldı","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} jeton · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Geçmiş kaydedilmedi","heteroAgent.claudeQuota.calendar.pace": "Dengeli hız","heteroAgent.claudeQuota.calendar.partialCost": "en az {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Son gözlemlenen pencere","heteroAgent.claudeQuota.calendar.rateLimited": "Hız sınırlandırıldı","heteroAgent.claudeQuota.calendar.resetAt": "Pencere {{time}}'de sıfırlanacak",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Tekrar Dene","input.inputCompletionError.settings": "Ayarlar","input.inputCompletionError.title": "Giriş önerileri duraklatıldı",+ "input.modelDisabled": "Mevcut model devre dışı bırakıldı",+ "input.modelDisabled.action": "Etkinleştir",+ "input.modelDisabled.actionFailed": "Modeli etkinleştirme başarısız oldu. Lütfen tekrar deneyin.",+ "input.modelDisabled.selectionFailed": "Model etkinleştirildi, ancak sağlayıcı değiştirme başarısız oldu. Devam etmek için tekrar seçin.","input.modelFixedTip": "Model, Temsilci Profilinde sabitlenmiştir ve sohbet sırasında değiştirilemez.","input.modelUnavailable": "Mevcut model artık kullanılamıyor. Devam etmek için başka bir model seçin.","input.more": "Daha Fazla",diff --git a/locales/tr-TR/file.json b/locales/tr-TR/file.jsonindex 05ca40ae92e..1cdefdd5c3f 100644--- a/locales/tr-TR/file.json+++ b/locales/tr-TR/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Simge Ekle","pageEditor.autoSaveMessage": "Sayfanız otomatik olarak kaydedilir. Manuel kaydetmenize gerek yok.","pageEditor.chooseIcon": "Simge Seç",+ "pageEditor.comments.attachments.add": "Ekle",+ "pageEditor.comments.attachments.chooseLibrary": "Kütüphaneden Seç",+ "pageEditor.comments.author.deactivated": "Devre dışı bırakılmış kullanıcı",+ "pageEditor.comments.author.former": "Eski üye",+ "pageEditor.comments.cancel": "İptal",+ "pageEditor.comments.createFailed": "Yorum yayınlanamadı. Taslağınız hala burada.",+ "pageEditor.comments.delete": "Sil",+ "pageEditor.comments.deleteConfirm.content": "Bu yorumu silmek istiyor musunuz? Eğer bu yorumun bir dizisi varsa, yanıtlar görünür kalacaktır.",+ "pageEditor.comments.deleteConfirm.title": "Yorumu sil",+ "pageEditor.comments.deleteFailed": "Yorum silinemedi. Tekrar deneyin.",+ "pageEditor.comments.deleted": "Bu yorum silindi.",+ "pageEditor.comments.edit": "Düzenle",+ "pageEditor.comments.edited": "(düzenlendi)",+ "pageEditor.comments.empty": "Henüz yorum yok. Aşağıdan konuşmayı başlatın.",+ "pageEditor.comments.hideReplies": "Yanıtları gizle",+ "pageEditor.comments.loadMore": "Daha fazla yorum yükle",+ "pageEditor.comments.loadMoreReplies": "Daha fazla yanıt yükle",+ "pageEditor.comments.moreActions": "Daha fazla işlem",+ "pageEditor.comments.placeholder": "Bir yorum ekle…",+ "pageEditor.comments.publish": "Yorum Yap",+ "pageEditor.comments.replies_one": "{{count}} yanıt",+ "pageEditor.comments.replies_other": "{{count}} yanıt",+ "pageEditor.comments.replyAction": "Yanıtla",+ "pageEditor.comments.replyPlaceholder": "Bir yanıt yazın…",+ "pageEditor.comments.save": "Kaydet",+ "pageEditor.comments.title": "Yorumlar",+ "pageEditor.comments.updateFailed": "Yorum güncellenemedi. Tekrar deneyin.","pageEditor.deleteConfirm.content": "Bu sayfa silinecek ve geri alınamayacak. Lütfen dikkatli olun.","pageEditor.deleteConfirm.title": "Sayfayı Sil","pageEditor.deleteError": "Sayfa silinemedi",diff --git a/locales/tr-TR/notification.json b/locales/tr-TR/notification.jsonindex cff02e82aca..582c5d3bd3e 100644--- a/locales/tr-TR/notification.json+++ b/locales/tr-TR/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Planlanmış göreviniz \"{{jobName}}\" {{count}} ardışık hata sonrası duraklatıldı. Hata inceleyin ve hazır olduğunuzda devam ettirin.","agent_cron_job_failed_paused_title": "Planlanmış görev duraklatıldı","agent_cron_job_failed_title": "Zamanlanmış görev başarısız oldu",+ "agent_intervention_required": "{{agent}} sizin girdinize ihtiyaç duyuyor: {{summary}}",+ "agent_intervention_required_title": "{{agent}} incelemenizi bekliyor","agent_run_completed": "{{preview}}","agent_run_completed_title": "Ajans görevi tamamlandı","agent_transfer_reassigned": "Bir çalışma alanı sahibi, \"{{agentTitle}}\" adlı temsilcinizi {{recipientLabel}}'e aktardı.",@@ -32,6 +34,12 @@"credit_balance_low": "Kredi bakiyeniz azalıyor — yaklaşık {{balance}} kredi kaldı. Otomatik bakiye yüklemeyi açarak bakiyenizin otomatik olarak yenilenmesini sağlayabilir ve çalışmalarınızın kesintiye uğramasını önleyebilirsiniz.","credit_balance_low_action": "Otomatik bakiye yüklemeyi ayarla","credit_balance_low_title": "Kredi bakiyeniz azalıyor",+ "document_comment_activity": "{{actorLabel}} belgeniz \"{{documentTitle}}\" üzerinde yorum yaptı.",+ "document_comment_activity_replied": "{{actorLabel}} \"{{documentTitle}}\" içindeki yorumunuza yanıt verdi.",+ "document_comment_activity_replied_title": "Yorumunuza yeni bir yanıt",+ "document_comment_activity_title": "Belgenizde yeni bir yorum",+ "document_comment_mentioned": "{{actorLabel}} \"{{documentTitle}}\" üzerindeki bir yorumda sizi bahsetti.",+ "document_comment_mentioned_title": "Bir belge yorumunda bahsedildiniz","email.footer.contactSupport": "Destek ile iletişime geçin","email.footer.joinDiscord": "Discord'a katılın","email.footer.manage": "Bildirimleri yönet",diff --git a/locales/tr-TR/portal.json b/locales/tr-TR/portal.jsonindex 9254b193d3d..fc94ca64c84 100644--- a/locales/tr-TR/portal.json+++ b/locales/tr-TR/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "URL'yi Kopyala","artifacts.deploy.copySuccess": "Dağıtım URL'si kopyalandı","artifacts.deploy.failed": "Dağıtım başarısız oldu",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Mevcut self-servis dağıtım kapasitesine ulaşıldı. Yayınlanan projeleri yönetin veya dağıtım kullanımını azaltın.","artifacts.deploy.highestPlanLimitReached": "Halka açık dağıtım limiti aşıldı ({{used}} / {{limit}}). Bir projeyi yayından kaldırarak bir slot boşaltın.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Bu site {{actual}}, {{limit}} self-servis limitinin üzerinde. Yayınlamadan önce varlıklarını azaltın.","artifacts.deploy.history": "Revizyon geçmişi","artifacts.deploy.limitReached": "Halka açık dağıtım limiti aşıldı ({{used}} / {{limit}}). Bir projeyi yayından kaldırın veya planınızı yükseltin.","artifacts.deploy.open": "Dağıtımı aç",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Yayınla","artifacts.deploy.publishNewVersion": "Bu sürümü yayınla","artifacts.deploy.quotaUnavailable": "Dağıtım kotası doğrulaması geçici olarak kullanılamıyor. Daha sonra tekrar deneyin.",+ "artifacts.deploy.serviceOverloaded": "Artifact barındırma geçici olarak aşırı yüklendi. Kısa bir süre sonra tekrar yayınlamayı deneyin.","artifacts.deploy.success": "Yayınlandı","artifacts.deploy.writeInProgress": "Başka bir dağıtım değişikliği devam ediyor. Kısa bir süre sonra tekrar deneyin.","artifacts.display.code": "Kod",diff --git a/locales/tr-TR/subscription.json b/locales/tr-TR/subscription.jsonindex 0e39388d56a..439b80d6804 100644--- a/locales/tr-TR/subscription.json+++ b/locales/tr-TR/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Yükseltme Başarısız","payment.upgradeSuccess.desc": "Abonelik planınız başarıyla yükseltildi","payment.upgradeSuccess.title": "Yükseltme Başarılı",+ "plans.artifactHosting.deployments": "{{count}} adede kadar aktif Artifact sitesi",+ "plans.artifactHosting.siteSize": "Yayımlanan site başına {{size}}'ye kadar",+ "plans.artifactHosting.title": "Artifact Barındırma","plans.btn.contact": "Bize Ulaşın","plans.btn.noAction": "Plan Kilitli","plans.btn.payment": "Satın Al",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 634e8ceedb4..f8e35fc5b67 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Đã hết — đặt lại {{time}}","heteroAgent.claudeQuota.calendar.burnout.safe": "Với tốc độ hiện tại, cửa sổ này kết thúc khoảng {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "Với tốc độ hiện tại, hạn ngạch sẽ hết khoảng {{time}}",- "heteroAgent.claudeQuota.calendar.capacityUsed": "Dung lượng đã sử dụng","heteroAgent.claudeQuota.calendar.currentWindow": "Cửa sổ hiện tại","heteroAgent.claudeQuota.calendar.dayShare": "Đã sử dụng {{percent}}% của cửa sổ này","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} mã thông báo · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "Lịch sử không được ghi lại","heteroAgent.claudeQuota.calendar.pace": "Tốc độ đều","heteroAgent.claudeQuota.calendar.partialCost": "ít nhất {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "Cửa sổ quan sát gần đây","heteroAgent.claudeQuota.calendar.rateLimited": "Bị giới hạn tốc độ","heteroAgent.claudeQuota.calendar.resetAt": "Cửa sổ đặt lại lúc {{time}}",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "Thử lại","input.inputCompletionError.settings": "Cài đặt","input.inputCompletionError.title": "Gợi ý nhập liệu đã tạm dừng",+ "input.modelDisabled": "Mô hình hiện tại đã bị vô hiệu hóa",+ "input.modelDisabled.action": "Kích hoạt",+ "input.modelDisabled.actionFailed": "Không thể kích hoạt mô hình. Vui lòng thử lại.",+ "input.modelDisabled.selectionFailed": "Mô hình đã được kích hoạt, nhưng việc chuyển đổi nhà cung cấp thất bại. Vui lòng chọn lại để tiếp tục.","input.modelFixedTip": "Mô hình được cố định trong Hồ sơ Đại lý và không thể thay đổi trong khi trò chuyện.","input.modelUnavailable": "Mô hình hiện tại không còn khả dụng. Chọn mô hình khác để tiếp tục.","input.more": "Thêm",diff --git a/locales/vi-VN/file.json b/locales/vi-VN/file.jsonindex 68502bfdaa2..4a6fe169841 100644--- a/locales/vi-VN/file.json+++ b/locales/vi-VN/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "Thêm Biểu Tượng","pageEditor.autoSaveMessage": "Trang của bạn được lưu tự động. Không cần lưu thủ công.","pageEditor.chooseIcon": "Chọn Biểu Tượng",+ "pageEditor.comments.attachments.add": "Thêm",+ "pageEditor.comments.attachments.chooseLibrary": "Chọn từ Thư viện",+ "pageEditor.comments.author.deactivated": "Người dùng đã bị vô hiệu hóa",+ "pageEditor.comments.author.former": "Thành viên cũ",+ "pageEditor.comments.cancel": "Hủy",+ "pageEditor.comments.createFailed": "Không thể đăng bình luận. Bản nháp của bạn vẫn còn ở đây.",+ "pageEditor.comments.delete": "Xóa",+ "pageEditor.comments.deleteConfirm.content": "Xóa bình luận này? Các phản hồi sẽ vẫn hiển thị nếu bình luận này có chuỗi.",+ "pageEditor.comments.deleteConfirm.title": "Xóa bình luận",+ "pageEditor.comments.deleteFailed": "Không thể xóa bình luận. Vui lòng thử lại.",+ "pageEditor.comments.deleted": "Bình luận này đã bị xóa.",+ "pageEditor.comments.edit": "Chỉnh sửa",+ "pageEditor.comments.edited": "(đã chỉnh sửa)",+ "pageEditor.comments.empty": "Chưa có bình luận nào. Bắt đầu cuộc trò chuyện bên dưới.",+ "pageEditor.comments.hideReplies": "Ẩn phản hồi",+ "pageEditor.comments.loadMore": "Tải thêm bình luận",+ "pageEditor.comments.loadMoreReplies": "Tải thêm phản hồi",+ "pageEditor.comments.moreActions": "Thêm hành động",+ "pageEditor.comments.placeholder": "Thêm bình luận…",+ "pageEditor.comments.publish": "Bình luận",+ "pageEditor.comments.replies_one": "{{count}} phản hồi",+ "pageEditor.comments.replies_other": "{{count}} phản hồi",+ "pageEditor.comments.replyAction": "Phản hồi",+ "pageEditor.comments.replyPlaceholder": "Viết phản hồi…",+ "pageEditor.comments.save": "Lưu",+ "pageEditor.comments.title": "Bình luận",+ "pageEditor.comments.updateFailed": "Không thể cập nhật bình luận. Vui lòng thử lại.","pageEditor.deleteConfirm.content": "Trang này sẽ bị xóa và không thể khôi phục. Vui lòng cẩn thận.","pageEditor.deleteConfirm.title": "Xóa Trang","pageEditor.deleteError": "Không thể xóa trang",diff --git a/locales/vi-VN/notification.json b/locales/vi-VN/notification.jsonindex 4c4a919bc0e..7987687191a 100644--- a/locales/vi-VN/notification.json+++ b/locales/vi-VN/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "Nhiệm vụ đã lên lịch \"{{jobName}}\" của bạn đã bị tạm dừng sau {{count}} lần thất bại liên tiếp. Vui lòng xem lại lỗi và tiếp tục khi sẵn sàng.","agent_cron_job_failed_paused_title": "Nhiệm vụ đã lên lịch bị tạm dừng","agent_cron_job_failed_title": "Tác vụ đã lên lịch thất bại",+ "agent_intervention_required": "{{agent}} cần ý kiến của bạn: {{summary}}",+ "agent_intervention_required_title": "{{agent}} cần bạn xem xét","agent_run_completed": "{{preview}}","agent_run_completed_title": "Nhiệm vụ của tác nhân đã hoàn thành","agent_transfer_reassigned": "Một chủ sở hữu không gian làm việc đã chuyển đại lý của bạn \"{{agentTitle}}\" đến {{recipientLabel}}.",@@ -32,6 +34,12 @@"credit_balance_low": "Số dư tín dụng của bạn sắp hết — còn khoảng {{balance}} tín dụng. Bật tự động nạp tiền để số dư của bạn được nạp lại tự động và công việc của bạn không bị gián đoạn.","credit_balance_low_action": "Thiết lập tự động nạp tiền","credit_balance_low_title": "Số dư tín dụng của bạn sắp hết",+ "document_comment_activity": "{{actorLabel}} đã bình luận về tài liệu của bạn \"{{documentTitle}}\".",+ "document_comment_activity_replied": "{{actorLabel}} đã trả lời bình luận của bạn trong \"{{documentTitle}}\".",+ "document_comment_activity_replied_title": "Phản hồi mới cho bình luận của bạn",+ "document_comment_activity_title": "Bình luận mới về tài liệu của bạn",+ "document_comment_mentioned": "{{actorLabel}} đã nhắc đến bạn trong một bình luận về \"{{documentTitle}}\".",+ "document_comment_mentioned_title": "Bạn đã được nhắc đến trong một bình luận tài liệu","email.footer.contactSupport": "Liên hệ hỗ trợ","email.footer.joinDiscord": "Tham gia Discord","email.footer.manage": "Quản lý thông báo",diff --git a/locales/vi-VN/portal.json b/locales/vi-VN/portal.jsonindex 20228cc1640..0cfea05a46e 100644--- a/locales/vi-VN/portal.json+++ b/locales/vi-VN/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "Sao chép URL","artifacts.deploy.copySuccess": "URL triển khai đã được sao chép","artifacts.deploy.failed": "Triển khai thất bại",+ "artifacts.deploy.highestPlanCapacityLimitReached": "Đã đạt đến giới hạn triển khai tự phục vụ hiện tại. Quản lý các dự án đã xuất bản hoặc giảm sử dụng triển khai.","artifacts.deploy.highestPlanLimitReached": "Đã đạt giới hạn triển khai công khai ({{used}} / {{limit}}). Hủy xuất bản một dự án để giải phóng một vị trí.",+ "artifacts.deploy.highestPlanSizeLimitReached": "Trang web này là {{actual}}, vượt quá giới hạn tự phục vụ {{limit}}. Giảm tài nguyên của nó trước khi xuất bản.","artifacts.deploy.history": "Lịch sử phiên bản","artifacts.deploy.limitReached": "Đã đạt giới hạn triển khai công khai ({{used}} / {{limit}}). Hủy xuất bản một dự án hoặc nâng cấp gói của bạn.","artifacts.deploy.open": "Mở triển khai",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "Xuất bản","artifacts.deploy.publishNewVersion": "Xuất bản phiên bản này","artifacts.deploy.quotaUnavailable": "Xác thực hạn mức triển khai tạm thời không khả dụng. Vui lòng thử lại sau.",+ "artifacts.deploy.serviceOverloaded": "Dịch vụ lưu trữ tài nguyên hiện đang quá tải. Vui lòng thử xuất bản lại sau.","artifacts.deploy.success": "Đã xuất bản","artifacts.deploy.writeInProgress": "Một thay đổi triển khai khác đang được tiến hành. Vui lòng thử lại sau.","artifacts.display.code": "Mã",diff --git a/locales/vi-VN/subscription.json b/locales/vi-VN/subscription.jsonindex 0b1901382df..dd2b24d0357 100644--- a/locales/vi-VN/subscription.json+++ b/locales/vi-VN/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "Nâng cấp thất bại","payment.upgradeSuccess.desc": "Gói đăng ký của bạn đã được nâng cấp thành công","payment.upgradeSuccess.title": "Nâng cấp thành công",+ "plans.artifactHosting.deployments": "Tối đa {{count}} trang Artifact đang hoạt động",+ "plans.artifactHosting.siteSize": "Tối đa {{size}} cho mỗi trang đã xuất bản",+ "plans.artifactHosting.title": "Lưu trữ Artifact","plans.btn.contact": "Liên hệ với chúng tôi","plans.btn.noAction": "Gói bị khóa","plans.btn.payment": "Mua",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 8977a6c9c14..b4c5fb905c4 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "添加图标","pageEditor.autoSaveMessage": "文稿会自动保存,无需手动保存","pageEditor.chooseIcon": "选择图标",+ "pageEditor.comments.attachments.add": "添加",+ "pageEditor.comments.attachments.chooseLibrary": "从文件库选择",+ "pageEditor.comments.author.deactivated": "已停用用户",+ "pageEditor.comments.author.former": "前成员",+ "pageEditor.comments.cancel": "取消",+ "pageEditor.comments.createFailed": "评论发布失败,草稿已为你保留",+ "pageEditor.comments.delete": "删除",+ "pageEditor.comments.deleteConfirm.content": "确定删除这条评论吗?如果评论下有回复,回复仍会保留。",+ "pageEditor.comments.deleteConfirm.title": "删除评论",+ "pageEditor.comments.deleteFailed": "评论删除失败,请重试",+ "pageEditor.comments.deleted": "这条评论已被删除",+ "pageEditor.comments.edit": "编辑",+ "pageEditor.comments.edited": "(已编辑)",+ "pageEditor.comments.empty": "还没有评论,在下方开始讨论吧",+ "pageEditor.comments.hideReplies": "收起回复",+ "pageEditor.comments.loadMore": "加载更多评论",+ "pageEditor.comments.loadMoreReplies": "加载更多回复",+ "pageEditor.comments.moreActions": "更多操作",+ "pageEditor.comments.placeholder": "添加评论…",+ "pageEditor.comments.publish": "评论",+ "pageEditor.comments.replies_one": "{{count}} 条回复",+ "pageEditor.comments.replies_other": "{{count}} 条回复",+ "pageEditor.comments.replyAction": "回复",+ "pageEditor.comments.replyPlaceholder": "写下回复…",+ "pageEditor.comments.save": "保存",+ "pageEditor.comments.title": "评论",+ "pageEditor.comments.updateFailed": "评论更新失败,请重试","pageEditor.deleteConfirm.content": "确认删除该文稿吗?删除后不可恢复。建议先导出或复制重要内容","pageEditor.deleteConfirm.title": "删除文稿","pageEditor.deleteError": "删除遇到了问题。你可以重试",diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.jsonindex 41c3d5b1892..ef575c3fe6b 100644--- a/locales/zh-CN/notification.json+++ b/locales/zh-CN/notification.json@@ -34,6 +34,12 @@"credit_balance_low": "您的积分余额即将用尽,当前约剩余 {{balance}} 的积分。建议开启自动充值,余额不足时自动续费,让你的工作不被中断。","credit_balance_low_action": "开启自动充值","credit_balance_low_title": "您的积分余额即将用尽",+ "document_comment_activity": "{{actorLabel}} 评论了你的文档「{{documentTitle}}」。",+ "document_comment_activity_replied": "{{actorLabel}} 在「{{documentTitle}}」中回复了你的评论。",+ "document_comment_activity_replied_title": "你的评论有新回复",+ "document_comment_activity_title": "你的文档有新评论",+ "document_comment_mentioned": "{{actorLabel}} 在文档「{{documentTitle}}」的评论中提到了你。",+ "document_comment_mentioned_title": "你在文档评论中被提及","email.footer.contactSupport": "联系支持","email.footer.joinDiscord": "加入 Discord","email.footer.manage": "管理通知",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex 4ca07b3225d..1bc492c914b 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -557,7 +557,6 @@"heteroAgent.claudeQuota.calendar.burnout.exhausted": "已用盡——將於 {{time}} 重置","heteroAgent.claudeQuota.calendar.burnout.safe": "按當前速度,此窗口結束時約為 {{percent}}%","heteroAgent.claudeQuota.calendar.burnout.willExhaust": "按當前速度,配額將於 {{time}} 用盡",- "heteroAgent.claudeQuota.calendar.capacityUsed": "已用容量","heteroAgent.claudeQuota.calendar.currentWindow": "當前窗口","heteroAgent.claudeQuota.calendar.dayShare": "已用 {{percent}}% 的此窗口","heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} 代幣 · {{cost}}",@@ -572,6 +571,7 @@"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "未記錄歷史","heteroAgent.claudeQuota.calendar.pace": "均勻速度","heteroAgent.claudeQuota.calendar.partialCost": "至少 {{cost}}",+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+","heteroAgent.claudeQuota.calendar.pastWindow": "上次觀察窗口","heteroAgent.claudeQuota.calendar.rateLimited": "速率受限","heteroAgent.claudeQuota.calendar.resetAt": "窗口將於 {{time}} 重置",@@ -787,6 +787,10 @@"input.inputCompletionError.retry": "重試","input.inputCompletionError.settings": "設定","input.inputCompletionError.title": "輸入建議已暫停",+ "input.modelDisabled": "目前的模型已停用",+ "input.modelDisabled.action": "啟用",+ "input.modelDisabled.actionFailed": "啟用模型失敗。請再試一次。",+ "input.modelDisabled.selectionFailed": "模型已啟用,但切換提供者失敗。請重新選擇以繼續。","input.modelFixedTip": "模型已在代理檔案中固定,聊天時無法切換。","input.modelUnavailable": "目前的模型已不再可用。請選擇其他模型以繼續。","input.more": "更多",diff --git a/locales/zh-TW/file.json b/locales/zh-TW/file.jsonindex 6f8514759d4..c3462e6aea6 100644--- a/locales/zh-TW/file.json+++ b/locales/zh-TW/file.json@@ -92,6 +92,33 @@"pageEditor.addIcon": "新增圖示","pageEditor.autoSaveMessage": "文稿會自動儲存,無需手動儲存","pageEditor.chooseIcon": "選擇圖示",+ "pageEditor.comments.attachments.add": "新增",+ "pageEditor.comments.attachments.chooseLibrary": "從資料庫選擇",+ "pageEditor.comments.author.deactivated": "已停用的使用者",+ "pageEditor.comments.author.former": "前成員",+ "pageEditor.comments.cancel": "取消",+ "pageEditor.comments.createFailed": "發佈評論失敗。您的草稿仍然保留。",+ "pageEditor.comments.delete": "刪除",+ "pageEditor.comments.deleteConfirm.content": "確定要刪除此評論嗎?如果此評論有回覆,回覆仍會顯示。",+ "pageEditor.comments.deleteConfirm.title": "刪除評論",+ "pageEditor.comments.deleteFailed": "刪除評論失敗。請再試一次。",+ "pageEditor.comments.deleted": "此評論已被刪除。",+ "pageEditor.comments.edit": "編輯",+ "pageEditor.comments.edited": "(已編輯)",+ "pageEditor.comments.empty": "目前沒有評論。請在下方開始對話。",+ "pageEditor.comments.hideReplies": "隱藏回覆",+ "pageEditor.comments.loadMore": "載入更多評論",+ "pageEditor.comments.loadMoreReplies": "載入更多回覆",+ "pageEditor.comments.moreActions": "更多操作",+ "pageEditor.comments.placeholder": "新增評論…",+ "pageEditor.comments.publish": "發表評論",+ "pageEditor.comments.replies_one": "{{count}} 則回覆",+ "pageEditor.comments.replies_other": "{{count}} 則回覆",+ "pageEditor.comments.replyAction": "回覆",+ "pageEditor.comments.replyPlaceholder": "撰寫回覆…",+ "pageEditor.comments.save": "儲存",+ "pageEditor.comments.title": "評論",+ "pageEditor.comments.updateFailed": "更新評論失敗。請再試一次。","pageEditor.deleteConfirm.content": "即將刪除此文稿,刪除後將無法恢復,請謹慎操作。","pageEditor.deleteConfirm.title": "刪除文稿","pageEditor.deleteError": "刪除文稿失敗",diff --git a/locales/zh-TW/notification.json b/locales/zh-TW/notification.jsonindex d0792063370..5063c7f727b 100644--- a/locales/zh-TW/notification.json+++ b/locales/zh-TW/notification.json@@ -7,6 +7,8 @@"agent_cron_job_failed_paused": "您的排程任務「{{jobName}}」在連續失敗 {{count}} 次後已被暫停。請檢查錯誤並在準備好後恢復執行。","agent_cron_job_failed_paused_title": "排程任務已暫停","agent_cron_job_failed_title": "排程任務失敗",+ "agent_intervention_required": "{{agent}} 需要您的輸入:{{summary}}",+ "agent_intervention_required_title": "{{agent}} 需要您的審核","agent_run_completed": "{{preview}}","agent_run_completed_title": "代理任務已完成","agent_transfer_reassigned": "工作區擁有者已將您的代理「{{agentTitle}}」轉移至 {{recipientLabel}}。",@@ -32,6 +34,12 @@"credit_balance_low": "您的信用餘額即將不足 — 剩餘約 {{balance}} 點信用。啟用自動充值功能,讓您的餘額自動補充,工作不受中斷。","credit_balance_low_action": "設定自動充值","credit_balance_low_title": "您的信用餘額即將不足",+ "document_comment_activity": "{{actorLabel}} 在您的文件「{{documentTitle}}」中留下了評論。",+ "document_comment_activity_replied": "{{actorLabel}} 回覆了您在「{{documentTitle}}」中的評論。",+ "document_comment_activity_replied_title": "您的評論有新的回覆",+ "document_comment_activity_title": "您的文件有新的評論",+ "document_comment_mentioned": "{{actorLabel}} 在「{{documentTitle}}」的評論中提到了您。",+ "document_comment_mentioned_title": "您在文件評論中被提及","email.footer.contactSupport": "聯絡支援","email.footer.joinDiscord": "加入 Discord","email.footer.manage": "管理通知",diff --git a/locales/zh-TW/portal.json b/locales/zh-TW/portal.jsonindex 6319cf62954..42715cc2506 100644--- a/locales/zh-TW/portal.json+++ b/locales/zh-TW/portal.json@@ -9,7 +9,9 @@"artifacts.deploy.copy": "複製網址","artifacts.deploy.copySuccess": "部署網址已複製","artifacts.deploy.failed": "部署失敗",+ "artifacts.deploy.highestPlanCapacityLimitReached": "目前已達到自助部署容量上限。請管理已發布的專案或減少部署使用量。","artifacts.deploy.highestPlanLimitReached": "已達公開部署限制({{used}} / {{limit}})。取消發布一個專案以釋放空間。",+ "artifacts.deploy.highestPlanSizeLimitReached": "此網站大小為 {{actual}},超過了 {{limit}} 的自助限制。請在發布前減少其資產。","artifacts.deploy.history": "修訂歷史","artifacts.deploy.limitReached": "已達公開部署限制({{used}} / {{limit}})。取消發布一個專案或升級您的方案。","artifacts.deploy.open": "開啟部署",@@ -17,6 +19,7 @@"artifacts.deploy.publish": "發布","artifacts.deploy.publishNewVersion": "發布此版本","artifacts.deploy.quotaUnavailable": "部署配額驗證暫時不可用。請稍後再試。",+ "artifacts.deploy.serviceOverloaded": "工件託管暫時過載。請稍後再嘗試發布。","artifacts.deploy.success": "已發布","artifacts.deploy.writeInProgress": "另一項部署變更正在進行中。請稍後再試。","artifacts.display.code": "程式碼",diff --git a/locales/zh-TW/subscription.json b/locales/zh-TW/subscription.jsonindex dafd2ad2c2c..8553ea2a388 100644--- a/locales/zh-TW/subscription.json+++ b/locales/zh-TW/subscription.json@@ -361,6 +361,9 @@"payment.upgradeFailed.title": "升級失敗","payment.upgradeSuccess.desc": "您的訂閱方案已成功升級","payment.upgradeSuccess.title": "升級成功",+ "plans.artifactHosting.deployments": "最多可有 {{count}} 個啟用的 Artifact 網站",+ "plans.artifactHosting.siteSize": "每個已發布網站最多可達 {{size}}",+ "plans.artifactHosting.title": "Artifact 主機服務","plans.btn.contact": "聯絡我們","plans.btn.noAction": "方案已鎖定","plans.btn.payment": "立即購買",diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 0ada181c788..3e2ae38e47f 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -201,6 +201,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuleconnector: 'blocked',device: 'blocked',document: rw('knowledge:read', 'knowledge:write'),+ documentComment: rw('knowledge:read', 'knowledge:write'),expertise: rw('agent:read', 'agent:write'),// whole-account backup dump (settings incl. market tokens, providers, agents)exporter: 'blocked',diff --git a/packages/const/src/rbac.ts b/packages/const/src/rbac.tsindex 90e4f45da27..b5f3694b1a0 100644--- a/packages/const/src/rbac.ts+++ b/packages/const/src/rbac.ts@@ -62,6 +62,15 @@ export const PERMISSION_ACTIONS = {DOCUMENT_UPDATE: 'document:update',+ // ==================== Document Comment Management ====================+ DOCUMENT_COMMENT_CREATE: 'document_comment:create',++ DOCUMENT_COMMENT_DELETE: 'document_comment:delete',++ DOCUMENT_COMMENT_READ: 'document_comment:read',++ DOCUMENT_COMMENT_UPDATE: 'document_comment:update',+// ==================== File Management ====================FILE_DELETE: 'file:delete',@@ -406,6 +415,10 @@ export const WORKSPACE_ROLE_PERMISSIONS: Record<WorkspaceSystemRoleName, readonl`${action('DOCUMENT_CREATE')}:all`,`${action('DOCUMENT_UPDATE')}:all`,`${action('DOCUMENT_DELETE')}:all`,+ `${action('DOCUMENT_COMMENT_READ')}:all`,+ `${action('DOCUMENT_COMMENT_CREATE')}:all`,+ `${action('DOCUMENT_COMMENT_UPDATE')}:all`,+ `${action('DOCUMENT_COMMENT_DELETE')}:all`,`${action('KNOWLEDGE_BASE_READ')}:all`,`${action('KNOWLEDGE_BASE_CREATE')}:all`,`${action('KNOWLEDGE_BASE_UPDATE')}:all`,@@ -483,6 +496,10 @@ export const WORKSPACE_ROLE_PERMISSIONS: Record<WorkspaceSystemRoleName, readonl`${action('DOCUMENT_CREATE')}:owner`,`${action('DOCUMENT_UPDATE')}:owner`,`${action('DOCUMENT_DELETE')}:owner`,+ `${action('DOCUMENT_COMMENT_READ')}:all`,+ `${action('DOCUMENT_COMMENT_CREATE')}:owner`,+ `${action('DOCUMENT_COMMENT_UPDATE')}:owner`,+ `${action('DOCUMENT_COMMENT_DELETE')}:all`,`${action('KNOWLEDGE_BASE_READ')}:all`,`${action('KNOWLEDGE_BASE_CREATE')}:owner`,// `:all` marks admins as knowledge-base curators: it powers the@@ -546,6 +563,10 @@ export const WORKSPACE_ROLE_PERMISSIONS: Record<WorkspaceSystemRoleName, readonl`${action('DOCUMENT_CREATE')}:owner`,`${action('DOCUMENT_UPDATE')}:owner`,`${action('DOCUMENT_DELETE')}:owner`,+ `${action('DOCUMENT_COMMENT_READ')}:all`,+ `${action('DOCUMENT_COMMENT_CREATE')}:owner`,+ `${action('DOCUMENT_COMMENT_UPDATE')}:owner`,+ `${action('DOCUMENT_COMMENT_DELETE')}:owner`,`${action('KNOWLEDGE_BASE_READ')}:all`,`${action('KNOWLEDGE_BASE_CREATE')}:owner`,`${action('KNOWLEDGE_BASE_UPDATE')}:owner`,@@ -572,6 +593,7 @@ export const WORKSPACE_ROLE_PERMISSIONS: Record<WorkspaceSystemRoleName, readonl`${action('TOPIC_COMMENT_READ')}:all`,`${action('FILE_READ')}:all`,`${action('DOCUMENT_READ')}:all`,+ `${action('DOCUMENT_COMMENT_READ')}:all`,`${action('KNOWLEDGE_BASE_READ')}:all`,`${action('AI_MODEL_READ')}:all`,`${action('AI_PROVIDER_READ')}:all`,@@ -709,6 +731,10 @@ export const PERSONAL_DEFAULT_PERMISSIONS: readonly string[] = [`${action('DOCUMENT_CREATE')}:owner`,`${action('DOCUMENT_UPDATE')}:owner`,`${action('DOCUMENT_DELETE')}:owner`,+ `${action('DOCUMENT_COMMENT_READ')}:owner`,+ `${action('DOCUMENT_COMMENT_CREATE')}:owner`,+ `${action('DOCUMENT_COMMENT_UPDATE')}:owner`,+ `${action('DOCUMENT_COMMENT_DELETE')}:owner`,`${action('KNOWLEDGE_BASE_READ')}:owner`,`${action('KNOWLEDGE_BASE_CREATE')}:owner`,`${action('KNOWLEDGE_BASE_UPDATE')}:owner`,diff --git a/packages/database/src/models/__tests__/documentComment.test.ts b/packages/database/src/models/__tests__/documentComment.test.tsnew file mode 100644index 00000000000..5bd769254da--- /dev/null+++ b/packages/database/src/models/__tests__/documentComment.test.ts@@ -0,0 +1,353 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ documentCommentMentions,+ documentComments,+ documents,+ users,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import {+ DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND,+ DOCUMENT_COMMENT_PARENT_NOT_FOUND,+ DOCUMENT_COMMENT_WORKSPACE_REQUIRED,+ DocumentCommentModel,+} from '../documentComment';++const serverDB: LobeChatDatabase = await getTestDB();++const authorId = 'document-comment-author';+const memberId = 'document-comment-member';+const outsiderId = 'document-comment-outsider';+const workspaceId = 'document-comment-workspace';+const otherWorkspaceId = 'document-comment-other-workspace';+const documentId = 'document-comment-document';+const secondDocumentId = 'document-comment-second-document';+const foreignDocumentId = 'document-comment-foreign-document';++const authorModel = new DocumentCommentModel(serverDB, authorId, workspaceId);+const memberModel = new DocumentCommentModel(serverDB, memberId, workspaceId);+const outsiderModel = new DocumentCommentModel(serverDB, outsiderId, otherWorkspaceId);++const createDocument = (id: string, userId: string, targetWorkspaceId: string | null) =>+ serverDB.insert(documents).values({+ fileType: 'custom',+ id,+ source: id,+ sourceType: 'api',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ workspaceId: targetWorkspaceId,+ });++const cleanup = async () => {+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: authorId }, { id: memberId }, { id: outsiderId }]);+ await serverDB.insert(workspaces).values([+ { id: workspaceId, name: 'Comments', primaryOwnerId: authorId, slug: workspaceId },+ {+ id: otherWorkspaceId,+ name: 'Other comments',+ primaryOwnerId: outsiderId,+ slug: otherWorkspaceId,+ },+ ]);+ await Promise.all([+ createDocument(documentId, authorId, workspaceId),+ createDocument(secondDocumentId, authorId, workspaceId),+ createDocument(foreignDocumentId, outsiderId, otherWorkspaceId),+ ]);+});++afterEach(cleanup);++describe('DocumentCommentModel', () => {+ it('requires workspace scope and stamps the document workspace on an idempotent create', async () => {+ const personalModel = new DocumentCommentModel(serverDB, authorId);+ await expect(+ personalModel.create({ clientId: 'personal', content: 'no', documentId }),+ ).rejects.toThrow(DOCUMENT_COMMENT_WORKSPACE_REQUIRED);++ const input = { clientId: 'same-request', content: 'hello', documentId };+ const first = await authorModel.create(input);+ const duplicate = await authorModel.create(input);++ expect(first.isDuplicate).toBe(false);+ expect(first.documentAuthorUserId).toBe(authorId);+ expect(first.comment).toMatchObject({+ authorUserId: authorId,+ content: 'hello',+ documentId,+ workspaceId,+ });+ expect(duplicate).toMatchObject({ isDuplicate: true, comment: { id: first.comment.id } });+ });++ it('rejects foreign parents and flattens replies to replies into the root thread', async () => {+ await expect(+ authorModel.create({ clientId: 'foreign', content: 'no', documentId: foreignDocumentId }),+ ).rejects.toThrow(DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND);++ const root = await authorModel.create({+ clientId: 'root',+ content: 'root',+ documentId,+ });+ await expect(+ authorModel.create({+ clientId: 'cross-document',+ content: 'no',+ documentId: secondDocumentId,+ parentCommentId: root.comment.id,+ }),+ ).rejects.toThrow(DOCUMENT_COMMENT_PARENT_NOT_FOUND);++ const reply = await memberModel.create({+ clientId: 'reply',+ content: 'reply',+ documentId,+ parentCommentId: root.comment.id,+ });+ const nestedReply = await authorModel.create({+ clientId: 'nested-reply',+ content: 'nested',+ documentId,+ parentCommentId: reply.comment.id,+ });++ expect(reply.comment).toMatchObject({+ parentCommentId: root.comment.id,+ replyToCommentId: null,+ });+ expect(reply.parentAuthorUserId).toBe(authorId);+ expect(nestedReply.comment).toMatchObject({+ parentCommentId: root.comment.id,+ replyToCommentId: reply.comment.id,+ });+ expect(nestedReply.parentAuthorUserId).toBe(memberId);+ expect(await authorModel.listReplies({ rootCommentId: root.comment.id })).toMatchObject({+ items: [{ id: reply.comment.id }, { id: nestedReply.comment.id }],+ total: 2,+ });++ expect(await memberModel.delete(reply.comment.id)).toBe('hard');+ expect(await authorModel.findById(nestedReply.comment.id)).toMatchObject({+ parentCommentId: root.comment.id,+ replyToCommentId: null,+ });+ });++ it('scopes updates and deletes to the author unless explicitly overridden', async () => {+ const created = await authorModel.create({+ clientId: 'owned',+ content: 'original',+ documentId,+ });++ expect(await memberModel.update(created.comment.id, { content: 'hacked' })).toBeUndefined();+ expect(await memberModel.delete(created.comment.id)).toBe(false);+ expect((await authorModel.findById(created.comment.id))?.content).toBe('original');++ expect(await memberModel.delete(created.comment.id, { overrideAuthorScope: true })).toBe(+ 'hard',+ );+ expect(await authorModel.findById(created.comment.id)).toBeUndefined();+ });++ it('persists Markdown source and Lexical JSON for rendering and future edits', async () => {+ const initialEditorData = {+ root: {+ children: [{ children: [{ format: 1, text: 'bold', type: 'text' }], type: 'paragraph' }],+ type: 'root',+ },+ };+ const created = await authorModel.create({+ clientId: 'markdown',+ content: '**bold**',+ documentId,+ editorData: initialEditorData,+ });++ expect(created.comment).toMatchObject({+ content: '**bold**',+ editorData: initialEditorData,+ });++ const nextEditorData = {+ root: {+ children: [{ children: [{ text: 'updated', type: 'text' }], type: 'paragraph' }],+ type: 'root',+ },+ };+ const updated = await authorModel.update(created.comment.id, {+ content: '[updated](https://lobehub.com)',+ editorData: nextEditorData,+ });++ expect(updated?.comment).toMatchObject({+ content: '[updated](https://lobehub.com)',+ editorData: nextEditorData,+ });+ });++ it('stores validated mentions transactionally and diffs them on update', async () => {+ const created = await authorModel.create({+ clientId: 'mentioned',+ content: 'hello @member',+ documentId,+ mentionedUserIds: [memberId, memberId],+ });+ const duplicate = await authorModel.create({+ clientId: 'mentioned',+ content: 'hello @member',+ documentId,+ mentionedUserIds: [memberId],+ });++ expect(created.addedMentionUserIds).toEqual([memberId]);+ expect(duplicate.addedMentionUserIds).toEqual([]);+ expect(+ await serverDB+ .select({ mentionedUserId: documentCommentMentions.mentionedUserId })+ .from(documentCommentMentions)+ .where(eq(documentCommentMentions.commentId, created.comment.id)),+ ).toEqual([{ mentionedUserId: memberId }]);++ const removed = await authorModel.update(+ created.comment.id,+ { content: 'mention removed' },+ { mentionedUserIds: [] },+ );+ expect(removed?.addedMentionUserIds).toEqual([]);+ expect(+ await serverDB+ .select()+ .from(documentCommentMentions)+ .where(eq(documentCommentMentions.commentId, created.comment.id)),+ ).toEqual([]);++ const addedAgain = await authorModel.update(+ created.comment.id,+ { content: 'hello again @member' },+ { mentionedUserIds: [memberId] },+ );+ expect(addedAgain?.addedMentionUserIds).toEqual([memberId]);++ await memberModel.create({+ clientId: 'mentioned-reply',+ content: 'reply',+ documentId,+ parentCommentId: created.comment.id,+ });+ expect(await authorModel.delete(created.comment.id)).toBe('soft');+ expect(+ await serverDB+ .select()+ .from(documentCommentMentions)+ .where(eq(documentCommentMentions.commentId, created.comment.id)),+ ).toEqual([]);+ });++ it('keeps a deleted root as a tombstone until its final reply is removed', async () => {+ const root = await authorModel.create({+ clientId: 'tombstone-root',+ content: 'root',+ documentId,+ });+ const reply = await memberModel.create({+ clientId: 'tombstone-reply',+ content: 'reply',+ documentId,+ parentCommentId: root.comment.id,+ });++ expect(await authorModel.delete(root.comment.id)).toBe('soft');+ expect(await authorModel.findById(root.comment.id)).toMatchObject({+ content: '',+ deletedAt: expect.any(Date),+ });+ expect(await memberModel.delete(reply.comment.id)).toBe('hard');+ expect(await authorModel.findById(root.comment.id)).toBeUndefined();+ });++ it('paginates roots and replies oldest-first and returns an active total', async () => {+ const rootRows = await serverDB+ .insert(documentComments)+ .values([+ {+ authorUserId: authorId,+ clientId: 'old',+ content: 'old',+ createdAt: new Date('2024-01-01T00:00:00Z'),+ documentId,+ workspaceId,+ },+ {+ authorUserId: authorId,+ clientId: 'new',+ content: 'new',+ createdAt: new Date('2024-01-03T00:00:00Z'),+ documentId,+ workspaceId,+ },+ ])+ .returning();+ const oldRoot = rootRows.find(({ content }) => content === 'old')!;+ await serverDB.insert(documentComments).values([+ {+ authorUserId: memberId,+ clientId: 'reply-2',+ content: 'reply 2',+ createdAt: new Date('2024-01-02T00:00:02Z'),+ documentId,+ parentCommentId: oldRoot.id,+ workspaceId,+ },+ {+ authorUserId: memberId,+ clientId: 'reply-1',+ content: 'reply 1',+ createdAt: new Date('2024-01-02T00:00:01Z'),+ documentId,+ parentCommentId: oldRoot.id,+ workspaceId,+ },+ ]);++ const firstPage = await authorModel.listThreads({ documentId, limit: 1 });+ const secondPage = await authorModel.listThreads({+ cursor: firstPage.nextCursor!,+ documentId,+ limit: 1,+ });+ expect(firstPage.items[0]).toMatchObject({ replyCount: 2, root: { content: 'old' } });+ expect(secondPage.items[0].root.content).toBe('new');++ const firstReplies = await authorModel.listReplies({ limit: 1, rootCommentId: oldRoot.id });+ const secondReplies = await authorModel.listReplies({+ cursor: firstReplies.nextCursor!,+ limit: 1,+ rootCommentId: oldRoot.id,+ });+ expect(firstReplies).toMatchObject({ items: [{ content: 'reply 1' }], total: 2 });+ expect(secondReplies.items[0].content).toBe('reply 2');+ expect(await authorModel.summary(documentId)).toEqual({ total: 4 });++ await serverDB+ .update(documentComments)+ .set({ deletedAt: new Date() })+ .where(eq(documentComments.id, oldRoot.id));+ expect(await authorModel.summary(documentId)).toEqual({ total: 3 });+ expect(await outsiderModel.summary(foreignDocumentId)).toEqual({ total: 0 });+ });+});diff --git a/packages/database/src/models/documentComment.ts b/packages/database/src/models/documentComment.tsnew file mode 100644index 00000000000..d89cd564db6--- /dev/null+++ b/packages/database/src/models/documentComment.ts@@ -0,0 +1,485 @@+import type { DocumentCommentJson } from '@lobechat/types';+import { and, asc, count, eq, getTableColumns, gt, inArray, isNull, or, sql } from 'drizzle-orm';++import type { DocumentCommentItem } from '../schemas/documentComment';+import { documentCommentMentions, documentComments } from '../schemas/documentComment';+import { documents } from '../schemas/file';+import type { LobeChatDatabase } from '../type';++export const DOCUMENT_COMMENT_WORKSPACE_REQUIRED =+ 'Document comments are workspace-scoped; a workspaceId is required';+export const DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND = 'Document not found in current workspace';+export const DOCUMENT_COMMENT_PARENT_NOT_FOUND = 'Parent comment not found in the document';++const documentCommentCursorSelection = {+ ...getTableColumns(documentComments),+ cursorCreatedAt: sql<string>`${documentComments.createdAt}::text`.as('cursor_created_at'),+};++const encodeCursor = (createdAt: string, id: string): string => `${createdAt}|${id}`;++const decodeCursor = (cursor?: string): { createdAt: string; id: string } | null => {+ if (!cursor) return null;+ const separator = cursor.lastIndexOf('|');+ if (separator <= 0) return null;+ const createdAt = cursor.slice(0, separator);+ const id = cursor.slice(separator + 1);+ if (!id || Number.isNaN(Date.parse(createdAt))) return null;+ return { createdAt, id };+};++export interface CreateDocumentCommentParams {+ clientId: string;+ content: string;+ documentId: string;+ editorData?: DocumentCommentJson;+ /** Validated active Workspace members parsed from editorData by the router. */+ mentionedUserIds?: string[];+ parentCommentId?: string;+}++export interface CreateDocumentCommentResult {+ /** Mention targets written by this create; empty for an idempotent retry. */+ addedMentionUserIds: string[];+ comment: DocumentCommentItem;+ /** Author of the document; receives activity for a new root comment. */+ documentAuthorUserId: string;+ /** true when the idempotency key already existed and no new activity should be emitted */+ isDuplicate: boolean;+ /** Author of the directly targeted comment when creating a reply. */+ parentAuthorUserId?: string | null;+}++export interface UpdateDocumentCommentParams {+ content?: string;+ editorData?: DocumentCommentJson;+}++export interface UpdateDocumentCommentOptions {+ /** Replace the persisted mention set with these validated Workspace member ids. */+ mentionedUserIds?: string[];+}++export interface UpdateDocumentCommentResult {+ /** Newly added mention targets; only these should receive a notification. */+ addedMentionUserIds: string[];+ comment: DocumentCommentItem;+}++export interface ListDocumentCommentThreadsParams {+ cursor?: string;+ documentId: string;+ limit?: number;+}++export interface ListDocumentCommentRepliesParams {+ cursor?: string;+ limit?: number;+ rootCommentId: string;+}++export class DocumentCommentModel {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly workspaceId?: string | null;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string | null) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private requireWorkspaceId = (): string => {+ if (!this.workspaceId) throw new Error(DOCUMENT_COMMENT_WORKSPACE_REQUIRED);+ return this.workspaceId;+ };++ async create(params: CreateDocumentCommentParams): Promise<CreateDocumentCommentResult> {+ const workspaceId = this.requireWorkspaceId();++ return this.db.transaction(async (tx) => {+ const [document] = await tx+ .select({ id: documents.id, userId: documents.userId, workspaceId: documents.workspaceId })+ .from(documents)+ .where(eq(documents.id, params.documentId))+ .limit(1)+ .for('update');++ if (!document || document.workspaceId !== workspaceId) {+ throw new Error(DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND);+ }++ let parentCommentId: string | null = null;+ let parentAuthorUserId: string | null | undefined;+ let replyToCommentId: string | null = null;+ if (params.parentCommentId) {+ const [parent] = await tx+ .select({+ authorUserId: documentComments.authorUserId,+ documentId: documentComments.documentId,+ id: documentComments.id,+ parentCommentId: documentComments.parentCommentId,+ workspaceId: documentComments.workspaceId,+ })+ .from(documentComments)+ .where(eq(documentComments.id, params.parentCommentId))+ .limit(1)+ .for('key share');++ if (+ !parent ||+ parent.documentId !== params.documentId ||+ parent.workspaceId !== workspaceId+ ) {+ throw new Error(DOCUMENT_COMMENT_PARENT_NOT_FOUND);+ }+ parentAuthorUserId = parent.authorUserId;+ parentCommentId = parent.parentCommentId ?? parent.id;+ replyToCommentId = parent.parentCommentId ? parent.id : null;+ }++ const [inserted] = await tx+ .insert(documentComments)+ .values({+ authorUserId: this.userId,+ clientId: params.clientId,+ content: params.content,+ documentId: params.documentId,+ editorData: params.editorData,+ parentCommentId,+ replyToCommentId,+ workspaceId,+ })+ .onConflictDoNothing({+ target: [+ documentComments.documentId,+ documentComments.authorUserId,+ documentComments.clientId,+ ],+ })+ .returning();++ if (inserted) {+ const mentionedUserIds = [...new Set(params.mentionedUserIds ?? [])];+ if (mentionedUserIds.length > 0) {+ await tx+ .insert(documentCommentMentions)+ .values(+ mentionedUserIds.map((mentionedUserId) => ({+ commentId: inserted.id,+ mentionedUserId,+ workspaceId,+ })),+ )+ .onConflictDoNothing();+ }++ return {+ addedMentionUserIds: mentionedUserIds,+ comment: inserted,+ documentAuthorUserId: document.userId,+ isDuplicate: false,+ parentAuthorUserId,+ };+ }++ const [existing] = await tx+ .select()+ .from(documentComments)+ .where(+ and(+ eq(documentComments.documentId, params.documentId),+ eq(documentComments.workspaceId, workspaceId),+ eq(documentComments.authorUserId, this.userId),+ eq(documentComments.clientId, params.clientId),+ ),+ )+ .limit(1);+ if (!existing) throw new Error('Failed to create document comment');+ return {+ addedMentionUserIds: [],+ comment: existing,+ documentAuthorUserId: document.userId,+ isDuplicate: true,+ parentAuthorUserId,+ };+ });+ }++ async update(+ id: string,+ params: UpdateDocumentCommentParams,+ options: UpdateDocumentCommentOptions = {},+ ): Promise<UpdateDocumentCommentResult | undefined> {+ const workspaceId = this.requireWorkspaceId();+ return this.db.transaction(async (tx) => {+ const [comment] = await tx+ .update(documentComments)+ .set({+ ...(params.content === undefined ? {} : { content: params.content }),+ ...(params.editorData === undefined ? {} : { editorData: params.editorData }),+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(documentComments.id, id),+ eq(documentComments.workspaceId, workspaceId),+ eq(documentComments.authorUserId, this.userId),+ isNull(documentComments.deletedAt),+ ),+ )+ .returning();+ if (!comment) return undefined;++ let addedMentionUserIds: string[] = [];+ if (options.mentionedUserIds) {+ const next = [...new Set(options.mentionedUserIds)];+ const existingRows = await tx+ .select({ mentionedUserId: documentCommentMentions.mentionedUserId })+ .from(documentCommentMentions)+ .where(eq(documentCommentMentions.commentId, id));+ const existing = new Set(existingRows.map(({ mentionedUserId }) => mentionedUserId));+ addedMentionUserIds = next.filter((userId) => !existing.has(userId));+ const removedMentionUserIds = [...existing].filter((userId) => !next.includes(userId));++ if (addedMentionUserIds.length > 0) {+ await tx+ .insert(documentCommentMentions)+ .values(+ addedMentionUserIds.map((mentionedUserId) => ({+ commentId: id,+ mentionedUserId,+ workspaceId,+ })),+ )+ .onConflictDoNothing();+ }+ if (removedMentionUserIds.length > 0) {+ await tx+ .delete(documentCommentMentions)+ .where(+ and(+ eq(documentCommentMentions.commentId, id),+ inArray(documentCommentMentions.mentionedUserId, removedMentionUserIds),+ ),+ );+ }+ }++ return { addedMentionUserIds, comment };+ });+ }++ async delete(id: string, options: { overrideAuthorScope?: boolean } = {}) {+ const workspaceId = this.requireWorkspaceId();++ return this.db.transaction(async (tx) => {+ const conditions = [+ eq(documentComments.id, id),+ eq(documentComments.workspaceId, workspaceId),+ ];+ if (!options.overrideAuthorScope) {+ conditions.push(eq(documentComments.authorUserId, this.userId));+ }++ const [candidate] = await tx+ .select({ id: documentComments.id, parentCommentId: documentComments.parentCommentId })+ .from(documentComments)+ .where(and(...conditions))+ .limit(1);+ if (!candidate) return false;++ const rootId = candidate.parentCommentId ?? candidate.id;+ const [root] = await tx+ .select({ id: documentComments.id })+ .from(documentComments)+ .where(+ and(+ eq(documentComments.id, rootId),+ eq(documentComments.workspaceId, workspaceId),+ isNull(documentComments.parentCommentId),+ ),+ )+ .for('update');+ if (!root) return false;++ const [comment] = await tx+ .select({+ deletedAt: documentComments.deletedAt,+ id: documentComments.id,+ parentCommentId: documentComments.parentCommentId,+ })+ .from(documentComments)+ .where(and(...conditions))+ .limit(1);+ if (!comment || comment.deletedAt) return false;++ const [replyCount] = await tx+ .select({ total: count() })+ .from(documentComments)+ .where(eq(documentComments.parentCommentId, id));++ if ((replyCount?.total ?? 0) > 0) {+ await tx.delete(documentCommentMentions).where(eq(documentCommentMentions.commentId, id));+ await tx+ .update(documentComments)+ .set({ content: '', deletedAt: new Date(), editorData: null, updatedAt: new Date() })+ .where(eq(documentComments.id, id));+ return 'soft' as const;+ }++ await tx.delete(documentComments).where(eq(documentComments.id, id));++ if (comment.parentCommentId) {+ const [parent] = await tx+ .select({ deletedAt: documentComments.deletedAt, id: documentComments.id })+ .from(documentComments)+ .where(eq(documentComments.id, comment.parentCommentId))+ .limit(1);+ if (parent?.deletedAt) {+ const [siblings] = await tx+ .select({ total: count() })+ .from(documentComments)+ .where(eq(documentComments.parentCommentId, parent.id));+ if ((siblings?.total ?? 0) === 0) {+ await tx.delete(documentComments).where(eq(documentComments.id, parent.id));+ }+ }+ }++ return 'hard' as const;+ });+ }++ async findById(id: string) {+ const workspaceId = this.requireWorkspaceId();+ const [comment] = await this.db+ .select()+ .from(documentComments)+ .where(and(eq(documentComments.id, id), eq(documentComments.workspaceId, workspaceId)))+ .limit(1);+ return comment;+ }++ async listThreads(params: ListDocumentCommentThreadsParams) {+ const workspaceId = this.requireWorkspaceId();+ const { cursor, documentId, limit = 20 } = params;+ const conditions = [+ eq(documentComments.documentId, documentId),+ eq(documentComments.workspaceId, workspaceId),+ isNull(documentComments.parentCommentId),+ ];+ const decodedCursor = decodeCursor(cursor);+ if (decodedCursor) {+ const createdAt = sql`${decodedCursor.createdAt}::timestamptz`;+ conditions.push(+ or(+ gt(documentComments.createdAt, createdAt),+ and(eq(documentComments.createdAt, createdAt), gt(documentComments.id, decodedCursor.id)),+ )!,+ );+ }++ const rows = await this.db+ .select(documentCommentCursorSelection)+ .from(documentComments)+ .where(and(...conditions))+ .orderBy(asc(documentComments.createdAt), asc(documentComments.id))+ .limit(limit + 1);+ const hasMore = rows.length > limit;+ const pageRows = hasMore ? rows.slice(0, limit) : rows;+ const roots = pageRows.map(({ cursorCreatedAt: _cursorCreatedAt, ...root }) => root);+ const rootIds = roots.map(({ id }) => id);+ const replyCounts = rootIds.length+ ? await this.db+ .select({ parentCommentId: documentComments.parentCommentId, total: count() })+ .from(documentComments)+ .where(+ and(+ eq(documentComments.workspaceId, workspaceId),+ inArray(documentComments.parentCommentId, rootIds),+ isNull(documentComments.deletedAt),+ ),+ )+ .groupBy(documentComments.parentCommentId)+ : [];+ const countByRoot = new Map(+ replyCounts.flatMap(({ parentCommentId, total }) =>+ parentCommentId ? [[parentCommentId, total] as const] : [],+ ),+ );++ return {+ items: roots.map((root) => ({ replyCount: countByRoot.get(root.id) ?? 0, root })),+ nextCursor: hasMore+ ? encodeCursor(pageRows.at(-1)!.cursorCreatedAt, pageRows.at(-1)!.id)+ : null,+ };+ }++ async listReplies(params: ListDocumentCommentRepliesParams) {+ const workspaceId = this.requireWorkspaceId();+ const { cursor, limit = 50, rootCommentId } = params;+ const conditions = [+ eq(documentComments.parentCommentId, rootCommentId),+ eq(documentComments.workspaceId, workspaceId),+ ];+ const decodedCursor = decodeCursor(cursor);+ if (decodedCursor) {+ const createdAt = sql`${decodedCursor.createdAt}::timestamptz`;+ conditions.push(+ or(+ gt(documentComments.createdAt, createdAt),+ and(eq(documentComments.createdAt, createdAt), gt(documentComments.id, decodedCursor.id)),+ )!,+ );+ }++ const [rows, total] = await Promise.all([+ this.db+ .select(documentCommentCursorSelection)+ .from(documentComments)+ .where(and(...conditions))+ .orderBy(asc(documentComments.createdAt), asc(documentComments.id))+ .limit(limit + 1),+ decodedCursor+ ? Promise.resolve(undefined)+ : this.db+ .select({ total: count() })+ .from(documentComments)+ .where(+ and(+ eq(documentComments.parentCommentId, rootCommentId),+ eq(documentComments.workspaceId, workspaceId),+ isNull(documentComments.deletedAt),+ ),+ )+ .then(([row]) => row.total),+ ]);+ const hasMore = rows.length > limit;+ const pageRows = hasMore ? rows.slice(0, limit) : rows;++ return {+ items: pageRows.map(({ cursorCreatedAt: _cursorCreatedAt, ...item }) => item),+ nextCursor: hasMore+ ? encodeCursor(pageRows.at(-1)!.cursorCreatedAt, pageRows.at(-1)!.id)+ : null,+ ...(total === undefined ? {} : { total }),+ };+ }++ async summary(documentId: string) {+ const workspaceId = this.requireWorkspaceId();+ const [row] = await this.db+ .select({ total: count() })+ .from(documentComments)+ .where(+ and(+ eq(documentComments.documentId, documentId),+ eq(documentComments.workspaceId, workspaceId),+ isNull(documentComments.deletedAt),+ ),+ );+ return { total: row?.total ?? 0 };+ }+}diff --git a/packages/database/src/schemas/documentComment.ts b/packages/database/src/schemas/documentComment.tsindex 576b3be8f02..5451a5f6a8d 100644--- a/packages/database/src/schemas/documentComment.ts+++ b/packages/database/src/schemas/documentComment.ts@@ -1,3 +1,4 @@+import type { DocumentCommentJson } from '@lobechat/types';import type { AnyPgColumn } from 'drizzle-orm/pg-core';import { index, jsonb, pgTable, text, uniqueIndex, uuid } from 'drizzle-orm/pg-core';@@ -31,7 +32,7 @@ export const documentComments = pgTable(.references(() => workspaces.id, { onDelete: 'cascade' }).notNull(),content: text('content').notNull(),- editorData: jsonb('editor_data'),+ editorData: jsonb('editor_data').$type<DocumentCommentJson>(),/** Client-generated idempotency key for retried creates. */clientId: text('client_id').notNull(),/** Tombstone retained only while a deleted root still has replies. */diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex bd5ce8566fd..1decd507e55 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -104,6 +104,34 @@ export default {'pageEditor.addIcon': 'Add Icon','pageEditor.autoSaveMessage': 'Your page is saved automatically. No need to save manually.','pageEditor.chooseIcon': 'Choose Icon',+ 'pageEditor.comments.author.deactivated': 'Deactivated user',+ 'pageEditor.comments.author.former': 'Former member',+ 'pageEditor.comments.attachments.add': 'Add',+ 'pageEditor.comments.attachments.chooseLibrary': 'Choose from Library',+ 'pageEditor.comments.cancel': 'Cancel',+ 'pageEditor.comments.createFailed': 'Failed to publish comment. Your draft is still here.',+ 'pageEditor.comments.delete': 'Delete',+ 'pageEditor.comments.deleteConfirm.content':+ 'Delete this comment? Replies will remain visible if this comment has a thread.',+ 'pageEditor.comments.deleteConfirm.title': 'Delete comment',+ 'pageEditor.comments.deleteFailed': 'Failed to delete comment. Try again.',+ 'pageEditor.comments.deleted': 'This comment was deleted.',+ 'pageEditor.comments.edit': 'Edit',+ 'pageEditor.comments.edited': '(edited)',+ 'pageEditor.comments.empty': 'No comments yet. Start the conversation below.',+ 'pageEditor.comments.hideReplies': 'Hide replies',+ 'pageEditor.comments.loadMore': 'Load more comments',+ 'pageEditor.comments.loadMoreReplies': 'Load more replies',+ 'pageEditor.comments.moreActions': 'More actions',+ 'pageEditor.comments.placeholder': 'Add a comment…',+ 'pageEditor.comments.publish': 'Comment',+ 'pageEditor.comments.replies_one': '{{count}} reply',+ 'pageEditor.comments.replies_other': '{{count}} replies',+ 'pageEditor.comments.replyAction': 'Reply',+ 'pageEditor.comments.replyPlaceholder': 'Write a reply…',+ 'pageEditor.comments.save': 'Save',+ 'pageEditor.comments.title': 'Comments',+ 'pageEditor.comments.updateFailed': 'Failed to update comment. Try again.','pageEditor.deleteConfirm.content':'This page will be deleted and cannot be recovered. Please proceed with caution.','pageEditor.deleteConfirm.title': 'Delete Page',diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.tsindex 514adf646f2..ee096d610c2 100644--- a/packages/locales/src/default/notification.ts+++ b/packages/locales/src/default/notification.ts@@ -88,6 +88,13 @@ export default {'storage_overage_cap_reached':'Your storage pay-as-you-go monthly cap of ${{monthlyCap}} has been reached. Estimated charges this cycle are ${{estimatedCycleCharge}}. New uploads beyond your included storage will be blocked until the next billing cycle or until you increase the cap.','storage_overage_cap_reached_title': 'Storage pay-as-you-go cap reached',+ 'document_comment_activity': '{{actorLabel}} commented on your document "{{documentTitle}}".',+ 'document_comment_activity_replied':+ '{{actorLabel}} replied to your comment in "{{documentTitle}}".',+ 'document_comment_activity_replied_title': 'New reply to your comment',+ 'document_comment_activity_title': 'New comment on your document',+ 'document_comment_mentioned': '{{actorLabel}} mentioned you in a comment on "{{documentTitle}}".',+ 'document_comment_mentioned_title': 'You were mentioned in a document comment','subscription_payment_failed':'Your subscription renewal payment failed. Please update your payment method to keep your subscription active.','subscription_payment_failed_action': 'Update payment method',diff --git a/packages/types/src/documentComment.ts b/packages/types/src/documentComment.tsnew file mode 100644index 00000000000..937dacd0b24--- /dev/null+++ b/packages/types/src/documentComment.ts@@ -0,0 +1,65 @@+export type DocumentCommentAuthorStatus = 'active' | 'deactivated' | 'former';++export type DocumentCommentJson =+ boolean | number | string | null | DocumentCommentJson[] | { [key: string]: DocumentCommentJson };++export interface DocumentCommentAuthor {+ avatar: string | null;+ fullName: string | null;+ id: string | null;+ status: DocumentCommentAuthorStatus;+ username: string | null;+}++export interface DocumentCommentItem {+ author: DocumentCommentAuthor;+ authorUserId: string | null;+ canDelete: boolean;+ canEdit: boolean;+ clientId: string;+ content: string;+ createdAt: Date;+ deletedAt: Date | null;+ documentId: string;+ editorData: DocumentCommentJson | null;+ id: string;+ parentCommentId: string | null;+ replyTo: { author: DocumentCommentAuthor; id: string } | null;+ replyToCommentId: string | null;+ updatedAt: Date;+ workspaceId: string;+}++export interface DocumentCommentThread {+ replyCount: number;+ root: DocumentCommentItem;+}++export interface DocumentCommentThreadPage {+ items: DocumentCommentThread[];+ nextCursor: string | null;+}++export interface DocumentCommentReplyPage {+ items: DocumentCommentItem[];+ nextCursor: string | null;+ total?: number;+}++export interface DocumentCommentSummary {+ total: number;+}++export interface CreateDocumentCommentInput {+ clientId: string;+ content: string;+ documentId: string;+ editorData?: DocumentCommentJson;+ parentCommentId?: string;+}++export interface UpdateDocumentCommentInput {+ content?: string;+ editorData?: DocumentCommentJson;+ id: string;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 567ed76f78f..c4dd1dbefd0 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -17,6 +17,7 @@ export * from './creds';export * from './device';export * from './discover';export * from './document';+export * from './documentComment';export * from './entityId';export * from './eval';export * from './expertise';diff --git a/src/business/server/document-comment/notifyActivity.ts b/src/business/server/document-comment/notifyActivity.tsnew file mode 100644index 00000000000..df845d0f7c1--- /dev/null+++ b/src/business/server/document-comment/notifyActivity.ts@@ -0,0 +1,15 @@+export type DocumentCommentActivityKind = 'commented' | 'mentioned' | 'replied';++export interface NotifyDocumentCommentActivityParams {+ actorUserId: string;+ commentId: string;+ documentId: string;+ kind: DocumentCommentActivityKind;+ recipientUserId: string;+ rootCommentId: string;+ workspaceId: string;+}++export const notifyDocumentCommentActivity = (+ _params: NotifyDocumentCommentActivityParams,+): Promise<void> => Promise.resolve();diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsxindex 8fb19556fa2..5cf300e1124 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx@@ -18,7 +18,6 @@ const topicMetaCardMock = vi.hoisted(() => ({}));vi.mock('@lobehub/ui', () => ({- ContextMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (<div {...props}>{children}</div>),diff --git a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsxindex 1295f861553..fe667eeb994 100644--- a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx+++ b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx@@ -33,6 +33,9 @@ vi.mock('@lobehub/ui', () => ({</div>),Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));++vi.mock('@lobehub/ui/base-ui', () => ({Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,}));diff --git a/src/features/AttachmentInput/AttachmentMenu.tsx b/src/features/AttachmentInput/AttachmentMenu.tsxnew file mode 100644index 00000000000..dbe41466987--- /dev/null+++ b/src/features/AttachmentInput/AttachmentMenu.tsx@@ -0,0 +1,113 @@+'use client';++import { Icon } from '@lobehub/ui';+import { ActionIcon } from '@lobehub/ui/base-ui';+import { Upload } from 'antd';+import { css, cx } from 'antd-style';+import { ChevronRight, FileUp, LibraryBig, PlusIcon, TypeIcon } from 'lucide-react';+import { memo, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { ExistingEditorAttachment } from '@/features/EditorCanvas/editorAttachments';+import { openLibraryFilePicker } from '@/features/LibraryModal';++import ActionDropdown, {+ type ActionDropdownMenuItems,+} from '../ChatInput/ActionBar/components/ActionDropdown';++const hotArea = css`+ &::before {+ content: '';+ position: absolute;+ inset: 0;+ background: transparent;+ }+`;++interface AttachmentMenuProps {+ disabled?: boolean;+ formatEnabled: boolean;+ onFiles: (files: File[]) => void | Promise<void>;+ onFormatEnabledChange: (enabled: boolean) => void;+ onLibraryFiles: (attachments: ExistingEditorAttachment[]) => void;+}++const AttachmentMenu = memo<AttachmentMenuProps>(+ ({ disabled, formatEnabled, onFiles, onFormatEnabledChange, onLibraryFiles }) => {+ const { t } = useTranslation(['chat', 'editor', 'file']);+ const [open, setOpen] = useState(false);++ const items = useMemo<ActionDropdownMenuItems>(+ () => [+ {+ children: [+ {+ closeOnClick: false,+ icon: <Icon icon={FileUp} size={18} />,+ key: 'upload',+ label: (+ <Upload+ multiple+ showUploadList={false}+ beforeUpload={(file, fileList) => {+ if (file === fileList.at(-1)) {+ setOpen(false);+ void onFiles(fileList);+ }+ return false;+ }}+ >+ <div className={cx(hotArea)}>+ {t('upload.action.fileOrImageUpload', { ns: 'chat' })}+ </div>+ </Upload>+ ),+ },+ {+ icon: <Icon icon={LibraryBig} size={18} />,+ key: 'library',+ label: t('pageEditor.comments.attachments.chooseLibrary', { ns: 'file' }),+ onClick: () => {+ setOpen(false);+ openLibraryFilePicker(onLibraryFiles);+ },+ },+ ],+ extra: <Icon className={'lobe-submenu-chevron'} icon={ChevronRight} size={16} />,+ icon: LibraryBig,+ key: 'attachments',+ label: t('plus.addAttachments', { ns: 'chat' }),+ },+ { type: 'divider' },+ {+ checked: formatEnabled,+ icon: TypeIcon,+ key: 'formatting',+ label: t('actions.typobar.title', { ns: 'editor' }),+ onCheckedChange: onFormatEnabledChange,+ type: 'switch',+ },+ ],+ [formatEnabled, onFiles, onFormatEnabledChange, onLibraryFiles, t],+ );++ const title = t('pageEditor.comments.attachments.add', { ns: 'file' });++ return (+ <ActionDropdown menu={{ items }} open={open} placement={'topLeft'} onOpenChange={setOpen}>+ <ActionIcon+ aria-label={title}+ disabled={disabled}+ icon={PlusIcon}+ size={{ blockSize: 32, size: 18 }}+ title={title}+ onClick={() => setOpen(true)}+ />+ </ActionDropdown>+ );+ },+);++AttachmentMenu.displayName = 'AttachmentMenu';++export default AttachmentMenu;diff --git a/src/features/AttachmentInput/index.ts b/src/features/AttachmentInput/index.tsindex 9dfc369be52..59e4be05975 100644--- a/src/features/AttachmentInput/index.ts+++ b/src/features/AttachmentInput/index.ts@@ -1 +1,2 @@+export { default as AttachmentMenu } from './AttachmentMenu';export { default as AttachmentUploadButton } from './AttachmentUploadButton';diff --git a/src/features/ChatInput/TypoBar/index.tsx b/src/features/ChatInput/TypoBar/index.tsxindex 248165c112f..4ad344bec64 100644--- a/src/features/ChatInput/TypoBar/index.tsx+++ b/src/features/ChatInput/TypoBar/index.tsx@@ -1,136 +1,13 @@-import { getHotkeyById, HotkeyEnum } from '@lobehub/editor';-import { type ChatInputActionsProps } from '@lobehub/editor/react';-import { ChatInputActionBar, ChatInputActions, useEditorState } from '@lobehub/editor/react';-import { cssVar } from 'antd-style';-import {- BoldIcon,- CodeXmlIcon,- ItalicIcon,- ListIcon,- ListOrderedIcon,- ListTodoIcon,- MessageSquareQuote,- SigmaIcon,- SquareDashedBottomCodeIcon,- StrikethroughIcon,- UnderlineIcon,-} from 'lucide-react';-import { memo, useMemo } from 'react';-import { useTranslation } from 'react-i18next';+import { memo } from 'react';-import { useChatInputStore } from '@/features/ChatInput/store';+import { TypoBar as EditorTypoBar } from '@/features/EditorCanvas/TypoBar';++import { useChatInputStore } from '../store';const TypoBar = memo(() => {- const { t } = useTranslation('editor');const editor = useChatInputStore((s) => s.editor);- const editorState = useEditorState(editor);-- const items: ChatInputActionsProps['items'] = useMemo(- () =>- [- {- active: editorState.isBold,- icon: BoldIcon,- key: 'bold',- label: t('typobar.bold'),- onClick: editorState.bold,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Bold).keys },- },- {- active: editorState.isItalic,- icon: ItalicIcon,- key: 'italic',- label: t('typobar.italic'),- onClick: editorState.italic,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Italic).keys },- },- {- active: editorState.isUnderline,- icon: UnderlineIcon,- key: 'underline',- label: t('typobar.underline'),- onClick: editorState.underline,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Underline).keys },- },- {- active: editorState.isStrikethrough,- icon: StrikethroughIcon,- key: 'strikethrough',- label: t('typobar.strikethrough'),- onClick: editorState.strikethrough,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },- },- {- type: 'divider',- },-- {- icon: ListIcon,- key: 'bulletList',- label: t('typobar.bulletList'),- onClick: editorState.bulletList,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.BulletList).keys },- },- {- icon: ListOrderedIcon,- key: 'numberlist',- label: t('typobar.numberList'),- onClick: editorState.numberList,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.NumberList).keys },- },- {- icon: ListTodoIcon,- key: 'tasklist',- label: t('typobar.taskList'),- onClick: editorState.checkList,- },- {- type: 'divider',- },- {- active: editorState.isBlockquote,- icon: MessageSquareQuote,- key: 'blockquote',- label: t('typobar.blockquote'),- onClick: editorState.blockquote,- },- {- type: 'divider',- },- {- icon: SigmaIcon,- key: 'math',- label: t('typobar.tex'),- onClick: editorState.insertMath,- },- {- active: editorState.isCode,- icon: CodeXmlIcon,- key: 'code',- label: t('typobar.code'),- onClick: editorState.code,- tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.CodeInline).keys },- },- {- icon: SquareDashedBottomCodeIcon,- key: 'codeblock',- label: t('typobar.codeblock'),- onClick: editorState.codeblock,- },- ].filter(Boolean) as ChatInputActionsProps['items'],- [editorState],- );- return (- <ChatInputActionBar- left={<ChatInputActions items={items} />}- style={{- background: cssVar.colorFillQuaternary,- borderTopLeftRadius: 8,- borderTopRightRadius: 8,- }}- />- );+ return <EditorTypoBar editor={editor} />;});TypoBar.displayName = 'TypoBar';diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsxindex aa5d7fdbaef..dd26d485fac 100644--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx@@ -7,6 +7,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import Render from './index';+vi.mock('@lobehub/ui/base-ui', () => ({+ ActionIcon: ({ icon: _icon, onClick, title, ...rest }: any) => (+ <button {...rest} aria-label={title} type="button" onClick={onClick} />+ ),+}));+let mockIsDesktop = false;vi.mock('@lobechat/const', async (importOriginal) => ({diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsxindex e373534a56d..bf81ed42870 100644--- a/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx@@ -67,6 +67,20 @@ afterEach(() => {});describe('RichTextMessage', () => {+ it('should allow document comments to use the default 16px renderer scale', async () => {+ const { container } = render(+ <RichTextMessage editorState={mentionEditorState} variant={'default'} />,+ );++ await act(async () => {+ await moment();+ });++ expect(+ (container.firstElementChild as HTMLElement).style.getPropertyValue('--common-font-size'),+ ).toBe('16px');+ });+it('should render mention nodes from editor state', async () => {const { container } = render(<RichTextMessage editorState={mentionEditorState} />);diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.tsxindex d14e28c25f5..25160618d1b 100644--- a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.tsx@@ -10,13 +10,14 @@ import { ReferTopicNode } from '@/features/ChatInput/InputEditor/ReferTopic/Refeinterface RichTextMessageProps {editorState: unknown;+ variant?: 'chat' | 'default';}const LINE_HEIGHT = 1.6;const style: CSSProperties = { '--common-line-height': LINE_HEIGHT } as CSSProperties;const EXTRA_NODES = [ActionTagNode, ReferTopicNode, LocalFileTagNode];-const RichTextMessage = memo<RichTextMessageProps>(({ editorState }) => {+const RichTextMessage = memo<RichTextMessageProps>(({ editorState, variant = 'chat' }) => {const value = useMemo(() => {if (!editorState || typeof editorState !== 'object') return null;if (Object.keys(editorState as Record<string, unknown>).length === 0) return null;@@ -31,7 +32,7 @@ const RichTextMessage = memo<RichTextMessageProps>(({ editorState }) => {extraNodes={EXTRA_NODES}style={style}value={value}- variant="chat"+ variant={variant}/>);});diff --git a/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx b/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsxindex cddbc1f1d69..ef99b4bc488 100644--- a/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx+++ b/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx@@ -30,6 +30,14 @@ vi.mock('@/components/AntdStaticMethods', () => ({message: { error: vi.fn(), success: vi.fn() },}));+vi.mock('@lobehub/ui/base-ui', () => ({+ ActionIcon: ({ onClick, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button type="button" {...props} onClick={onClick} />+ ),+ confirmModal: vi.fn(),+ toast: { error: vi.fn(), success: vi.fn() },+}));+vi.mock('@/services/git', () => ({gitService: { revertGitFile: vi.fn() },}));diff --git a/src/features/EditorCanvas/EditorCanvas.test.tsx b/src/features/EditorCanvas/EditorCanvas.test.tsxindex ddfe78800c5..a9658fa3064 100644--- a/src/features/EditorCanvas/EditorCanvas.test.tsx+++ b/src/features/EditorCanvas/EditorCanvas.test.tsx@@ -137,12 +137,17 @@ describe('EditorCanvas', () => {const onContentChange = vi.fn();const onInit = vi.fn();const editorData = { content: 'test', editorData: { blocks: [] } };+ const mentionOption = { items: [] };+ const getPopupContainer = vi.fn(() => null);render(<EditorCanvascontentRevision={3}+ contentStyle={{ minHeight: 44, padding: 0 }}editor={mockEditor}editorData={editorData}+ getPopupContainer={getPopupContainer}+ mentionOption={mentionOption}placeholder="Custom placeholder"onContentChange={onContentChange}onInit={onInit}@@ -154,8 +159,11 @@ describe('EditorCanvas', () => {expect(lastCall?.[0]).toMatchObject({contentRevision: 3,+ contentStyle: { minHeight: 44, padding: 0 },editor: mockEditor,editorData,+ getPopupContainer,+ mentionOption,onContentChange,onInit,placeholder: 'Custom placeholder',@@ -225,11 +233,13 @@ describe('EditorCanvas', () => {it('should forward props to InternalEditor in basic mode', async () => {const onContentChange = vi.fn();const onInit = vi.fn();+ const mentionOption = { items: [] };render(<EditorCanvaseditor={mockEditor}floatingToolbar={false}+ mentionOption={mentionOption}placeholder="Custom placeholder"onContentChange={onContentChange}onInit={onInit}@@ -242,6 +252,7 @@ describe('EditorCanvas', () => {expect(lastCall?.[0]).toMatchObject({editor: mockEditor,floatingToolbar: false,+ mentionOption,onContentChange,onInit,placeholder: 'Custom placeholder',diff --git a/src/features/EditorCanvas/EditorCanvas.tsx b/src/features/EditorCanvas/EditorCanvas.tsxindex 3a2427154ec..33d87ed7b1d 100644--- a/src/features/EditorCanvas/EditorCanvas.tsx+++ b/src/features/EditorCanvas/EditorCanvas.tsx@@ -1,7 +1,7 @@'use client';import { type IEditor, type SlashOptions } from '@lobehub/editor';-import { type ChatInputActionsProps, type Editor } from '@lobehub/editor/react';+import type { ChatInputActionsProps, Editor, EditorProps } from '@lobehub/editor/react';import { type CSSProperties } from 'react';import { memo } from 'react';@@ -49,6 +49,9 @@ export interface EditorCanvasProps {*/contentRevision?: number;+ /** Styles applied to the editable content instead of the outer data-mode wrapper. */+ contentStyle?: CSSProperties;+disabled?: boolean;/**@@ -91,6 +94,12 @@ export interface EditorCanvasProps {*/floatingToolbar?: boolean;+ /** Resolve the portal host used by slash and mention menus. */+ getPopupContainer?: EditorProps['getPopupContainer'];++ /** Structured @mention configuration forwarded to the editor. */+ mentionOption?: EditorProps['mentionOption'];+/*** Content change handler*/diff --git a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx b/src/features/EditorCanvas/InternalEditor.readonly.test.tsxindex f1a97de6c5e..78453f981c1 100644--- a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx+++ b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx@@ -10,6 +10,12 @@ import { createEditorFileUploadTracker } from './editorFileUploadTracker';import InternalEditor from './InternalEditor';import { LinearFileCard } from './LinearFilePlugin';+vi.mock('@lobehub/ui/base-ui', () => ({+ ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (+ <button aria-label={title} type="button" onClick={onClick} />+ ),+}));+const editorProps = vi.hoisted(() => ({last: undefined as any,}));diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsxindex 7fcef13820e..aae4464a000 100644--- a/src/features/EditorCanvas/InternalEditor.tsx+++ b/src/features/EditorCanvas/InternalEditor.tsx@@ -99,11 +99,14 @@ export interface InternalEditorProps extends EditorCanvasProps {const InternalEditor = memo<InternalEditorProps>(({contentChangeLockRef,+ contentStyle,disabled,editable = true,editor,extraPlugins,floatingToolbar = true,+ getPopupContainer,+ mentionOption,onContentChange,onInit,onPressEnter,@@ -313,6 +316,8 @@ const InternalEditor = memo<InternalEditorProps>(content={''}editable={editable && !disabled}editor={editor}+ getPopupContainer={getPopupContainer}+ mentionOption={mentionOption}placeholder={finalPlaceholder}plugins={plugins}slashOption={slashItems ? { items: slashItems } : undefined}@@ -320,6 +325,7 @@ const InternalEditor = memo<InternalEditorProps>(style={{paddingBottom: 32,...style,+ ...contentStyle,}}{...(onPressEnter ? { onPressEnter } : {})}/>diff --git a/src/features/EditorCanvas/LinearFilePlugin.tsx b/src/features/EditorCanvas/LinearFilePlugin.tsxindex 9e90c2f597e..4fd71ceb610 100644--- a/src/features/EditorCanvas/LinearFilePlugin.tsx+++ b/src/features/EditorCanvas/LinearFilePlugin.tsx@@ -18,6 +18,7 @@ import { useTranslation } from 'react-i18next';import FileIcon from '@/components/FileIcon';import { formatSize, formatSpeed, formatTime } from '@/utils/format';+import { preserveInsertedFileSize } from './editorAttachments';import type { EditorFileUploadTracker } from './editorFileUploadTracker';import { createEditorFileUploadTracker } from './editorFileUploadTracker';import { openFileDownload } from './fileDownload';@@ -284,6 +285,7 @@ const LinearFilePlugin: FC<LinearFilePluginProps> = ({ handleUpload, theme }) =>const uploadTracker = uploadTrackerRef.current;const trackedHandleUpload = useCallback<EditorAttachmentUpload>(async (file) => {+ preserveInsertedFileSize(file);const uploadId = uploadTracker.start(file);try {diff --git a/src/features/EditorModal/Typobar.tsx b/src/features/EditorCanvas/TypoBar.tsxsimilarity index 88%rename from src/features/EditorModal/Typobar.tsxrename to src/features/EditorCanvas/TypoBar.tsxindex 3b45b0f73f9..c19b1db05fd 100644--- a/src/features/EditorModal/Typobar.tsx+++ b/src/features/EditorCanvas/TypoBar.tsx@@ -1,6 +1,6 @@-import { type IEditor } from '@lobehub/editor';+import type { IEditor } from '@lobehub/editor';import { getHotkeyById, HotkeyEnum } from '@lobehub/editor';-import { type ChatInputActionsProps } from '@lobehub/editor/react';+import type { ChatInputActionsProps } from '@lobehub/editor/react';import { ChatInputActionBar, ChatInputActions, useEditorState } from '@lobehub/editor/react';import { cssVar } from 'antd-style';import {@@ -19,7 +19,12 @@ import {import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';-const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {+interface TypoBarProps {+ editor?: IEditor;+}++/** Shared fixed Markdown toolbar for ChatInput-based editors. */+export const TypoBar = memo<TypoBarProps>(({ editor }) => {const { t } = useTranslation('editor');const editorState = useEditorState(editor);@@ -58,10 +63,7 @@ const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {onClick: editorState.strikethrough,tooltipProps: { hotkey: getHotkeyById(HotkeyEnum.Strikethrough).keys },},- {- type: 'divider',- },-+ { type: 'divider' },{icon: ListIcon,key: 'bulletList',@@ -82,9 +84,7 @@ const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {label: t('typobar.taskList'),onClick: editorState.checkList,},- {- type: 'divider',- },+ { type: 'divider' },{active: editorState.isBlockquote,icon: MessageSquareQuote,@@ -92,9 +92,7 @@ const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {label: t('typobar.blockquote'),onClick: editorState.blockquote,},- {- type: 'divider',- },+ { type: 'divider' },{icon: SigmaIcon,key: 'math',@@ -115,8 +113,8 @@ const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {label: t('typobar.codeblock'),onClick: editorState.codeblock,},- ].filter(Boolean) as ChatInputActionsProps['items'],- [editorState],+ ] as ChatInputActionsProps['items'],+ [editorState, t],);return (@@ -132,5 +130,3 @@ const TypoBar = memo<{ editor?: IEditor }>(({ editor }) => {});TypoBar.displayName = 'TypoBar';--export default TypoBar;diff --git a/src/features/EditorCanvas/editorAttachments.test.ts b/src/features/EditorCanvas/editorAttachments.test.tsnew file mode 100644index 00000000000..b83a6ba0f25--- /dev/null+++ b/src/features/EditorCanvas/editorAttachments.test.ts@@ -0,0 +1,90 @@+import type { IEditor } from '@lobehub/editor';+import { describe, expect, it, vi } from 'vitest';++import { getFileIdForUrl } from './attachmentRegistry';+import {+ getEditorAttachmentStateFromJson,+ getExistingEditorAttachment,+ insertExistingAttachmentsIntoEditor,+ preservePendingFileNodeSize,+} from './editorAttachments';++describe('getEditorAttachmentStateFromJson', () => {+ it('distinguishes completed attachments from pending and failed uploads', () => {+ expect(+ getEditorAttachmentStateFromJson({+ root: {+ children: [+ {+ fileUrl: 'https://files.example.com/report.pdf',+ status: 'uploaded',+ type: 'file',+ },+ { src: 'blob:pending-image', status: 'loading', type: 'block-image' },+ { message: 'upload failed', status: 'error', type: 'image' },+ ],+ },+ }),+ ).toEqual({ hasCompletedAttachments: true, hasIncompleteAttachments: true });+ });++ it('treats an uploaded image as a completed attachment', () => {+ expect(+ getEditorAttachmentStateFromJson({+ root: {+ children: [+ { src: 'https://files.example.com/image.png', status: 'uploaded', type: 'image' },+ ],+ },+ }),+ ).toEqual({ hasCompletedAttachments: true, hasIncompleteAttachments: false });+ });+});++describe('insertExistingAttachmentsIntoEditor', () => {+ it('marks library resources for reuse instead of uploading them again', () => {+ const dispatchCommand = vi.fn();+ const focus = vi.fn();+ const editor = {+ focus,+ getLexicalEditor: () => ({ dispatchCommand }),+ } as unknown as IEditor;+ const attachment = {+ fileId: 'file-library-1',+ fileType: 'application/pdf',+ name: 'roadmap.pdf',+ size: 2048,+ url: 'https://files.example.com/roadmap.pdf',+ };++ insertExistingAttachmentsIntoEditor(editor, [attachment]);++ expect(dispatchCommand).toHaveBeenCalledTimes(1);+ const placeholderFile = dispatchCommand.mock.calls[0][1].file as File;+ expect(placeholderFile).toBeInstanceOf(File);+ expect(placeholderFile.name).toBe(attachment.name);+ expect(placeholderFile.size).toBe(attachment.size);+ expect(getExistingEditorAttachment(placeholderFile)).toEqual(attachment);+ expect(getFileIdForUrl(attachment.url)).toBe(attachment.fileId);+ expect(focus).toHaveBeenCalledTimes(1);+ });++ it('persists the source size on the pending file node', () => {+ const writable = { __size: undefined as number | undefined };+ const fileNode = {+ getType: () => 'file',+ getWritable: () => writable,+ name: 'roadmap.pdf',+ size: undefined,+ status: 'pending',+ };+ const root = {+ getChildren: () => [fileNode],+ getType: () => 'root',+ };+ const file = new File(['content'], 'roadmap.pdf', { type: 'application/pdf' });++ expect(preservePendingFileNodeSize(root as never, file)).toBe(true);+ expect(writable.__size).toBe(file.size);+ });+});diff --git a/src/features/EditorCanvas/editorAttachments.ts b/src/features/EditorCanvas/editorAttachments.tsindex 1cf996c744e..d6162efdbef 100644--- a/src/features/EditorCanvas/editorAttachments.ts+++ b/src/features/EditorCanvas/editorAttachments.ts@@ -4,9 +4,113 @@ import {INSERT_FILE_COMMAND,INSERT_IMAGE_COMMAND,} from '@lobehub/editor';-import type { SerializedEditorState } from 'lexical';+import type { ElementNode, LexicalNode, SerializedEditorState } from 'lexical';+import { $getRoot, $getSelection, $isElementNode, $isRangeSelection } from 'lexical';-import { getFileIdForUrl } from './attachmentRegistry';+import { getFileIdForUrl, registerAttachment } from './attachmentRegistry';++export interface ExistingEditorAttachment {+ fileId: string;+ fileType: string;+ name: string;+ size: number;+ url: string;+}++const existingAttachmentByFile = new WeakMap<File, ExistingEditorAttachment>();++interface FileNodeWithSize {+ __size?: number;+ getWritable: () => FileNodeWithSize;+ name: string;+ size?: number;+ status?: 'pending' | 'uploaded' | 'error';+}++export interface EditorAttachmentState {+ hasCompletedAttachments: boolean;+ hasIncompleteAttachments: boolean;+}++const toRecord = (value: unknown): Record<string, unknown> | undefined =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;++export const getEditorAttachmentStateFromJson = (json: unknown): EditorAttachmentState => {+ const pending: unknown[] = [json];+ let hasCompletedAttachments = false;+ let hasIncompleteAttachments = false;++ while (pending.length > 0) {+ const node = toRecord(pending.pop());+ if (!node) continue;++ const isFile = node.type === 'file';+ const isImage = node.type === 'image' || node.type === 'block-image';+ if (isFile || isImage) {+ const url = isFile ? node.fileUrl : node.src;+ if (node.status === 'uploaded' && typeof url === 'string' && url.length > 0) {+ hasCompletedAttachments = true;+ } else {+ hasIncompleteAttachments = true;+ }+ }++ if (Array.isArray(node.children)) pending.push(...node.children);+ if (node.root) pending.push(node.root);+ }++ return { hasCompletedAttachments, hasIncompleteAttachments };+};++export const getExistingEditorAttachment = (file: File): ExistingEditorAttachment | undefined =>+ existingAttachmentByFile.get(file);++const getChildren = (node: LexicalNode): LexicalNode[] =>+ 'getChildren' in node ? (node as ElementNode).getChildren() : [];++/**+ * The editor's file command currently creates its node with only the filename.+ * It invokes the upload handler from the same Lexical update, so persist the+ * source File size on that newly inserted pending node before the upload starts.+ */+export const preservePendingFileNodeSize = (root: LexicalNode, file: File): boolean => {+ const pending: LexicalNode[] = [root];++ while (pending.length > 0) {+ const node = pending.pop();+ if (!node) continue;++ if (node.getType() === 'file') {+ const fileNode = node as unknown as FileNodeWithSize;+ if (+ fileNode.name === file.name &&+ fileNode.status === 'pending' &&+ fileNode.size === undefined+ ) {+ fileNode.getWritable().__size = file.size;+ return true;+ }+ }+ pending.push(...getChildren(node));+ }++ return false;+};++export const preserveInsertedFileSize = (file: File): void => {+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ const anchorNode = selection.anchor.getNode();+ const candidate = $isElementNode(anchorNode)+ ? anchorNode.getChildAtIndex(selection.anchor.offset - 1)+ : anchorNode.getPreviousSibling();+ if (candidate && preservePendingFileNodeSize(candidate, file)) return;+ }++ preservePendingFileNodeSize($getRoot(), file);+};/*** URLs that have no registered fileId (e.g. externally pasted image URLs)@@ -51,6 +155,30 @@ export const insertFilesIntoEditor = (editor: IEditor | undefined, files: File[]editor.focus?.();};+/**+ * Insert already-uploaded library files without downloading or uploading them again.+ * The editor's file plugin still receives a `File`, while the upload adapter resolves+ * that placeholder straight back to the existing resource URL and file id.+ */+export const insertExistingAttachmentsIntoEditor = (+ editor: IEditor | undefined,+ attachments: ExistingEditorAttachment[],+): void => {+ if (!editor || attachments.length === 0) return;+ const lexicalEditor = editor.getLexicalEditor?.();+ if (!lexicalEditor) return;++ for (const attachment of attachments) {+ const file = new File([], attachment.name, { type: attachment.fileType });+ Object.defineProperty(file, 'size', { value: attachment.size });+ existingAttachmentByFile.set(file, attachment);+ registerAttachment(attachment.url, attachment.fileId);+ lexicalEditor.dispatchCommand(INSERT_FILE_COMMAND, { file });+ }++ editor.focus?.();+};+export const pickAndInsertAttachments = (editor: IEditor | undefined, accept?: string): void => {if (!editor?.getLexicalEditor?.()) return;diff --git a/src/features/EditorCanvas/index.ts b/src/features/EditorCanvas/index.tsindex e175152599d..9e5ee34724a 100644--- a/src/features/EditorCanvas/index.ts+++ b/src/features/EditorCanvas/index.ts@@ -7,4 +7,5 @@ export {type EditorCanvasWithEditorProps,} from './EditorCanvas';export { default as InlineToolbar, type InlineToolbarProps } from './InlineToolbar';+export { TypoBar } from './TypoBar';export { useImageUpload } from './useImageUpload';diff --git a/src/features/EditorCanvas/useImageUpload.ts b/src/features/EditorCanvas/useImageUpload.tsindex ed8aa0cf38c..d2a055ec185 100644--- a/src/features/EditorCanvas/useImageUpload.ts+++ b/src/features/EditorCanvas/useImageUpload.ts@@ -4,6 +4,7 @@ import { useFileStore } from '@/store/file';import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';import { registerAttachment } from './attachmentRegistry';+import { getExistingEditorAttachment } from './editorAttachments';export type EditorAttachmentUploadProgress = (status: FileUploadStatus,@@ -26,6 +27,12 @@ const useEditorAttachmentUpload = (skipCheckFileType: boolean) => {return useCallback(async (file: File, onProgress?: EditorAttachmentUploadProgress): Promise<{ url: string }> => {+ const existingAttachment = getExistingEditorAttachment(file);+ if (existingAttachment) {+ registerAttachment(existingAttachment.url, existingAttachment.fileId);+ return { url: existingAttachment.url };+ }+const result = await uploadWithProgress({file,onStatusUpdate: (data) => {diff --git a/src/features/EditorModal/EditorCanvas.test.tsx b/src/features/EditorModal/EditorCanvas.test.tsxindex 85739478d2d..bc6455158b9 100644--- a/src/features/EditorModal/EditorCanvas.test.tsx+++ b/src/features/EditorModal/EditorCanvas.test.tsx@@ -10,8 +10,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import EditorCanvas from './EditorCanvas';-vi.mock('./Typobar', () => ({- default: () => null,+vi.mock('@/features/EditorCanvas/TypoBar', () => ({+ TypoBar: () => null,}));const mentionEditorState = {diff --git a/src/features/EditorModal/EditorCanvas.tsx b/src/features/EditorModal/EditorCanvas.tsxindex 8bf7cf234d0..d5e11d7aa15 100644--- a/src/features/EditorModal/EditorCanvas.tsx+++ b/src/features/EditorModal/EditorCanvas.tsx@@ -5,8 +5,7 @@ import { Flexbox } from '@lobehub/ui';import { type FC, useMemo } from 'react';import { createChatInputRichPlugins } from '@/features/ChatInput/InputEditor/plugins';--import TypoBar from './Typobar';+import { TypoBar } from '@/features/EditorCanvas/TypoBar';interface EditorCanvasProps {defaultValue?: string;diff --git a/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItem.tsx b/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItem.tsxindex f82c92ed261..d7f4067d706 100644--- a/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItem.tsx+++ b/src/features/LibraryModal/AssignKnowledgeBase/Item/MasonryItem.tsx@@ -2,7 +2,7 @@ import { Flexbox, Icon } from '@lobehub/ui';import { Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { LockIcon } from 'lucide-react';-import { memo } from 'react';+import { memo, type ReactNode } from 'react';import KnowledgeIcon from '@/components/KnowledgeIcon';import { type KnowledgeItem } from '@/types/knowledgeBase';@@ -44,8 +44,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const MasonryItem = memo<KnowledgeItem>(- ({ id, fileType, name, type, description, enabled, memberRestricted, visibility }) => {+interface MasonryItemProps extends KnowledgeItem {+ action?: ReactNode;+}++const MasonryItem = memo<MasonryItemProps>(+ ({ action, id, fileType, name, type, description, enabled, memberRestricted, visibility }) => {return (<div className={styles.card}><Flexbox gap={12} style={{ position: 'relative' }}>@@ -74,7 +78,7 @@ const MasonryItem = memo<KnowledgeItem>(</Text>)}<Flexbox align={'center'} justify={'flex-end'}>- <Actions enabled={enabled} id={id} type={type} />+ {action === undefined ? <Actions enabled={enabled} id={id} type={type} /> : action}</Flexbox></Flexbox></div>diff --git a/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx b/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsxindex 0f8db9db0eb..8689ed5f9fb 100644--- a/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx+++ b/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx@@ -2,7 +2,7 @@ import { Flexbox, Icon } from '@lobehub/ui';import { Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';import { LockIcon } from 'lucide-react';-import { memo } from 'react';+import { memo, type ReactNode } from 'react';import KnowledgeIcon from '@/components/KnowledgeIcon';import { type KnowledgeItem } from '@/types/knowledgeBase';@@ -27,8 +27,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const PluginItem = memo<KnowledgeItem>(- ({ id, fileType, name, type, description, enabled, memberRestricted, visibility }) => {+interface PluginItemProps extends KnowledgeItem {+ action?: ReactNode;+}++const PluginItem = memo<PluginItemProps>(+ ({ action, id, fileType, name, type, description, enabled, memberRestricted, visibility }) => {return (<Flexboxhorizontal@@ -69,7 +73,7 @@ const PluginItem = memo<KnowledgeItem>()}</Flexbox></Flexbox>- <Actions enabled={enabled} id={id} type={type} />+ {action === undefined ? <Actions enabled={enabled} id={id} type={type} /> : action}</Flexbox>);},diff --git a/src/features/LibraryModal/FilePicker/index.tsx b/src/features/LibraryModal/FilePicker/index.tsxnew file mode 100644index 00000000000..91c4af8e251--- /dev/null+++ b/src/features/LibraryModal/FilePicker/index.tsx@@ -0,0 +1,207 @@+'use client';++import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';+import { Button, createModal, useModalContext } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { t } from 'i18next';+import { FileSearch, ServerCrash } from 'lucide-react';+import { memo, useCallback, useEffect, useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { Virtuoso } from 'react-virtuoso';+import useSWRInfinite from 'swr/infinite';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import type { ExistingEditorAttachment } from '@/features/EditorCanvas/editorAttachments';+import { resourceService } from '@/services/resource';+import { useGlobalStore } from '@/store/global';+import { KnowledgeType } from '@/types/knowledgeBase';+import type { ResourceItem } from '@/types/resource';++import Item from '../AssignKnowledgeBase/Item';+import MasonryItem from '../AssignKnowledgeBase/Item/MasonryItem';+import Loading from '../AssignKnowledgeBase/Loading';+import { type ViewMode } from '../AssignKnowledgeBase/ViewSwitcher';+import ViewSwitcher from '../AssignKnowledgeBase/ViewSwitcher';++const PAGE_SIZE = 50;++const styles = createStaticStyles(({ css }) => ({+ grid: css`+ overflow-y: auto;+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 8px;++ padding-block: 4px;+ `,+}));++interface ResourcePage {+ hasMore: boolean;+ items: ResourceItem[];+}++interface FilePickerProps {+ onSelect: (attachments: ExistingEditorAttachment[]) => void;+}++const isAttachableFile = (+ item: ResourceItem,+): item is ResourceItem & { sourceType: 'file'; url: string } =>+ item.sourceType === 'file' && Boolean(item.url);++const FilePicker = memo<FilePickerProps>(({ onSelect }) => {+ const { t } = useTranslation(['file', 'chat', 'common']);+ const { close } = useModalContext();+ const workspaceId = useActiveWorkspaceId();+ const viewMode = useGlobalStore((s) => s.status.knowledgeBaseModalViewMode || 'list') as ViewMode;+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);++ const getKey = useCallback(+ (pageIndex: number, previousPage: ResourcePage | null) => {+ if (previousPage && !previousPage.hasMore) return null;+ return ['comment-library-files', workspaceId, pageIndex * PAGE_SIZE] as const;+ },+ [workspaceId],+ );++ const { data, error, isLoading, isValidating, mutate, setSize } = useSWRInfinite<ResourcePage>(+ getKey,+ ([, , offset]: readonly [string, string | null, number]) =>+ resourceService.queryResources({+ limit: PAGE_SIZE,+ offset,+ showFilesInKnowledgeBase: true,+ }),+ { revalidateFirstPage: false },+ );++ const files = useMemo(() => {+ const uniqueFiles = new Map<string, ResourceItem & { sourceType: 'file'; url: string }>();+ for (const item of data?.flatMap((page) => page?.items ?? []) ?? []) {+ if (!isAttachableFile(item)) continue;+ uniqueFiles.set(item.fileId || item.id, item);+ }+ return [...uniqueFiles.values()];+ }, [data]);+ const lastPage = data?.findLast(Boolean);+ const hasMore = Boolean(lastPage?.hasMore);++ useEffect(() => {+ if (!isLoading && !isValidating && files.length === 0 && hasMore) {+ void setSize((current) => current + 1);+ }+ }, [files.length, hasMore, isLoading, isValidating, setSize]);++ const handleSelect = useCallback(+ (file: ResourceItem & { sourceType: 'file'; url: string }) => {+ onSelect([+ {+ fileId: file.fileId || file.id,+ fileType: file.fileType,+ name: file.name,+ size: file.size,+ url: file.url,+ },+ ]);+ close();+ },+ [close, onSelect],+ );++ const renderAction = useCallback(+ (file: ResourceItem & { sourceType: 'file'; url: string }) => (+ <Button type={'primary'} onClick={() => handleSelect(file)}>+ {t('knowledgeBase.library.action.add', { ns: 'chat' })}+ </Button>+ ),+ [handleSelect, t],+ );++ const renderItem = useCallback(+ (file: ResourceItem & { sourceType: 'file'; url: string }) => (+ <Item+ action={renderAction(file)}+ fileType={file.fileType}+ id={file.fileId || file.id}+ name={file.name}+ type={KnowledgeType.File}+ visibility={file.visibility ?? undefined}+ />+ ),+ [renderAction],+ );++ const loadMore = useCallback(() => {+ if (hasMore && !isValidating) void setSize((current) => current + 1);+ }, [hasMore, isValidating, setSize]);++ return (+ <Flexbox height={500} width={'100%'}>+ <Flexbox horizontal align={'center'} justify={'flex-end'} style={{ paddingBlockEnd: 12 }}>+ <ViewSwitcher+ view={viewMode}+ onViewChange={(mode) => updateSystemStatus({ knowledgeBaseModalViewMode: mode })}+ />+ </Flexbox>+ {isLoading && files.length === 0 ? (+ <Loading />+ ) : error && files.length === 0 ? (+ <Center flex={1} gap={12} padding={40}>+ <Icon icon={ServerCrash} size={80} />+ {t('networkError', { ns: 'file' })}+ <Button onClick={() => void mutate()}>{t('retry', { ns: 'common' })}</Button>+ </Center>+ ) : files.length === 0 ? (+ <Center flex={1} padding={40}>+ <Empty+ description={t('empty', { ns: 'file' })}+ descriptionProps={{ fontSize: 14 }}+ icon={FileSearch}+ />+ </Center>+ ) : viewMode === 'list' ? (+ <Virtuoso+ data={files}+ endReached={loadMore}+ increaseViewportBy={typeof window !== 'undefined' ? window.innerHeight : 0}+ itemContent={(_, file) => renderItem(file)}+ overscan={24}+ style={{ flex: 1, marginInline: -16 }}+ />+ ) : (+ <div className={styles.grid}>+ {files.map((file) => (+ <MasonryItem+ action={renderAction(file)}+ fileType={file.fileType}+ id={file.fileId || file.id}+ key={file.fileId || file.id}+ name={file.name}+ type={KnowledgeType.File}+ visibility={file.visibility ?? undefined}+ />+ ))}+ {hasMore && (+ <Button loading={isValidating} type={'text'} onClick={loadMore}>+ {t('loadMore', { ns: 'file' })}+ </Button>+ )}+ </div>+ )}+ </Flexbox>+ );+});++FilePicker.displayName = 'LibraryFilePicker';++export const openLibraryFilePicker = (+ onSelect: (attachments: ExistingEditorAttachment[]) => void,+) =>+ createModal({+ content: <FilePicker onSelect={onSelect} />,+ footer: false,+ styles: { content: { overflow: 'hidden' } },+ title: t('knowledgeBase.library.title', { ns: 'chat' }),+ width: 600,+ });diff --git a/src/features/LibraryModal/index.ts b/src/features/LibraryModal/index.tsindex 4aa226de76e..b8e31b6f5ce 100644--- a/src/features/LibraryModal/index.ts+++ b/src/features/LibraryModal/index.ts@@ -1,2 +1,3 @@export * from './AssignKnowledgeBase';export * from './CreateNew';+export * from './FilePicker';diff --git a/src/features/Messenger/IntegrationDetail/Wechat.test.tsx b/src/features/Messenger/IntegrationDetail/Wechat.test.tsxindex 3b8c9a6d773..51c1d24638d 100644--- a/src/features/Messenger/IntegrationDetail/Wechat.test.tsx+++ b/src/features/Messenger/IntegrationDetail/Wechat.test.tsx@@ -73,6 +73,8 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({))}</select>),+ Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,toast: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() },}));diff --git a/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx b/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsxindex 6bc1a8f4aee..ef5aa4609ca 100644--- a/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx+++ b/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx@@ -16,7 +16,6 @@ vi.mock('react-i18next', () => ({}));vi.mock('@lobehub/ui', () => ({- Avatar: () => <span />,DropdownMenuGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,DropdownMenuGroupLabel: ({ children }: { children: ReactNode }) => <div>{children}</div>,DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (@@ -45,13 +44,18 @@ vi.mock('@lobehub/ui', () => ({),Icon: () => <span />,Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,Tooltip: ({ children, title }: { children: ReactNode; title: string }) => (<span data-testid={`tooltip-${title}`}>{children}</span>),menuSharedStyles: { item: 'item' },}));+vi.mock('@lobehub/ui/base-ui', () => ({+ Avatar: () => <span />,+ Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,+}));+vi.mock('@lobehub/icons', () => ({LobeHub: { Morden: () => <span /> },ModelIcon: () => <span />,diff --git a/src/features/PageEditor/DocumentComments/CommentCard.tsx b/src/features/PageEditor/DocumentComments/CommentCard.tsxnew file mode 100644index 00000000000..4501892ccab--- /dev/null+++ b/src/features/PageEditor/DocumentComments/CommentCard.tsx@@ -0,0 +1,301 @@+import type { DocumentCommentItem } from '@lobechat/types';+import { ChatInput, ChatInputActionBar, useEditor } from '@lobehub/editor/react';+import { Flexbox, Markdown } from '@lobehub/ui';+import { ActionIcon, Avatar, Button, confirmModal, Text, toast } from '@lobehub/ui/base-ui';+import { ChevronRight, MessageCircle, Pencil, Trash } from 'lucide-react';+import { memo, useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { AttachmentMenu } from '@/features/AttachmentInput';+import RichTextMessage from '@/features/Conversation/Messages/User/components/RichTextMessage';+import { TypoBar } from '@/features/EditorCanvas';+import {+ getEditorAttachmentStateFromJson,+ insertExistingAttachmentsIntoEditor,+ insertFilesIntoEditor,+} from '@/features/EditorCanvas/editorAttachments';+import { useActivityTime } from '@/hooks/useActivityTime';+import { useLocalStorageState } from '@/hooks/useLocalStorageState';+import { documentCommentService } from '@/services/documentComment';++import DocumentCommentEditor, {+ type DocumentCommentEditorRef,+ type DocumentCommentEditorValue,+} from './DocumentCommentEditor';+import type { DocumentCommentUpdateHandler } from './optimistic';+import { isOptimisticDocumentComment } from './optimistic';+import { styles } from './styles';++interface CommentCardProps {+ comment: DocumentCommentItem;+ onMutated: () => void | Promise<void>;+ onReply?: () => void;+ onUpdate: DocumentCommentUpdateHandler;+ replying?: boolean;+ variant?: 'reply' | 'root';+}++const hasDocumentCommentEditorData = (editorData: DocumentCommentItem['editorData']) =>+ Boolean(+ editorData &&+ typeof editorData === 'object' &&+ !Array.isArray(editorData) &&+ Object.keys(editorData).length > 0,+ );++const CommentContent = memo<Pick<DocumentCommentItem, 'content' | 'editorData'>>(+ ({ content, editorData }) =>+ hasDocumentCommentEditorData(editorData) ? (+ <RichTextMessage editorState={editorData} variant={'default'} />+ ) : (+ <Markdown fontSize={16} variant={'chat'}>+ {content}+ </Markdown>+ ),+);++CommentContent.displayName = 'DocumentCommentContent';++const CommentCard = memo<CommentCardProps>(+ ({ comment, onMutated, onReply, onUpdate, replying, variant = 'root' }) => {+ const { t } = useTranslation('file');+ const { text: time, title: timeTitle } = useActivityTime(comment.createdAt);+ const [editing, setEditing] = useState(false);+ const [content, setContent] = useState(comment.content);+ const [editorData, setEditorData] = useState(comment.editorData);+ const editEditor = useEditor();+ const editorRef = useRef<DocumentCommentEditorRef>(null);+ const editInputRef = useRef<HTMLDivElement>(null);+ const [showTypoBar, setShowTypoBar] = useLocalStorageState(+ 'document-comment:show-formatting-toolbar',+ false,+ );+ const [mutating, setMutating] = useState(false);+ const deleted = Boolean(comment.deletedAt);+ const optimistic = isOptimisticDocumentComment(comment);+ const authorName =+ comment.author.fullName ||+ comment.author.username ||+ t('pageEditor.comments.author.deactivated');+ const replyToName =+ comment.replyTo?.author.fullName ||+ comment.replyTo?.author.username ||+ (comment.replyTo ? t('pageEditor.comments.author.deactivated') : null);+ const edited = new Date(comment.updatedAt).getTime() > new Date(comment.createdAt).getTime();++ const handleUpdate = useCallback(async () => {+ const editorValue: DocumentCommentEditorValue = editorRef.current?.getValue() ?? {+ content,+ editorData,+ };+ const nextContent = editorValue.content.trim();+ const attachmentState = getEditorAttachmentStateFromJson(editorValue.editorData);+ if (+ attachmentState.hasIncompleteAttachments ||+ (!nextContent && !attachmentState.hasCompletedAttachments) ||+ mutating+ )+ return;+ setContent(nextContent);+ setEditorData(editorValue.editorData);+ setMutating(true);+ setEditing(false);+ try {+ await onUpdate(comment, { content: nextContent, editorData: editorValue.editorData });+ } catch {+ setEditing(true);+ toast.error(t('pageEditor.comments.updateFailed'));+ } finally {+ setMutating(false);+ }+ }, [comment, content, editorData, mutating, onUpdate, t]);++ const handleDelete = useCallback(() => {+ confirmModal({+ content: t('pageEditor.comments.deleteConfirm.content'),+ okButtonProps: { danger: true },+ okText: t('pageEditor.comments.delete'),+ onOk: async () => {+ setMutating(true);+ try {+ await documentCommentService.delete(comment.id);+ await onMutated();+ } catch {+ toast.error(t('pageEditor.comments.deleteFailed'));+ throw new Error('Failed to delete document comment');+ } finally {+ setMutating(false);+ }+ },+ title: t('pageEditor.comments.deleteConfirm.title'),+ });+ }, [comment.id, onMutated, t]);++ const handleEdit = useCallback(() => {+ setContent(comment.content);+ setEditorData(comment.editorData);+ setEditing(true);+ }, [comment.content, comment.editorData]);++ const handleAttach = useCallback(+ (files: File[]) => {+ insertFilesIntoEditor(editEditor, files);+ },+ [editEditor],+ );+ const attachmentState = getEditorAttachmentStateFromJson(editorData);++ return (+ <Flexbox+ className={`${styles.card} ${variant === 'reply' ? styles.replyCard : ''}`}+ data-document-comment-id={comment.id}+ >+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ <Avatar+ avatar={comment.author.avatar || authorName}+ size={variant === 'reply' ? 28 : 32}+ />+ <Text fontSize={14} weight={600}>+ {authorName}+ </Text>+ {replyToName && (+ <>+ <ChevronRight aria-hidden className={styles.replyTargetIcon} size={14} />+ <Text fontSize={14} weight={600}>+ {replyToName}+ </Text>+ </>+ )}+ {comment.author.status === 'former' && (+ <Text className={styles.meta} fontSize={12}>+ {t('pageEditor.comments.author.former')}+ </Text>+ )}+ {time && (+ <Text className={styles.meta} fontSize={14} title={timeTitle}>+ {time}+ </Text>+ )}+ {edited && !deleted && (+ <Text className={styles.meta} fontSize={12}>+ {t('pageEditor.comments.edited')}+ </Text>+ )}+ </Flexbox>++ <div className={`${styles.body} ${variant === 'reply' ? styles.replyBody : ''}`}>+ {deleted ? (+ <Text className={styles.deleted}>{t('pageEditor.comments.deleted')}</Text>+ ) : editing ? (+ <ChatInput+ className={styles.editComposer}+ header={showTypoBar ? <TypoBar editor={editEditor} /> : undefined}+ minHeight={64}+ resize={false}+ slashMenuRef={editInputRef}+ footer={+ <ChatInputActionBar+ style={{ paddingBlock: 4, paddingInline: 8 }}+ left={+ <AttachmentMenu+ disabled={mutating}+ formatEnabled={showTypoBar}+ onFiles={handleAttach}+ onFormatEnabledChange={setShowTypoBar}+ onLibraryFiles={(attachments) =>+ insertExistingAttachmentsIntoEditor(editEditor, attachments)+ }+ />+ }+ right={+ <Flexbox horizontal gap={8}>+ <Button disabled={mutating} size={'small'} onClick={() => setEditing(false)}>+ {t('pageEditor.comments.cancel')}+ </Button>+ <Button+ loading={mutating}+ size={'small'}+ type={'primary'}+ disabled={+ attachmentState.hasIncompleteAttachments ||+ (!content.trim() && !attachmentState.hasCompletedAttachments)+ }+ onClick={handleUpdate}+ >+ {t('pageEditor.comments.save')}+ </Button>+ </Flexbox>+ }+ />+ }+ onBodyClick={() => editEditor.focus()}+ >+ <DocumentCommentEditor+ autoFocus+ compact+ disabled={mutating}+ editor={editEditor}+ entityId={comment.id}+ getPopupContainer={() => editInputRef.current}+ initialContent={content}+ initialEditorData={editorData}+ placeholder={t('pageEditor.comments.placeholder')}+ ref={editorRef}+ onChange={({ content: nextContent, editorData: nextEditorData }) => {+ setContent(nextContent);+ setEditorData(nextEditorData);+ }}+ />+ </ChatInput>+ ) : (+ <CommentContent content={comment.content} editorData={comment.editorData} />+ )}+ </div>++ {!optimistic && !editing && (onReply || comment.canEdit || comment.canDelete) && (+ <Flexbox+ horizontal+ className={`${styles.actions} ${variant === 'reply' ? styles.replyCardActions : ''}`}+ gap={4}+ >+ {onReply && (+ <ActionIcon+ aria-label={t('pageEditor.comments.replyAction')}+ aria-pressed={replying}+ disabled={mutating}+ icon={MessageCircle}+ size={'small'}+ title={t('pageEditor.comments.replyAction')}+ onClick={onReply}+ />+ )}+ {comment.canEdit && (+ <ActionIcon+ aria-label={t('pageEditor.comments.edit')}+ disabled={mutating}+ icon={Pencil}+ size={'small'}+ title={t('pageEditor.comments.edit')}+ onClick={handleEdit}+ />+ )}+ {comment.canDelete && (+ <ActionIcon+ aria-label={t('pageEditor.comments.delete')}+ icon={Trash}+ loading={mutating}+ size={'small'}+ title={t('pageEditor.comments.delete')}+ onClick={handleDelete}+ />+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);++CommentCard.displayName = 'DocumentCommentCard';++export default CommentCard;diff --git a/src/features/PageEditor/DocumentComments/Composer.tsx b/src/features/PageEditor/DocumentComments/Composer.tsxnew file mode 100644index 00000000000..7da3865c300--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Composer.tsx@@ -0,0 +1,187 @@+import type { DocumentCommentJson } from '@lobechat/types';+import { ChatInput, ChatInputActionBar, SendButton, useEditor } from '@lobehub/editor/react';+import { Flexbox } from '@lobehub/ui';+import { Avatar, toast } from '@lobehub/ui/base-ui';+import { nanoid } from 'nanoid';+import { memo, useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { AttachmentMenu } from '@/features/AttachmentInput';+import { TypoBar } from '@/features/EditorCanvas';+import {+ getEditorAttachmentStateFromJson,+ insertExistingAttachmentsIntoEditor,+ insertFilesIntoEditor,+} from '@/features/EditorCanvas/editorAttachments';+import { useEnterToSend } from '@/hooks/useEnterToSend';+import { useLocalStorageState } from '@/hooks/useLocalStorageState';+import { usePermission } from '@/hooks/usePermission';+import { useUserAvatar } from '@/hooks/useUserAvatar';++import DocumentCommentEditor, { type DocumentCommentEditorRef } from './DocumentCommentEditor';+import type { DocumentCommentSubmitInput } from './optimistic';+import { styles } from './styles';++interface Draft {+ clientId: string;+ content: string;+ editorData: DocumentCommentJson | null;+}++interface ComposerProps {+ documentId: string;+ onSubmit: (input: DocumentCommentSubmitInput) => Promise<void>;+ onSuccess?: () => void;+ parentCommentId?: string;+}++const Composer = memo<ComposerProps>(({ documentId, onSubmit, onSuccess, parentCommentId }) => {+ const { t } = useTranslation('file');+ const workspaceId = useActiveWorkspaceId();+ const { allowed: canCreate } = usePermission('create_content');+ const avatar = useUserAvatar();+ const shouldSendOnEnter = useEnterToSend();+ const editor = useEditor();+ const editorRef = useRef<DocumentCommentEditorRef>(null);+ const inputRef = useRef<HTMLDivElement>(null);+ const submittingRef = useRef(false);+ const [draft, setDraft] = useLocalStorageState<Draft>(+ `document-comment-draft:${workspaceId ?? 'personal'}:${documentId}:${parentCommentId ?? 'root'}`,+ { clientId: nanoid(), content: '', editorData: null },+ );+ const [showTypoBar, setShowTypoBar] = useLocalStorageState(+ 'document-comment:show-formatting-toolbar',+ false,+ );+ const [submitting, setSubmitting] = useState(false);++ const submit = useCallback(async () => {+ const editorValue = editorRef.current?.getValue() ?? {+ content: draft.content,+ editorData: draft.editorData,+ };+ const content = editorValue.content.trim();+ const attachmentState = getEditorAttachmentStateFromJson(editorValue.editorData);+ if (+ !workspaceId ||+ !canCreate ||+ attachmentState.hasIncompleteAttachments ||+ (!content && !attachmentState.hasCompletedAttachments) ||+ submittingRef.current+ )+ return;++ submittingRef.current = true;+ setSubmitting(true);+ const submittedDraft = { clientId: draft.clientId, ...editorValue };+ setDraft({ clientId: nanoid(), content: '', editorData: null });+ editorRef.current?.clean();+ try {+ await onSubmit({+ clientId: submittedDraft.clientId,+ content,+ editorData: editorValue.editorData,+ });+ onSuccess?.();+ } catch {+ setDraft((current) => (current.content ? current : submittedDraft));+ editorRef.current?.setValue(editorValue);+ editorRef.current?.focus();+ toast.error(t('pageEditor.comments.createFailed'));+ } finally {+ submittingRef.current = false;+ setSubmitting(false);+ }+ }, [canCreate, draft, onSubmit, onSuccess, setDraft, t, workspaceId]);++ const handleAttach = useCallback(+ (files: File[]) => {+ insertFilesIntoEditor(editor, files);+ },+ [editor],+ );++ if (!workspaceId || !canCreate || (submitting && parentCommentId)) return null;++ const attachmentState = getEditorAttachmentStateFromJson(draft.editorData);++ return (+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <Flexbox className={styles.composerAvatar}>+ <Avatar avatar={avatar} size={parentCommentId ? 28 : 32} />+ </Flexbox>+ <ChatInput+ className={styles.composer}+ flex={1}+ header={showTypoBar ? <TypoBar editor={editor} /> : undefined}+ maxHeight={240}+ minHeight={72}+ resize={false}+ slashMenuRef={inputRef}+ footer={+ <ChatInputActionBar+ style={{ paddingBlock: 4, paddingInline: 8 }}+ left={+ <AttachmentMenu+ disabled={submitting}+ formatEnabled={showTypoBar}+ onFiles={handleAttach}+ onFormatEnabledChange={setShowTypoBar}+ onLibraryFiles={(attachments) =>+ insertExistingAttachmentsIntoEditor(editor, attachments)+ }+ />+ }+ right={+ <SendButton+ loading={submitting}+ shape={'round'}+ type={'primary'}+ disabled={+ attachmentState.hasIncompleteAttachments ||+ (!draft.content.trim() && !attachmentState.hasCompletedAttachments)+ }+ title={+ parentCommentId+ ? t('pageEditor.comments.replyAction')+ : t('pageEditor.comments.publish')+ }+ onClick={() => void submit()}+ />+ }+ />+ }+ onBodyClick={() => editor.focus()}+ >+ <DocumentCommentEditor+ autoFocus={Boolean(parentCommentId)}+ disabled={submitting}+ editor={editor}+ entityId={draft.clientId}+ getPopupContainer={() => inputRef.current}+ initialContent={draft.content}+ initialEditorData={draft.editorData}+ ref={editorRef}+ placeholder={+ parentCommentId+ ? t('pageEditor.comments.replyPlaceholder')+ : t('pageEditor.comments.placeholder')+ }+ onChange={({ content, editorData }) => {+ setDraft((current) => ({ ...current, content, editorData }));+ }}+ onPressEnter={(event) => {+ if (!shouldSendOnEnter(event)) return;+ void submit();+ return true;+ }}+ />+ </ChatInput>+ </Flexbox>+ );+});++Composer.displayName = 'DocumentCommentComposer';++export default Composer;diff --git a/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsx b/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsxnew file mode 100644index 00000000000..186f0c8d666--- /dev/null+++ b/src/features/PageEditor/DocumentComments/DocumentCommentEditor.tsx@@ -0,0 +1,115 @@+import type { DocumentCommentJson } from '@lobechat/types';+import type { IEditor } from '@lobehub/editor';+import type { EditorProps } from '@lobehub/editor/react';+import { useEditor } from '@lobehub/editor/react';+import type { Ref } from 'react';+import { memo, useCallback, useImperativeHandle } from 'react';++import { mentionFilledClassName } from '@/features/ChatInput/InputEditor/mentionStyle';+import { EditorCanvas } from '@/features/EditorCanvas';+import {+ readTopicCommentEditorValue,+ type TopicCommentEditorValue,+} from '@/features/Portal/TopicComments/editorUtils';+import { useWorkspaceCommentMentionOption } from '@/features/Portal/TopicComments/useWorkspaceCommentMentionOption';++import { styles } from './styles';++export type DocumentCommentEditorValue = TopicCommentEditorValue;++export interface DocumentCommentEditorRef {+ clean: () => void;+ focus: () => void;+ getValue: () => DocumentCommentEditorValue;+ setValue: (value: DocumentCommentEditorValue) => void;+}++interface DocumentCommentEditorProps {+ autoFocus?: boolean;+ compact?: boolean;+ disabled?: boolean;+ editor?: IEditor;+ entityId: string;+ getPopupContainer?: EditorProps['getPopupContainer'];+ initialContent: string;+ initialEditorData?: DocumentCommentJson | null;+ onChange?: (value: DocumentCommentEditorValue) => void;+ onPressEnter?: (event: KeyboardEvent) => boolean | void;+ placeholder: string;+ ref?: Ref<DocumentCommentEditorRef>;+}++const DocumentCommentEditor = memo<DocumentCommentEditorProps>(+ ({+ ref,+ autoFocus,+ compact = false,+ disabled,+ editor: externalEditor,+ entityId,+ getPopupContainer,+ initialContent,+ initialEditorData,+ onChange,+ onPressEnter,+ placeholder,+ }) => {+ const internalEditor = useEditor();+ const editor = externalEditor ?? internalEditor;+ const mentionOption = useWorkspaceCommentMentionOption();++ const setValue = useCallback(+ (value: DocumentCommentEditorValue) => {+ if (value.editorData) editor.setDocument('json', value.editorData);+ else editor.setDocument('markdown', value.content);+ },+ [editor],+ );++ useImperativeHandle(+ ref,+ () => ({+ clean: () => editor.cleanDocument(),+ focus: () => editor.focus(),+ getValue: () => readTopicCommentEditorValue(editor),+ setValue,+ }),+ [editor, setValue],+ );++ const handleInit = useCallback(+ (currentEditor: IEditor) => {+ if (autoFocus) currentEditor.focus();+ },+ [autoFocus],+ );++ return (+ <div className={`${styles.commentEditor} ${mentionFilledClassName}`}>+ <EditorCanvas+ disabled={disabled}+ editor={editor}+ editorData={{ content: initialContent, editorData: initialEditorData }}+ entityId={entityId}+ floatingToolbar={false}+ getPopupContainer={getPopupContainer}+ mentionOption={mentionOption}+ placeholder={placeholder}+ contentStyle={{+ maxHeight: compact ? 120 : 184,+ minHeight: compact ? 24 : 44,+ overflowY: 'auto',+ padding: 0,+ }}+ onContentChange={() => onChange?.(readTopicCommentEditorValue(editor))}+ onInit={handleInit}+ onPressEnter={({ event }) => onPressEnter?.(event)}+ />+ </div>+ );+ },+);++DocumentCommentEditor.displayName = 'DocumentCommentEditor';++export default DocumentCommentEditor;diff --git a/src/features/PageEditor/DocumentComments/Thread.tsx b/src/features/PageEditor/DocumentComments/Thread.tsxnew file mode 100644index 00000000000..94b673524d5--- /dev/null+++ b/src/features/PageEditor/DocumentComments/Thread.tsx@@ -0,0 +1,240 @@+import type { DocumentCommentThread } from '@lobechat/types';+import { Center, Flexbox } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { Fragment, memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import SurfaceSkeleton from '@/components/Skeleton/Surface';+import { documentCommentService } from '@/services/documentComment';++import CommentCard from './CommentCard';+import Composer from './Composer';+import { useDocumentCommentReplies, useOptimisticDocumentComment } from './hooks';+import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';+import {+ appendOptimisticReply,+ isOptimisticDocumentComment,+ removeOptimisticReply,+ replaceOptimisticReply,+ replaceReplyComment,+} from './optimistic';+import { styles } from './styles';+import { useAutoLoadReplies } from './useAutoLoadReplies';++interface ThreadProps extends DocumentCommentThread {+ documentId: string;+ onMutated: () => void | Promise<void>;+ onReplyCountChange: (rootCommentId: string, delta: number) => void | Promise<unknown>;+ onRootUpdate: DocumentCommentUpdateHandler;+ onSummaryChange: (delta: number) => void | Promise<unknown>;+}++const Thread = memo<ThreadProps>(+ ({+ documentId,+ onMutated,+ onReplyCountChange,+ onRootUpdate,+ onSummaryChange,+ replyCount,+ root,+ }) => {+ const { t } = useTranslation('file');+ const [replyTargetId, setReplyTargetId] = useState<string | null>(null);+ const { containerRef, shouldLoad } = useAutoLoadReplies(replyCount > 0);+ const replies = useDocumentCommentReplies(root.id, shouldLoad || Boolean(replyTargetId));+ const createOptimistic = useOptimisticDocumentComment();+ const mutateReplies = replies.mutate;+ const reloadReplies = replies.reload;+ const refreshThread = useCallback(async () => {+ await Promise.all([reloadReplies(), onMutated()]);+ }, [onMutated, reloadReplies]);+ const handleReplySubmit = useCallback(+ async ({ clientId, content, editorData }: DocumentCommentSubmitInput) => {+ const replyTarget =+ replyTargetId === root.id+ ? root+ : replies.items.find((item) => item.id === replyTargetId);+ if (!replyTarget) throw new Error('Document comment reply target is unavailable');+ if (isOptimisticDocumentComment(replyTarget)) {+ throw new Error('An optimistic document comment cannot be replied to');+ }++ const optimisticComment = createOptimistic({+ clientId,+ content,+ documentId: replyTarget.documentId,+ editorData,+ parentCommentId: root.id,+ replyTo:+ replyTarget.id === root.id ? null : { author: replyTarget.author, id: replyTarget.id },+ });+ await Promise.all([+ mutateReplies((pages) => appendOptimisticReply(pages, optimisticComment), {+ revalidate: false,+ }),+ onReplyCountChange(root.id, 1),+ onSummaryChange(1),+ ]);++ let created: Awaited<ReturnType<typeof documentCommentService.create>>;+ try {+ created = await documentCommentService.create({+ clientId,+ content,+ documentId: replyTarget.documentId,+ editorData,+ parentCommentId: replyTarget.id,+ });+ if (!created) throw new Error('Document comment reply creation returned no result');+ } catch (error) {+ await Promise.all([+ mutateReplies((pages) => removeOptimisticReply(pages, clientId), {+ revalidate: false,+ }),+ onReplyCountChange(root.id, -1),+ onSummaryChange(-1),+ ]);+ throw error;+ }++ try {+ await mutateReplies((pages) => replaceOptimisticReply(pages, created.comment), {+ revalidate: false,+ });+ } catch (error) {+ console.error('Failed to reconcile the created document comment reply', error);+ void reloadReplies();+ }+ if (created.isDuplicate) void refreshThread();+ },+ [+ createOptimistic,+ mutateReplies,+ onReplyCountChange,+ onSummaryChange,+ refreshThread,+ reloadReplies,+ replies.items,+ replyTargetId,+ root,+ ],+ );+ const handleReplyUpdate: DocumentCommentUpdateHandler = useCallback(+ async (comment, value) => {+ const optimisticComment = { ...comment, ...value, updatedAt: new Date() };+ await mutateReplies((pages) => replaceReplyComment(pages, optimisticComment), {+ revalidate: false,+ });++ let updated: Awaited<ReturnType<typeof documentCommentService.update>>;+ try {+ updated = await documentCommentService.update({ ...value, id: comment.id });+ if (!updated) throw new Error('Document comment reply update returned no result');+ } catch (error) {+ await mutateReplies((pages) => replaceReplyComment(pages, comment), {+ revalidate: false,+ });+ throw error;+ }++ try {+ await mutateReplies((pages) => replaceReplyComment(pages, updated), {+ revalidate: false,+ });+ } catch (error) {+ console.error('Failed to reconcile the updated document comment reply', error);+ void reloadReplies();+ }+ },+ [mutateReplies, reloadReplies],+ );++ const toggleReplyTarget = useCallback((commentId: string) => {+ setReplyTargetId((current) => (current === commentId ? null : commentId));+ }, []);++ return (+ <Flexbox className={styles.thread} ref={containerRef}>+ <CommentCard+ comment={root}+ replying={replyTargetId === root.id}+ onMutated={onMutated}+ onReply={() => toggleReplyTarget(root.id)}+ onUpdate={onRootUpdate}+ />++ {(replyCount > 0 || replyTargetId) && (+ <Flexbox className={styles.replyList}>+ {replyTargetId === root.id && (+ <Composer+ documentId={documentId}+ key={`reply:${root.id}`}+ parentCommentId={root.id}+ onSubmit={handleReplySubmit}+ onSuccess={() => setReplyTargetId(null)}+ />+ )}+ {replies.isLoadingInitial && replyCount > 0 ? (+ <SurfaceSkeleton header={false} variant={'list'} />+ ) : replies.isInitialError ? (+ <AsyncError+ error={replies.error}+ variant={'inline'}+ onRetry={() => void replies.reload()}+ />+ ) : (+ replies.items.map((reply) => (+ <Fragment key={reply.id}>+ <CommentCard+ comment={reply}+ replying={replyTargetId === reply.id}+ variant={'reply'}+ onMutated={refreshThread}+ onReply={() => toggleReplyTarget(reply.id)}+ onUpdate={handleReplyUpdate}+ />+ {replyTargetId === reply.id && (+ <Composer+ documentId={documentId}+ key={`reply:${reply.id}`}+ parentCommentId={reply.id}+ onSubmit={handleReplySubmit}+ onSuccess={() => setReplyTargetId(null)}+ />+ )}+ </Fragment>+ ))+ )}+ {replies.error && !replies.isInitialError ? (+ <AsyncError+ error={replies.error}+ retrying={replies.isRetrying}+ variant={'inline'}+ onRetry={() => void replies.reload()}+ />+ ) : (+ replies.hasMore && (+ <Center paddingBlock={8}>+ <Button+ loading={replies.isLoadingMore}+ size={'small'}+ type={'text'}+ onClick={() => void replies.loadMore()}+ >+ {t('pageEditor.comments.loadMoreReplies')}+ </Button>+ </Center>+ )+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);++Thread.displayName = 'DocumentCommentThread';++export default Thread;diff --git a/src/features/PageEditor/DocumentComments/hooks.ts b/src/features/PageEditor/DocumentComments/hooks.tsnew file mode 100644index 00000000000..a9909702513--- /dev/null+++ b/src/features/PageEditor/DocumentComments/hooks.ts@@ -0,0 +1,174 @@+import type {+ DocumentCommentItem,+ DocumentCommentReplyPage,+ DocumentCommentSummary,+ DocumentCommentThreadPage,+} from '@lobechat/types';+import { useCallback } from 'react';+import useSWRInfinite from 'swr/infinite';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useClientDataSWR } from '@/libs/swr';+import { documentCommentKeys } from '@/libs/swr/keys';+import { documentCommentService } from '@/services/documentComment';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import {+ createOptimisticComment,+ flattenDocumentCommentReplies,+ flattenDocumentCommentThreads,+} from './optimistic';++const PAGE_SIZE = 20;++const fetchThreads = ([, , documentId, cursor]: readonly string[]) =>+ documentCommentService.listThreads({+ cursor: cursor || undefined,+ documentId,+ limit: PAGE_SIZE,+ });++const fetchReplies = ([, , rootCommentId, cursor]: readonly string[]) =>+ documentCommentService.listReplies({+ cursor: cursor || undefined,+ limit: PAGE_SIZE,+ rootCommentId,+ });++const getPaginationState = <T extends { nextCursor: string | null }>(+ data: T[] | undefined,+ error: unknown,+ isLoading: boolean,+ isValidating: boolean,+ size: number,+) => {+ const hasLoadedPages = data !== undefined;+ const lastPage = data?.findLast(Boolean);++ return {+ hasMore: !error && Boolean(lastPage?.nextCursor),+ isInitialError: Boolean(error) && !hasLoadedPages,+ isLoadingInitial: !error && isLoading && !hasLoadedPages,+ isLoadingMore: !error && hasLoadedPages && size > 0 && typeof data?.[size - 1] === 'undefined',+ isRetrying: Boolean(error) && isValidating,+ };+};++export const useDocumentCommentSummary = (documentId?: string | null) =>+ useClientDataSWR<DocumentCommentSummary>(+ documentId ? documentCommentKeys.summary(documentId) : null,+ () => documentCommentService.summary(documentId!),+ { dedupingInterval: 30_000 },+ );++export const useOptimisticDocumentComment = () => {+ const workspaceId = useActiveWorkspaceId();+ const user = useUserStore(userProfileSelectors.userProfile);++ return useCallback(+ ({+ clientId,+ content,+ documentId,+ editorData,+ parentCommentId,+ replyTo,+ }: {+ clientId: string;+ content: string;+ documentId: string;+ editorData: DocumentCommentItem['editorData'];+ parentCommentId?: string;+ replyTo?: DocumentCommentItem['replyTo'];+ }) => {+ if (!workspaceId) throw new Error('Workspace is required for document comments');++ return createOptimisticComment({+ author: {+ avatar: user?.avatar ?? null,+ fullName: user?.fullName ?? null,+ id: user?.id ?? null,+ status: 'active',+ username: user?.username ?? null,+ },+ clientId,+ content,+ documentId,+ editorData,+ parentCommentId,+ replyTo,+ userId: user?.id ?? null,+ workspaceId,+ });+ },+ [user?.avatar, user?.fullName, user?.id, user?.username, workspaceId],+ );+};++export const useDocumentCommentThreads = (documentId?: string | null) => {+ const workspaceId = useActiveWorkspaceId();+ const getKey = useCallback(+ (_index: number, previous: DocumentCommentThreadPage | null) => {+ if (!documentId || !workspaceId || previous?.nextCursor === null) return null;+ return documentCommentKeys.threads(+ workspaceId,+ documentId,+ previous?.nextCursor ?? undefined,+ );+ },+ [documentId, workspaceId],+ );+ const response = useSWRInfinite<DocumentCommentThreadPage>(getKey, fetchThreads, {+ revalidateFirstPage: false,+ });++ return {+ ...response,+ ...getPaginationState(+ response.data,+ response.error,+ response.isLoading,+ response.isValidating,+ response.size,+ ),+ items: flattenDocumentCommentThreads(response.data),+ loadMore: () => response.setSize((current) => current + 1),+ reload: () => response.mutate(),+ };+};++export const useDocumentCommentReplies = (+ rootCommentId: string | null | undefined,+ enabled: boolean,+) => {+ const workspaceId = useActiveWorkspaceId();+ const getKey = useCallback(+ (_index: number, previous: DocumentCommentReplyPage | null) => {+ if (!enabled || !rootCommentId || !workspaceId || previous?.nextCursor === null) return null;+ return documentCommentKeys.replies(+ workspaceId,+ rootCommentId,+ previous?.nextCursor ?? undefined,+ );+ },+ [enabled, rootCommentId, workspaceId],+ );+ const response = useSWRInfinite<DocumentCommentReplyPage>(getKey, fetchReplies, {+ revalidateFirstPage: false,+ });++ return {+ ...response,+ ...getPaginationState(+ response.data,+ response.error,+ response.isLoading,+ response.isValidating,+ response.size,+ ),+ items: flattenDocumentCommentReplies(response.data),+ loadMore: () => response.setSize((current) => current + 1),+ reload: () => response.mutate(),+ };+};diff --git a/src/features/PageEditor/DocumentComments/index.tsx b/src/features/PageEditor/DocumentComments/index.tsxnew file mode 100644index 00000000000..c3dd55f05b2--- /dev/null+++ b/src/features/PageEditor/DocumentComments/index.tsx@@ -0,0 +1,212 @@+'use client';++import { Center, Empty, Flexbox, Skeleton } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { MessageCircle } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import AsyncError from '@/components/AsyncError';+import SurfaceSkeleton from '@/components/Skeleton/Surface';+import { documentCommentService } from '@/services/documentComment';++import Composer from './Composer';+import {+ useDocumentCommentSummary,+ useDocumentCommentThreads,+ useOptimisticDocumentComment,+} from './hooks';+import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';+import {+ appendOptimisticThread,+ removeOptimisticThread,+ replaceOptimisticThread,+ replaceThreadComment,+ updateThreadReplyCount,+} from './optimistic';+import { styles } from './styles';+import Thread from './Thread';++const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {+ const { t } = useTranslation('file');+ const workspaceId = useActiveWorkspaceId();+ const summary = useDocumentCommentSummary(workspaceId ? documentId : undefined);+ const threads = useDocumentCommentThreads(workspaceId ? documentId : undefined);+ const createOptimistic = useOptimisticDocumentComment();+ const reloadSummary = summary.mutate;+ const reloadThreads = threads.reload;+ const mutateThreads = threads.mutate;+ const refresh = useCallback(async () => {+ await Promise.all([reloadThreads(), reloadSummary()]);+ }, [reloadSummary, reloadThreads]);+ const updateSummaryTotal = useCallback(+ (delta: number) =>+ reloadSummary(+ (current) =>+ current ? { ...current, total: Math.max(0, current.total + delta) } : current,+ { revalidate: false },+ ),+ [reloadSummary],+ );+ const updateReplyCount = useCallback(+ (rootCommentId: string, delta: number) =>+ mutateThreads((pages) => updateThreadReplyCount(pages, rootCommentId, delta), {+ revalidate: false,+ }),+ [mutateThreads],+ );+ const handleCreate = useCallback(+ async ({ clientId, content, editorData }: DocumentCommentSubmitInput) => {+ const optimisticComment = createOptimistic({ clientId, content, documentId, editorData });+ await Promise.all([+ mutateThreads((pages) => appendOptimisticThread(pages, optimisticComment), {+ revalidate: false,+ }),+ updateSummaryTotal(1),+ ]);++ let created: Awaited<ReturnType<typeof documentCommentService.create>>;+ try {+ created = await documentCommentService.create({+ clientId,+ content,+ documentId,+ editorData,+ });+ if (!created) throw new Error('Document comment creation returned no result');+ } catch (error) {+ await Promise.all([+ mutateThreads((pages) => removeOptimisticThread(pages, clientId), {+ revalidate: false,+ }),+ updateSummaryTotal(-1),+ ]);+ throw error;+ }++ try {+ await mutateThreads((pages) => replaceOptimisticThread(pages, created.comment), {+ revalidate: false,+ });+ } catch (error) {+ console.error('Failed to reconcile the created document comment', error);+ void reloadThreads();+ }+ if (created.isDuplicate) void reloadSummary();+ },+ [createOptimistic, documentId, mutateThreads, reloadSummary, reloadThreads, updateSummaryTotal],+ );+ const handleUpdate: DocumentCommentUpdateHandler = useCallback(+ async (comment, value) => {+ const optimisticComment = { ...comment, ...value, updatedAt: new Date() };+ await mutateThreads((pages) => replaceThreadComment(pages, optimisticComment), {+ revalidate: false,+ });++ let updated: Awaited<ReturnType<typeof documentCommentService.update>>;+ try {+ updated = await documentCommentService.update({ ...value, id: comment.id });+ if (!updated) throw new Error('Document comment update returned no result');+ } catch (error) {+ await mutateThreads((pages) => replaceThreadComment(pages, comment), {+ revalidate: false,+ });+ throw error;+ }++ try {+ await mutateThreads((pages) => replaceThreadComment(pages, updated), {+ revalidate: false,+ });+ } catch (error) {+ console.error('Failed to reconcile the updated document comment', error);+ void reloadThreads();+ }+ },+ [mutateThreads, reloadThreads],+ );+ const isHeaderLoading = threads.isLoadingInitial || (summary.isLoading && !summary.data);++ if (!workspaceId) return null;++ return (+ <Flexbox+ data-document-comments+ className={styles.section}+ gap={24}+ onClick={(event) => event.stopPropagation()}+ >+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ {isHeaderLoading ? (+ <>+ <Skeleton.Button active style={{ height: 28, width: 48 }} />+ <Skeleton.Button active style={{ height: 20, width: 16 }} />+ </>+ ) : (+ <>+ <Text as={'h2'} fontSize={20} weight={600}>+ {t('pageEditor.comments.title')}+ </Text>+ {summary.data && (+ <Text className={styles.meta} fontSize={14}>+ {summary.data.total}+ </Text>+ )}+ </>+ )}+ </Flexbox>++ {threads.isInitialError ? (+ <AsyncError error={threads.error} variant={'block'} onRetry={() => void threads.reload()} />+ ) : threads.isLoadingInitial ? (+ <SurfaceSkeleton header={false} variant={'list'} />+ ) : threads.items.length === 0 ? (+ <Center className={styles.empty}>+ <Empty description={t('pageEditor.comments.empty')} icon={MessageCircle} />+ </Center>+ ) : (+ <Flexbox className={styles.threadList}>+ {threads.items.map(({ replyCount, root }) => (+ <Thread+ documentId={documentId}+ key={root.id}+ replyCount={replyCount}+ root={root}+ onMutated={refresh}+ onReplyCountChange={updateReplyCount}+ onRootUpdate={handleUpdate}+ onSummaryChange={updateSummaryTotal}+ />+ ))}+ {threads.error ? (+ <AsyncError+ error={threads.error}+ retrying={threads.isRetrying}+ variant={'inline'}+ onRetry={() => void threads.reload()}+ />+ ) : (+ threads.hasMore && (+ <Center paddingBlock={12}>+ <Button+ loading={threads.isLoadingMore}+ type={'text'}+ onClick={() => void threads.loadMore()}+ >+ {t('pageEditor.comments.loadMore')}+ </Button>+ </Center>+ )+ )}+ </Flexbox>+ )}++ <Composer documentId={documentId} key={`root:${documentId}`} onSubmit={handleCreate} />+ </Flexbox>+ );+});++DocumentComments.displayName = 'DocumentComments';++export default DocumentComments;diff --git a/src/features/PageEditor/DocumentComments/optimistic.test.ts b/src/features/PageEditor/DocumentComments/optimistic.test.tsnew file mode 100644index 00000000000..8c304baba8e--- /dev/null+++ b/src/features/PageEditor/DocumentComments/optimistic.test.ts@@ -0,0 +1,161 @@+import type { DocumentCommentItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import {+ appendOptimisticReply,+ appendOptimisticThread,+ createOptimisticComment,+ flattenDocumentCommentReplies,+ isOptimisticDocumentComment,+ removeOptimisticReply,+ removeOptimisticThread,+ replaceOptimisticReply,+ replaceOptimisticThread,+ replaceReplyComment,+ replaceThreadComment,+ updateThreadReplyCount,+} from './optimistic';++const createComment = (+ id: string,+ createdAt: Date = new Date('2026-01-01T00:00:00Z'),+): DocumentCommentItem => ({+ author: {+ avatar: null,+ fullName: 'Lin',+ id: 'user-1',+ status: 'active',+ username: 'lin',+ },+ authorUserId: 'user-1',+ canDelete: true,+ canEdit: true,+ clientId: `client-${id}`,+ content: id,+ createdAt,+ deletedAt: null,+ documentId: 'document-1',+ editorData: null,+ id,+ parentCommentId: null,+ replyTo: null,+ replyToCommentId: null,+ updatedAt: createdAt,+ workspaceId: 'workspace-1',+});++describe('document comment optimistic cache', () => {+ it('marks only temporary client comments as optimistic', () => {+ expect(isOptimisticDocumentComment({ id: 'optimistic:pending' })).toBe(true);+ expect(isOptimisticDocumentComment({ id: 'dcm_server' })).toBe(false);+ });++ it('adds, reconciles, and rolls back a root comment without a refetch', () => {+ const optimistic = createOptimisticComment({+ author: createComment('author').author,+ clientId: 'pending-root',+ content: 'pending',+ documentId: 'document-1',+ editorData: null,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });+ const initial = [+ { items: [{ replyCount: 0, root: createComment('root-1') }], nextCursor: null },+ ];+ const inserted = appendOptimisticThread(initial, optimistic);++ expect(inserted[0].items.map(({ root }) => root.id)).toEqual([+ 'root-1',+ 'optimistic:pending-root',+ ]);++ const serverComment = { ...optimistic, canDelete: true, canEdit: true, id: 'root-2' };+ expect(replaceOptimisticThread(inserted, serverComment)?.[0].items.at(-1)?.root).toEqual(+ serverComment,+ );+ expect(removeOptimisticThread(inserted, optimistic.clientId)?.[0].items).toHaveLength(1);+ });++ it('keeps optimistic replies oldest-first across paginated data and maintains totals', () => {+ const first = createComment('reply-1', new Date('2026-01-01T00:00:01Z'));+ const second = createComment('reply-2', new Date('2026-01-01T00:00:02Z'));+ const optimistic = createComment('optimistic:pending', new Date('2026-01-01T00:00:03Z'));+ optimistic.clientId = 'pending-reply';+ const initial = [{ items: [first], nextCursor: 'next', total: 2 }];+ const inserted = appendOptimisticReply(initial, optimistic);+ const withNextPage = [...inserted, { items: [second], nextCursor: null }];++ expect(flattenDocumentCommentReplies(withNextPage).map(({ id }) => id)).toEqual([+ 'reply-1',+ 'reply-2',+ 'optimistic:pending',+ ]);+ expect(inserted[0].total).toBe(3);++ const serverComment = { ...optimistic, id: 'reply-3' };+ expect(replaceOptimisticReply(inserted, serverComment)?.[0].items.at(-1)).toEqual(+ serverComment,+ );+ const rolledBack = removeOptimisticReply(inserted, optimistic.clientId);+ expect(rolledBack?.[0]).toMatchObject({ items: [first], total: 2 });+ });++ it('places replies to replies next to their target while keeping a single flat list', () => {+ const first = createComment('reply-1', new Date('2026-01-01T00:00:01Z'));+ const second = createComment('reply-2', new Date('2026-01-01T00:00:02Z'));+ const child = {+ ...createComment('reply-1-child', new Date('2026-01-01T00:00:03Z')),+ replyToCommentId: first.id,+ };+ const grandchild = {+ ...createComment('reply-1-grandchild', new Date('2026-01-01T00:00:04Z')),+ replyToCommentId: child.id,+ };+ const sibling = {+ ...createComment('reply-1-sibling', new Date('2026-01-01T00:00:05Z')),+ replyToCommentId: first.id,+ };++ expect(+ flattenDocumentCommentReplies([+ { items: [first, second, child, grandchild, sibling], nextCursor: null },+ ]).map(({ id }) => id),+ ).toEqual(['reply-1', 'reply-1-child', 'reply-1-grandchild', 'reply-1-sibling', 'reply-2']);+ });++ it('updates a thread reply count without affecting other threads', () => {+ const pages = [+ {+ items: [+ { replyCount: 1, root: createComment('root-1') },+ { replyCount: 3, root: createComment('root-2') },+ ],+ nextCursor: null,+ },+ ];++ expect(updateThreadReplyCount(pages, 'root-1', 1)?.[0].items).toMatchObject([+ { replyCount: 2, root: { id: 'root-1' } },+ { replyCount: 3, root: { id: 'root-2' } },+ ]);+ });++ it('optimistically replaces root and reply content by their server ids', () => {+ const root = createComment('root-1');+ const reply = createComment('reply-1');+ const updatedRoot = { ...root, content: 'updated root' };+ const updatedReply = { ...reply, content: 'updated reply' };++ expect(+ replaceThreadComment(+ [{ items: [{ replyCount: 1, root }], nextCursor: null }],+ updatedRoot,+ )?.[0].items[0].root.content,+ ).toBe('updated root');+ expect(+ replaceReplyComment([{ items: [reply], nextCursor: null }], updatedReply)?.[0].items[0]+ .content,+ ).toBe('updated reply');+ });+});diff --git a/src/features/PageEditor/DocumentComments/optimistic.ts b/src/features/PageEditor/DocumentComments/optimistic.tsnew file mode 100644index 00000000000..d241fc425a2--- /dev/null+++ b/src/features/PageEditor/DocumentComments/optimistic.ts@@ -0,0 +1,229 @@+import type {+ DocumentCommentAuthor,+ DocumentCommentItem,+ DocumentCommentJson,+ DocumentCommentReplyPage,+ DocumentCommentThreadPage,+} from '@lobechat/types';++interface CreateOptimisticCommentParams {+ author: DocumentCommentAuthor;+ clientId: string;+ content: string;+ documentId: string;+ editorData: DocumentCommentJson | null;+ parentCommentId?: string;+ replyTo?: DocumentCommentItem['replyTo'];+ userId: string | null;+ workspaceId: string;+}++export interface DocumentCommentSubmitInput {+ clientId: string;+ content: string;+ editorData: DocumentCommentJson;+}++export interface DocumentCommentEditorValue {+ content: string;+ editorData: DocumentCommentJson;+}++export type DocumentCommentUpdateHandler = (+ comment: DocumentCommentItem,+ value: DocumentCommentEditorValue,+) => Promise<void>;++export const isOptimisticDocumentComment = (comment: Pick<DocumentCommentItem, 'id'>) =>+ comment.id.startsWith('optimistic:');++const compareComments = (first: DocumentCommentItem, second: DocumentCommentItem) => {+ const timeDelta = new Date(first.createdAt).getTime() - new Date(second.createdAt).getTime();+ return timeDelta || first.id.localeCompare(second.id);+};++export const flattenDocumentCommentThreads = (pages: DocumentCommentThreadPage[] | undefined) => {+ const threads = new Map<string, DocumentCommentThreadPage['items'][number]>();+ for (const thread of pages?.flatMap((page) => page.items) ?? []) {+ threads.set(thread.root.id, thread);+ }+ return [...threads.values()].sort((first, second) => compareComments(first.root, second.root));+};++export const flattenDocumentCommentReplies = (pages: DocumentCommentReplyPage[] | undefined) => {+ const replies = new Map<string, DocumentCommentItem>();+ for (const reply of pages?.flatMap((page) => page.items) ?? []) replies.set(reply.id, reply);+ const chronologicalReplies = [...replies.values()].sort(compareComments);+ const childrenByReplyId = new Map<string, DocumentCommentItem[]>();+ const threadReplies: DocumentCommentItem[] = [];++ for (const reply of chronologicalReplies) {+ const targetId = reply.replyToCommentId;+ if (targetId && targetId !== reply.id && replies.has(targetId)) {+ const children = childrenByReplyId.get(targetId) ?? [];+ children.push(reply);+ childrenByReplyId.set(targetId, children);+ } else {+ threadReplies.push(reply);+ }+ }++ const orderedReplies: DocumentCommentItem[] = [];+ const visitedIds = new Set<string>();+ const appendReplyTree = (reply: DocumentCommentItem) => {+ if (visitedIds.has(reply.id)) return;+ visitedIds.add(reply.id);+ orderedReplies.push(reply);+ for (const child of childrenByReplyId.get(reply.id) ?? []) appendReplyTree(child);+ };++ for (const reply of threadReplies) appendReplyTree(reply);+ for (const reply of chronologicalReplies) appendReplyTree(reply);+ return orderedReplies;+};++export const createOptimisticComment = ({+ author,+ clientId,+ content,+ documentId,+ editorData,+ parentCommentId,+ replyTo = null,+ userId,+ workspaceId,+}: CreateOptimisticCommentParams): DocumentCommentItem => {+ const now = new Date();++ return {+ author,+ authorUserId: userId,+ canDelete: false,+ canEdit: false,+ clientId,+ content,+ createdAt: now,+ deletedAt: null,+ documentId,+ editorData,+ id: `optimistic:${clientId}`,+ parentCommentId: parentCommentId ?? null,+ replyTo,+ replyToCommentId: replyTo?.id ?? null,+ updatedAt: now,+ workspaceId,+ };+};++export const appendOptimisticThread = (+ pages: DocumentCommentThreadPage[] | undefined,+ comment: DocumentCommentItem,+): DocumentCommentThreadPage[] => {+ if (!pages?.length) return [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }];+ if (pages.some((page) => page.items.some(({ root }) => root.clientId === comment.clientId))) {+ return pages;+ }++ const nextPages = [...pages];+ const lastPage = nextPages.at(-1)!;+ nextPages[nextPages.length - 1] = {+ ...lastPage,+ items: [...lastPage.items, { replyCount: 0, root: comment }],+ };+ return nextPages;+};++export const replaceOptimisticThread = (+ pages: DocumentCommentThreadPage[] | undefined,+ comment: DocumentCommentItem,+) =>+ pages?.map((page) => ({+ ...page,+ items: page.items.map((thread) =>+ thread.root.clientId === comment.clientId ? { ...thread, root: comment } : thread,+ ),+ }));++export const replaceThreadComment = (+ pages: DocumentCommentThreadPage[] | undefined,+ comment: DocumentCommentItem,+) =>+ pages?.map((page) => ({+ ...page,+ items: page.items.map((thread) =>+ thread.root.id === comment.id ? { ...thread, root: comment } : thread,+ ),+ }));++export const removeOptimisticThread = (+ pages: DocumentCommentThreadPage[] | undefined,+ clientId: string,+) =>+ pages?.map((page) => ({+ ...page,+ items: page.items.filter(({ root }) => root.clientId !== clientId),+ }));++export const appendOptimisticReply = (+ pages: DocumentCommentReplyPage[] | undefined,+ comment: DocumentCommentItem,+): DocumentCommentReplyPage[] => {+ if (!pages?.length) return [{ items: [comment], nextCursor: null, total: 1 }];+ if (pages.some((page) => page.items.some((item) => item.clientId === comment.clientId))) {+ return pages;+ }++ const nextPages = [...pages];+ const lastPage = nextPages.at(-1)!;+ nextPages[nextPages.length - 1] = {+ ...lastPage,+ items: [...lastPage.items, comment],+ ...(lastPage.total === undefined ? {} : { total: lastPage.total + 1 }),+ };+ return nextPages;+};++export const replaceOptimisticReply = (+ pages: DocumentCommentReplyPage[] | undefined,+ comment: DocumentCommentItem,+) =>+ pages?.map((page) => ({+ ...page,+ items: page.items.map((item) => (item.clientId === comment.clientId ? comment : item)),+ }));++export const replaceReplyComment = (+ pages: DocumentCommentReplyPage[] | undefined,+ comment: DocumentCommentItem,+) =>+ pages?.map((page) => ({+ ...page,+ items: page.items.map((item) => (item.id === comment.id ? comment : item)),+ }));++export const removeOptimisticReply = (+ pages: DocumentCommentReplyPage[] | undefined,+ clientId: string,+) =>+ pages?.map((page) => {+ const removedCount = page.items.filter((item) => item.clientId === clientId).length;+ return {+ ...page,+ items: page.items.filter((item) => item.clientId !== clientId),+ ...(page.total === undefined ? {} : { total: Math.max(0, page.total - removedCount) }),+ };+ });++export const updateThreadReplyCount = (+ pages: DocumentCommentThreadPage[] | undefined,+ rootCommentId: string,+ delta: number,+) =>+ pages?.map((page) => ({+ ...page,+ items: page.items.map((thread) =>+ thread.root.id === rootCommentId+ ? { ...thread, replyCount: Math.max(0, thread.replyCount + delta) }+ : thread,+ ),+ }));diff --git a/src/features/PageEditor/DocumentComments/styles.ts b/src/features/PageEditor/DocumentComments/styles.tsnew file mode 100644index 00000000000..5538f83ee03--- /dev/null+++ b/src/features/PageEditor/DocumentComments/styles.ts@@ -0,0 +1,106 @@+import { createStaticStyles, cssVar } from 'antd-style';++export const styles = createStaticStyles(({ css }) => ({+ actions: css`+ margin-inline-start: 40px;+ padding-block-start: 8px;+ color: ${cssVar.colorTextTertiary};+ `,+ body: css`+ margin-inline-start: 40px;+ padding-block-start: 8px;+ line-height: 1.7;+ `,+ card: css`+ padding-block: 20px 12px;+ `,+ commentEditor: css`+ min-width: 0;++ /* Rich Markdown blocks carry document margins by default. A chat input+ keeps only inter-block rhythm so the first typed heading never jumps. */+ & [contenteditable='true'] > :first-child {+ margin-block-start: 0 !important;+ }++ & [contenteditable='true'] > :last-child {+ margin-block-end: 0 !important;+ }+ `,+ composer: css`+ min-width: 0;+ transition:+ border-color ${cssVar.motionDurationFast},+ box-shadow ${cssVar.motionDurationFast};++ &:focus-within {+ border-color: ${cssVar.colorPrimary};+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};+ }+ `,+ composerAvatar: css`+ flex: none;+ align-self: flex-start;+ `,+ deleted: css`+ font-style: italic;+ color: ${cssVar.colorTextTertiary};+ `,+ editComposer: css`+ min-width: 0;++ &:focus-within {+ border-color: ${cssVar.colorPrimary};+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};+ }+ `,+ empty: css`+ min-height: 120px;+ `,+ header: css`+ min-height: 32px;+ `,+ meta: css`+ color: ${cssVar.colorTextTertiary};+ `,+ replyBody: css`+ margin-inline-start: 36px;+ `,+ replyCard: css`+ padding-block: 12px 8px;+ `,+ replyCardActions: css`+ margin-inline-start: 36px;+ `,+ replyList: css`+ margin-inline-start: 40px;+ padding-block: 4px;+ padding-inline-start: 16px;+ `,+ replyTargetIcon: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ `,+ section: css`+ width: 100%;+ margin-block-start: 64px;+ padding-block-end: 80px;+ `,+ textarea: css`+ resize: none;+ padding: 0;+ font-size: ${cssVar.fontSize};+ line-height: ${cssVar.lineHeight};+ `,+ thread: css`+ padding-block-end: 20px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: 0;+ }+ `,+ threadList: css`+ gap: 8px;+ `,+}));diff --git a/src/features/PageEditor/DocumentComments/useAutoLoadReplies.test.ts b/src/features/PageEditor/DocumentComments/useAutoLoadReplies.test.tsnew file mode 100644index 00000000000..3eaaeb9f6ca--- /dev/null+++ b/src/features/PageEditor/DocumentComments/useAutoLoadReplies.test.ts@@ -0,0 +1,58 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useAutoLoadReplies } from './useAutoLoadReplies';++describe('useAutoLoadReplies', () => {+ afterEach(() => vi.unstubAllGlobals());++ it('waits for the thread to approach the viewport before loading replies', async () => {+ let callback: IntersectionObserverCallback | undefined;+ const disconnect = vi.fn();+ const observe = vi.fn();+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(next: IntersectionObserverCallback) {+ callback = next;+ }++ disconnect = disconnect;+ observe = observe;+ unobserve = vi.fn();+ },+ );+ const { result } = renderHook(() => useAutoLoadReplies(true));+ const container = document.createElement('div');++ act(() => result.current.containerRef(container));+ expect(observe).toHaveBeenCalledWith(container);+ expect(result.current.shouldLoad).toBe(false);++ act(() =>+ callback?.(+ [{ isIntersecting: true } as IntersectionObserverEntry],+ {} as IntersectionObserver,+ ),+ );+ await waitFor(() => expect(result.current.shouldLoad).toBe(true));+ expect(disconnect).toHaveBeenCalled();+ });++ it('does not observe threads without replies', () => {+ const observe = vi.fn();+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ disconnect = vi.fn();+ observe = observe;+ unobserve = vi.fn();+ },+ );+ const { result } = renderHook(() => useAutoLoadReplies(false));++ act(() => result.current.containerRef(document.createElement('div')));+ expect(observe).not.toHaveBeenCalled();+ expect(result.current.shouldLoad).toBe(false);+ });+});diff --git a/src/features/PageEditor/DocumentComments/useAutoLoadReplies.ts b/src/features/PageEditor/DocumentComments/useAutoLoadReplies.tsnew file mode 100644index 00000000000..b1fa7183158--- /dev/null+++ b/src/features/PageEditor/DocumentComments/useAutoLoadReplies.ts@@ -0,0 +1,28 @@+import { useCallback, useEffect, useState } from 'react';++export const useAutoLoadReplies = (enabled: boolean) => {+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ const [shouldLoad, setShouldLoad] = useState(false);+ const containerRef = useCallback((node: HTMLDivElement | null) => setContainer(node), []);++ useEffect(() => {+ if (!enabled || shouldLoad || !container) return;+ if (typeof IntersectionObserver === 'undefined') {+ setShouldLoad(true);+ return;+ }++ const observer = new IntersectionObserver(+ (entries) => {+ if (!entries.some(({ isIntersecting }) => isIntersecting)) return;+ setShouldLoad(true);+ observer.disconnect();+ },+ { rootMargin: '300px 0px' },+ );+ observer.observe(container);+ return () => observer.disconnect();+ }, [container, enabled, shouldLoad]);++ return { containerRef, shouldLoad };+};diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 5280b2e9022..168b4f7cf18 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -18,6 +18,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';import { usePageStore } from '@/store/page';import { StyleSheet } from '@/utils/styles';+import DocumentComments from './DocumentComments';import EditorCanvas from './EditorCanvas';import Header from './Header';import LockedAlert from './LockedAlert';@@ -315,6 +316,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {compact status badge lives in the Header (EditingIndicator). */}<LockedAlert /><EditorCanvas askCopilotTarget={askCopilotTarget} />+ {documentId && <DocumentComments documentId={documentId} />}</Flexbox></WideScreenContainer></Flexbox>diff --git a/src/features/PageEditor/resourceEventUtils.test.ts b/src/features/PageEditor/resourceEventUtils.test.tsnew file mode 100644index 00000000000..d43090cc57a--- /dev/null+++ b/src/features/PageEditor/resourceEventUtils.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { shouldIgnoreResourceEvent } from './resourceEventUtils';++describe('shouldIgnoreResourceEvent', () => {+ it('allows same-user comment events to refresh another window', () => {+ expect(+ shouldIgnoreResourceEvent({ actorId: 'user-1', type: 'document.commentsChanged' }, 'user-1'),+ ).toBe(false);+ });++ it('continues to suppress other same-user resource echoes', () => {+ expect(shouldIgnoreResourceEvent({ actorId: 'user-1', type: 'doc.updated' }, 'user-1')).toBe(+ true,+ );+ expect(shouldIgnoreResourceEvent({ actorId: 'user-2', type: 'doc.updated' }, 'user-1')).toBe(+ false,+ );+ });+});diff --git a/src/features/PageEditor/resourceEventUtils.ts b/src/features/PageEditor/resourceEventUtils.tsnew file mode 100644index 00000000000..4b4c07bc465--- /dev/null+++ b/src/features/PageEditor/resourceEventUtils.ts@@ -0,0 +1,11 @@+interface ResourceEventIdentity {+ actorId?: string;+ type?: string;+}++export const shouldIgnoreResourceEvent = (+ event: ResourceEventIdentity,+ currentUserId?: string,+): boolean =>+ event.type !== 'document.commentsChanged' &&+ Boolean(event.actorId && currentUserId && event.actorId === currentUserId);diff --git a/src/features/PageEditor/useResourceEvents.ts b/src/features/PageEditor/useResourceEvents.tsindex 358115ca1a9..ab99dc546f3 100644--- a/src/features/PageEditor/useResourceEvents.ts+++ b/src/features/PageEditor/useResourceEvents.ts@@ -4,12 +4,14 @@ import { fetchEventSource } from '@lobechat/utils/client';import { useEffect } from 'react';import { mutate } from '@/libs/swr';+import { isDocumentCommentKeyForEvent } from '@/libs/swr/keys';import { documentService } from '@/services/document';import { documentSWRKeys } from '@/services/document/swrKeys';import { pageSelectors, usePageStore } from '@/store/page';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/slices/auth/selectors';+import { shouldIgnoreResourceEvent } from './resourceEventUtils';import { usePageEditorStore } from './store';const buildHeaders = async (): Promise<Record<string, string>> => {@@ -70,6 +72,7 @@ export const useResourceEvents = () => {expiresAt?: string | null;holderId?: string | null;ownerId?: string | null;+ rootCommentId?: string;};type?: string;};@@ -78,13 +81,22 @@ export const useResourceEvents = () => {} catch {return;}- // Ignore our own echoes.- if (parsed.actorId && parsed.actorId === myUserId) return;+ // Content and lock mutations are already reflected locally, but comment+ // events must reach another window signed in as the same account.+ if (shouldIgnoreResourceEvent(parsed, myUserId)) return;if (parsed.type === 'doc.updated') {// Re-fetch; DocumentIdMode re-hydrates the editor on the new// version when the local editor isn't dirty.void mutate(documentSWRKeys.editor(documentId));+ } else if (parsed.type === 'document.commentsChanged' && workspaceId) {+ void mutate((key) =>+ isDocumentCommentKeyForEvent(key, {+ documentId,+ rootCommentId: parsed.data?.rootCommentId,+ workspaceId,+ }),+ );} else if (parsed.type === 'lock.changed') {// Store the holder verbatim; "locked by other" is derived against// the current user/session at read time (usePageLockedByOther).diff --git a/src/features/Portal/TopicComments/TopicCommentEditor.tsx b/src/features/Portal/TopicComments/TopicCommentEditor.tsxindex ddcd401356e..b74b69d1534 100644--- a/src/features/Portal/TopicComments/TopicCommentEditor.tsx+++ b/src/features/Portal/TopicComments/TopicCommentEditor.tsx@@ -1,22 +1,14 @@import type { TopicCommentJson } from '@lobechat/types';-import type { IEditor, ISlashMenuOption } from '@lobehub/editor';-import { INSERT_MENTION_COMMAND } from '@lobehub/editor';import { Editor, useEditor } from '@lobehub/editor/react';-import { Avatar } from '@lobehub/ui/base-ui';import type { Ref } from 'react';-import { memo, useCallback, useImperativeHandle, useMemo } from 'react';--import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';+import { memo, useCallback, useImperativeHandle } from 'react';import {- createTopicCommentMentionItems,- createTopicCommentMentionPayload,- type MentionableWorkspaceMember,readTopicCommentEditorValue,resolveTopicCommentEditorContent,type TopicCommentEditorValue,- writeTopicCommentMentionMarkdown,} from './editorUtils';+import { useWorkspaceCommentMentionOption } from './useWorkspaceCommentMentionOption';export type { TopicCommentEditorValue } from './editorUtils';@@ -27,9 +19,11 @@ export interface TopicCommentEditorRef {setValue: (value: TopicCommentEditorValue) => void;}-interface TopicCommentEditorProps {+export interface TopicCommentEditorProps {autoFocus?: boolean;+ compact?: boolean;disabled?: boolean;+ enableMarkdown?: boolean;initialContent: string;initialEditorData?: TopicCommentJson | null;onChange?: (value: TopicCommentEditorValue) => void;@@ -41,7 +35,9 @@ const TopicCommentEditor = memo(({ref,autoFocus,+ compact = false,disabled,+ enableMarkdown = false,initialContent,initialEditorData,onChange,@@ -49,23 +45,7 @@ const TopicCommentEditor = memo(placeholder,}: TopicCommentEditorProps & { ref?: Ref<TopicCommentEditorRef> }) => {const editor = useEditor();- const workspaceMembers = useWorkspaceMembers() as MentionableWorkspaceMember[];-- const mentionItems = useMemo<ISlashMenuOption[]>(- () =>- createTopicCommentMentionItems(workspaceMembers).map(({ avatar, ...item }) => ({- ...item,- icon: <Avatar avatar={avatar} size={24} />,- })),- [workspaceMembers],- );-- const handleMentionSelect = useCallback((currentEditor: IEditor, option: ISlashMenuOption) => {- currentEditor.dispatchCommand(- INSERT_MENTION_COMMAND,- createTopicCommentMentionPayload(option),- );- }, []);+ const mentionOption = useWorkspaceCommentMentionOption();const setValue = useCallback((value: TopicCommentEditorValue) => {@@ -96,18 +76,17 @@ const TopicCommentEditor = memo(debounceWait={0}editable={!disabled}editor={editor}- enablePasteMarkdown={false}- markdownOption={false}+ enablePasteMarkdown={enableMarkdown}+ markdownOption={enableMarkdown}+ mentionOption={mentionOption}placeholder={placeholder}- style={{ maxHeight: 184, minHeight: 44, overflowY: 'auto', padding: 0 }}type={type}variant={'chat'}- mentionOption={{- fuseOptions: { keys: ['label', 'metadata.description'], threshold: 0.35 },- items: mentionItems,- markdownWriter: writeTopicCommentMentionMarkdown,- maxLength: 50,- onSelect: handleMentionSelect,+ style={{+ maxHeight: compact ? 120 : 184,+ minHeight: compact ? 24 : 44,+ overflowY: 'auto',+ padding: 0,}}onPressEnter={({ event }) => onPressEnter?.(event)}onTextChange={(currentEditor) => onChange?.(readTopicCommentEditorValue(currentEditor))}diff --git a/src/features/Portal/TopicComments/editorUtils.test.ts b/src/features/Portal/TopicComments/editorUtils.test.tsindex 7d734ec5968..6b185bf9195 100644--- a/src/features/Portal/TopicComments/editorUtils.test.ts+++ b/src/features/Portal/TopicComments/editorUtils.test.ts@@ -1,9 +1,18 @@import type { IEditor } from '@lobehub/editor';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+} from 'lexical';import { describe, expect, it, vi } from 'vitest';import {createTopicCommentMentionItems,createTopicCommentMentionPayload,+ insertTopicCommentMention,readTopicCommentEditorValue,resolveTopicCommentEditorContent,writeTopicCommentMentionMarkdown,@@ -58,8 +67,64 @@ describe('topic comment editor utilities', () => {);});+ it('keeps a text caret after an inserted mention so typing can continue', async () => {+ const lexicalEditor = createEditor();+ await new Promise<void>((resolve) => {+ lexicalEditor.update(+ () => {+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('mention'));+ $getRoot().append(paragraph);+ paragraph.selectEnd();+ },+ { onUpdate: resolve },+ );+ });++ const focus = vi.fn();+ const dispatchCommand = vi.fn();+ const editor = {+ dispatchCommand,+ focus,+ getLexicalEditor: () => lexicalEditor,+ } as unknown as IEditor;+ const option = {+ key: 'member-user-alice',+ label: 'Alice',+ metadata: { id: 'user-alice', type: 'member' },+ };++ insertTopicCommentMention(editor, option);++ await new Promise<void>((resolve) => {+ lexicalEditor.update(() => undefined, { onUpdate: resolve });+ });++ let caret: { offset: number; type: string } | undefined;+ let text = '';+ lexicalEditor.getEditorState().read(() => {+ const selection = $getSelection();+ text = $getRoot().getTextContent();+ if ($isRangeSelection(selection)) {+ caret = { offset: selection.anchor.offset, type: selection.anchor.type };+ }+ });++ expect(text).toBe('mention ');+ expect(caret).toEqual({ offset: 8, type: 'text' });+ expect(focus).toHaveBeenCalledOnce();+ expect(dispatchCommand).toHaveBeenCalledWith(+ expect.anything(),+ createTopicCommentMentionPayload(option),+ );+ });+it('reads markdown and JSON from the editor for create and edit flows', () => {- const editorData = { root: { children: [] } };+ const editorData = {+ root: {+ children: [{ message: undefined, size: undefined, type: 'file', url: '/file.pdf' }],+ },+ };const editor = {getDocument: vi.fn((type: 'json' | 'markdown') =>type === 'json' ? editorData : 'Draft comment',@@ -68,7 +133,9 @@ describe('topic comment editor utilities', () => {expect(readTopicCommentEditorValue(editor)).toEqual({content: 'Draft comment',- editorData,+ editorData: {+ root: { children: [{ type: 'file', url: '/file.pdf' }] },+ },});});diff --git a/src/features/Portal/TopicComments/editorUtils.ts b/src/features/Portal/TopicComments/editorUtils.tsindex 510f37f2b8e..b0c8c3a47c5 100644--- a/src/features/Portal/TopicComments/editorUtils.ts+++ b/src/features/Portal/TopicComments/editorUtils.ts@@ -1,5 +1,7 @@import type { TopicCommentJson } from '@lobechat/types';import type { IEditor, ISlashMenuOption } from '@lobehub/editor';+import { INSERT_MENTION_COMMAND } from '@lobehub/editor';+import { $getSelection, $isRangeSelection } from 'lexical';export interface MentionableWorkspaceMember {user?: {@@ -53,10 +55,33 @@ export const createTopicCommentMentionPayload = (option: ISlashMenuOption) => ({metadata: option.metadata,});-export const readTopicCommentEditorValue = (editor: IEditor): TopicCommentEditorValue => ({- content: String(editor.getDocument('markdown') ?? ''),- editorData: (editor.getDocument('json') ?? null) as unknown as TopicCommentJson,-});+export const insertTopicCommentMention = (editor: IEditor, option: ISlashMenuOption) => {+ editor.dispatchCommand(INSERT_MENTION_COMMAND, createTopicCommentMentionPayload(option));++ editor.getLexicalEditor()?.update(() => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return;++ // An inline decorator at the end of a paragraph has no DOM text position for the caret.+ // Keep a trailing text node selected so typing can continue immediately after the mention.+ selection.insertText(' ');+ });+ editor.focus();+};++export const readTopicCommentEditorValue = (editor: IEditor): TopicCommentEditorValue => {+ const editorData = editor.getDocument('json') ?? null;++ return {+ content: String(editor.getDocument('markdown') ?? ''),+ // Lexical nodes can expose optional properties with an `undefined` value+ // (for example a FileNode without message/size). tRPC and PostgreSQL accept+ // JSON values only, so normalize the editor snapshot at this shared+ // boundary before comments are drafted or submitted.+ // eslint-disable-next-line unicorn/prefer-structured-clone -- structuredClone preserves undefined properties.+ editorData: JSON.parse(JSON.stringify(editorData)) as TopicCommentJson,+ };+};export const resolveTopicCommentEditorContent = (initialContent: string,diff --git a/src/features/Portal/TopicComments/useWorkspaceCommentMentionOption.tsx b/src/features/Portal/TopicComments/useWorkspaceCommentMentionOption.tsxnew file mode 100644index 00000000000..f9fc55d2247--- /dev/null+++ b/src/features/Portal/TopicComments/useWorkspaceCommentMentionOption.tsx@@ -0,0 +1,47 @@+import type { IEditor, ISlashMenuOption } from '@lobehub/editor';+import type { EditorProps } from '@lobehub/editor/react';+import { Avatar } from '@lobehub/ui/base-ui';+import { useCallback, useMemo } from 'react';++import { useFetchWorkspaceMembers } from '@/business/client/hooks/useFetchWorkspaceMembers';+import { useWorkspaceMembers } from '@/business/client/hooks/useWorkspaceMembers';++import {+ createTopicCommentMentionItems,+ insertTopicCommentMention,+ type MentionableWorkspaceMember,+ writeTopicCommentMentionMarkdown,+} from './editorUtils';++/**+ * Shared comment mention source. Mention metadata carries a stable `type`, so+ * Agent candidates can be merged here later without changing the editor JSON.+ */+export const useWorkspaceCommentMentionOption = (): EditorProps['mentionOption'] => {+ useFetchWorkspaceMembers();+ const workspaceMembers = useWorkspaceMembers() as MentionableWorkspaceMember[];++ const mentionItems = useMemo<ISlashMenuOption[]>(+ () =>+ createTopicCommentMentionItems(workspaceMembers).map(({ avatar, ...item }) => ({+ ...item,+ icon: <Avatar avatar={avatar} size={24} />,+ })),+ [workspaceMembers],+ );++ const handleMentionSelect = useCallback((editor: IEditor, option: ISlashMenuOption) => {+ insertTopicCommentMention(editor, option);+ }, []);++ return useMemo(+ () => ({+ fuseOptions: { keys: ['label', 'metadata.description'], threshold: 0.35 },+ items: mentionItems,+ markdownWriter: writeTopicCommentMentionMarkdown,+ maxLength: 50,+ onSelect: handleMentionSelect,+ }),+ [handleMentionSelect, mentionItems],+ );+};diff --git a/src/features/Settings/apikey/features/ApiKey.test.tsx b/src/features/Settings/apikey/features/ApiKey.test.tsxindex 9c3a750fba5..c7349a93a31 100644--- a/src/features/Settings/apikey/features/ApiKey.test.tsx+++ b/src/features/Settings/apikey/features/ApiKey.test.tsx@@ -100,6 +100,7 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {onChange={(event) => onChange?.(event.currentTarget.checked)}/>),+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,toast: hoisted.toast,};});diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 5c2935811c9..1b69030e130 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -1,7 +1,15 @@import { unstable_serialize } from 'swr';import { describe, expect, it } from 'vitest';-import { agentBuilderKeys, recentKeys, resourceKeys, taskKeys, workKeys } from './keys';+import {+ agentBuilderKeys,+ documentCommentKeys,+ isDocumentCommentKeyForEvent,+ recentKeys,+ resourceKeys,+ taskKeys,+ workKeys,+} from './keys';import { CACHE_TIERS } from './localStorageProvider';describe('recentKeys', () => {@@ -100,6 +108,44 @@ describe('resourceKeys', () => {});});+describe('isDocumentCommentKeyForEvent', () => {+ const event = {+ documentId: 'document-1',+ rootCommentId: 'root-1',+ workspaceId: 'workspace-1',+ };++ it('matches the affected summary, thread pages, and reply thread', () => {+ expect(isDocumentCommentKeyForEvent(documentCommentKeys.summary('document-1'), event)).toBe(+ true,+ );+ expect(+ isDocumentCommentKeyForEvent(+ documentCommentKeys.threads('workspace-1', 'document-1', 'cursor'),+ event,+ ),+ ).toBe(true);+ expect(+ isDocumentCommentKeyForEvent(+ documentCommentKeys.replies('workspace-1', 'root-1', 'cursor'),+ event,+ ),+ ).toBe(true);+ });++ it('does not invalidate other documents, workspaces, or reply threads', () => {+ expect(+ isDocumentCommentKeyForEvent(documentCommentKeys.threads('workspace-2', 'document-1'), event),+ ).toBe(false);+ expect(isDocumentCommentKeyForEvent(documentCommentKeys.summary('document-2'), event)).toBe(+ false,+ );+ expect(+ isDocumentCommentKeyForEvent(documentCommentKeys.replies('workspace-1', 'root-2'), event),+ ).toBe(false);+ });+});+describe('agentBuilderKeys', () => {// Regression: builder suggestion chips were memory-only (no CACHE_TIERS entry),// so every page load showed a skeleton and paid a fresh LLM generation. The keydiff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex bdef3dab485..512940b3549 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -172,6 +172,47 @@ export const topicCommentKeys = {]),};+// ---- document comment ---------------------------------------------------+export const documentCommentKeys = {+ replies: def(+ 'documentComment:replies',+ (workspaceId: string | null, rootCommentId: string, cursor?: string) => [+ 'documentComment:replies',+ workspaceId ?? '',+ rootCommentId,+ cursor ?? '',+ ],+ ),+ summary: def('documentComment:summary', (documentId: string) => [+ 'documentComment:summary',+ documentId,+ ]),+ threads: def(+ 'documentComment:threads',+ (workspaceId: string | null, documentId: string, cursor?: string) => [+ 'documentComment:threads',+ workspaceId ?? '',+ documentId,+ cursor ?? '',+ ],+ ),+};++export const isDocumentCommentKeyForEvent = (+ key: unknown,+ event: { documentId: string; rootCommentId?: string; workspaceId: string },+): boolean => {+ if (!Array.isArray(key)) return false;++ if (key[0] === documentCommentKeys.summary.root) return key[1] === event.documentId;+ if (key[1] !== event.workspaceId) return false;+ if (key[0] === documentCommentKeys.threads.root) return key[2] === event.documentId;+ if (key[0] === documentCommentKeys.replies.root) {+ return !event.rootCommentId || key[2] === event.rootCommentId;+ }+ return false;+};+// ---- agent --------------------------------------------------------------export const agentKeys = {/** Sidebar agent list. */@@ -1333,6 +1374,7 @@ export const swrKeys = {tool: toolKeys,topic: topicKeys,topicComment: topicCommentKeys,+ documentComment: documentCommentKeys,topicAction: topicActionKeys,user: userKeys,userMemory: userMemoryKeys,diff --git a/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx b/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsxindex 2a5a104d9cf..cf8ad94fdf8 100644--- a/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx+++ b/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx@@ -37,12 +37,12 @@ vi.mock('@lobehub/ui', () => ({),Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,Icon: () => <span />,- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,}));vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({...((await importOriginal()) as Record<string, unknown>),Tabs: () => <div />,+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsxindex 70b7921b011..cb10612c7b5 100644--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx@@ -23,6 +23,16 @@ vi.mock('@lobehub/ui', () => ({),}));+vi.mock('@lobehub/ui/base-ui', () => ({+ ActionIcon: ({ title, onClick }: { title?: string; onClick?: () => void }) => (+ <button+ aria-label={title}+ data-testid={title ? undefined : 'overflow-menu-button'}+ onClick={onClick}+ />+ ),+}));+vi.mock('./useMenu', () => ({useMenu: () => ({menuHeader: <div data-testid={'topic-info-header'} />,diff --git a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsxindex 6344604422a..aa8d38a2d95 100644--- a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx@@ -14,6 +14,12 @@ vi.mock('@lobehub/ui/base-ui', () => ({),}));+vi.mock('@lobehub/ui/base-ui', () => ({+ ActionIcon: ({ active, onClick }: { active?: boolean; onClick?: () => void }) => (+ <button data-active={String(active)} data-testid="terminal-panel-toggle" onClick={onClick} />+ ),+}));+vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsxindex 2f063b81c6d..8b3453389e7 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx@@ -56,6 +56,19 @@ const mocks = vi.hoisted(() => {});vi.mock('@lobehub/ui', () => ({+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,+ Icon: () => <span />,+ Input: (props: Record<string, unknown>) => {+ mocks.inputProps.all.push(props);+ return <input readOnly disabled={props.disabled as boolean} value={props.value as string} />;+ },+ Skeleton: {+ Button: () => <div />,+ },+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++vi.mock('@lobehub/ui/base-ui', () => ({ActionIcon: (props: Record<string, unknown>) => {mocks.actionIconProps.all.push(props);return (@@ -69,17 +82,7 @@ vi.mock('@lobehub/ui', () => ({{props.children as ReactNode}</button>),- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- Icon: () => <span />,- Input: (props: Record<string, unknown>) => {- mocks.inputProps.all.push(props);- return <input readOnly disabled={props.disabled as boolean} value={props.value as string} />;- },- Skeleton: {- Button: () => <div />,- },Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,- Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,}));vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsxindex 20dfc397cf2..a3e0f64454d 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx@@ -1,4 +1,5 @@import { act, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import WorkspaceAgentDevicePolicy from './WorkspaceAgentDevicePolicy';@@ -41,6 +42,7 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({role="combobox"/>),+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,}));vi.mock('@/features/DeviceManager/useDeviceList', () => ({diff --git a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx b/src/routes/(main)/community/(detail)/_layout/Header.test.tsxindex 2ac1f91eabf..299f602cc75 100644--- a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx+++ b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx@@ -19,6 +19,12 @@ vi.mock('@lobehub/ui/base-ui', () => ({),}));+vi.mock('@lobehub/ui/base-ui', () => ({+ ActionIcon: ({ onClick }: { onClick?: () => void }) => (+ <button data-testid="back-button" onClick={onClick} />+ ),+}));+vi.mock('@/features/NavHeader', () => ({default: ({ left, right }: { left?: React.ReactNode; right?: React.ReactNode }) => (<header>diff --git a/src/services/documentComment.ts b/src/services/documentComment.tsnew file mode 100644index 00000000000..979321d3e6b--- /dev/null+++ b/src/services/documentComment.ts@@ -0,0 +1,21 @@+import type { CreateDocumentCommentInput, UpdateDocumentCommentInput } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++class DocumentCommentService {+ create = (input: CreateDocumentCommentInput) => lambdaClient.documentComment.create.mutate(input);++ delete = (id: string) => lambdaClient.documentComment.delete.mutate({ id });++ listReplies = (params: { cursor?: string; limit?: number; rootCommentId: string }) =>+ lambdaClient.documentComment.listReplies.query(params);++ listThreads = (params: { cursor?: string; documentId: string; limit?: number }) =>+ lambdaClient.documentComment.listThreads.query(params);++ summary = (documentId: string) => lambdaClient.documentComment.summary.query({ documentId });++ update = (input: UpdateDocumentCommentInput) => lambdaClient.documentComment.update.mutate(input);+}++export const documentCommentService = new DocumentCommentService();