feat(comments): add internal comments and author comment editing (#552)

* feat(comments): add internal comments and author comment editing

* chore(i18n): add Korean comment translations and update AGENTS.md i18n rule

* style(comments): refine visibility selector corner radius and align send button height

* fix(webui): avoid ResizeObserver loop when resizing file browser
This commit is contained in:
Yiling-J
2026-11-26 14:54:45 +08:00
committed by GitHub
parent 1066900c78
commit fee6f39828
43 changed files with 2751 additions and 301 deletions
+363
View File
@@ -5964,4 +5964,367 @@ describe('AssetService — natural sort by name', () => {
expect(variant).toContain('http://mock-s3-url')
})
})
describe('internal comments and comment editing', () => {
async function setupCommentFixture() {
const team = await prisma.team.create({ data: { name: 'Comment Team' } })
const author = await prisma.user.create({
data: { name: 'Author', email: `author-${Date.now()}-${Math.random()}@test.com` },
})
const owner = await prisma.user.create({
data: { name: 'Owner', email: `owner-${Date.now()}-${Math.random()}@test.com` },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: author.id, role: 'editor' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: owner.id, role: 'owner' },
})
const project = await prisma.project.create({
data: { name: 'Comment Project', teamId: team.id },
})
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.folder,
projectId: project.id,
status: AssetStatus.uploaded,
},
})
const file = await prisma.asset.create({
data: {
name: 'clip.mp4',
type: AssetType.file,
projectId: project.id,
parentId: rootFolder.id,
creatorId: author.id,
status: AssetStatus.uploaded,
},
})
return { team, author, owner, project, rootFolder, file }
}
async function createAttachmentAsset(projectId: string, creatorId: string, name: string) {
const storageKey = await prisma.storageKey.create({
data: { key: `files/attachments/${Date.now()}-${Math.random()}-${name}` },
})
return prisma.asset.create({
data: {
name,
type: AssetType.attachment,
projectId,
creatorId,
status: AssetStatus.uploaded,
storageKeyId: storageKey.id,
},
})
}
it('creates public (default) and internal comments, and enforces internal replies on internal parents', async () => {
const { author, owner, file } = await setupCommentFixture()
const pub = await assetService.createComment(
{ assetId: file.id, userId: author.id, message: 'Public feedback', attachmentIds: [] },
{ triggerAgents: false },
)
expect(pub.isInternal).toBe(false)
const internal = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Internal note',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
expect(internal.isInternal).toBe(true)
// Replying to an internal parent forces isInternal: true even if false is passed
const replyToInternal = await assetService.createComment(
{
assetId: file.id,
userId: owner.id,
replyToId: internal.id,
message: 'Internal reply',
attachmentIds: [],
isInternal: false,
},
{ triggerAgents: false },
)
expect(replyToInternal.isInternal).toBe(true)
// Replying internally to a public parent is allowed
const internalReplyOnPublic = await assetService.createComment(
{
assetId: file.id,
userId: owner.id,
replyToId: pub.id,
message: 'Private side note',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
expect(internalReplyOnPublic.isInternal).toBe(true)
const publicReplyOnPublic = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: pub.id,
message: 'Public reply',
attachmentIds: [],
isInternal: false,
},
{ triggerAgents: false },
)
expect(publicReplyOnPublic.isInternal).toBe(false)
// Authenticated list includes everything
const allListed = await assetService.listComments(file.id, { first: 20 }, author.id)
expect(allListed.data).toHaveLength(2)
expect(allListed.data[0].replies).toHaveLength(2)
expect(allListed.data[1].replies).toHaveLength(1)
// Public share list excludes internal comments and internal replies
const publicListed = await assetService.listComments(file.id, { first: 20 }, undefined, {
excludeInternal: true,
})
expect(publicListed.data).toHaveLength(1)
expect(publicListed.data[0].id).toBe(pub.id)
expect(publicListed.data[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
// listAllComments with excludeInternal matches
const publicAll = await assetService.listAllComments(file.id, undefined, {
excludeInternal: true,
})
expect(publicAll).toHaveLength(1)
expect(publicAll[0].replies.map((r) => r.id)).toEqual([publicReplyOnPublic.id])
})
it('excludes internal comments and replies under internal parents from public share commentsCount', async () => {
const { author, rootFolder, file } = await setupCommentFixture()
const pub = await assetService.createComment(
{ assetId: file.id, userId: author.id, message: 'Public', attachmentIds: [] },
{ triggerAgents: false },
)
await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: pub.id,
message: 'Internal reply on public',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
const internal = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Internal root',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: internal.id,
message: 'Reply on internal',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
const allChildren = await assetService.listChildren({
assetId: rootFolder.id,
assetType: 'file',
})
expect(allChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(4)
const publicChildren = await assetService.listChildren(
{ assetId: rootFolder.id, assetType: 'file' },
{ excludeInternalComments: true },
)
expect(publicChildren.data.find((a) => a.id === file.id)?.commentsCount).toBe(1)
const publicFile = await assetService.getAsset(
{ assetId: file.id },
{ excludeInternalComments: true },
)
expect(publicFile.commentsCount).toBe(1)
})
it('rejects replying to an internal comment from a public share link', async () => {
const { author, file } = await setupCommentFixture()
const internal = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Internal only',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
await expect(
assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: internal.id,
message: 'Guest reply attempt',
attachmentIds: [],
},
{ triggerAgents: false, shareLinkId: 'share-1' },
),
).rejects.toMatchObject({ status: 404 })
})
it('allows author to edit text, visibility, remove timestamp, and add/delete attachments', async () => {
const { author, project, file } = await setupCommentFixture()
const att1 = await createAttachmentAsset(project.id, author.id, 'old.png')
const att2 = await createAttachmentAsset(project.id, author.id, 'keep.pdf')
const att3 = await createAttachmentAsset(project.id, author.id, 'new.png')
const created = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Original message',
second: 12.5,
attachmentIds: [att1.id, att2.id],
isInternal: false,
},
{ triggerAgents: false },
)
const updated = await assetService.updateComment({
commentId: created.id,
userId: author.id,
message: 'Updated message',
isInternal: true,
second: null,
attachmentIds: [att2.id, att3.id],
})
expect(updated.message).toBe('Updated message')
expect(updated.isInternal).toBe(true)
expect(updated.second).toBeNull()
expect(updated.attachments.map((a) => a.assetId).sort()).toEqual([att2.id, att3.id].sort())
// Removed attachment asset should be cleaned up since no comment references it anymore
expect(await prisma.asset.findUnique({ where: { id: att1.id } })).toBeNull()
expect(await prisma.asset.findUnique({ where: { id: att2.id } })).not.toBeNull()
expect(await prisma.asset.findUnique({ where: { id: att3.id } })).not.toBeNull()
})
it('enforces author-only edit, parent-internal reply constraint, non-empty validation, and preserves reply flags', async () => {
const { author, owner, file } = await setupCommentFixture()
const parent = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
message: 'Parent comment',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
const reply = await assetService.createComment(
{
assetId: file.id,
userId: author.id,
replyToId: parent.id,
message: 'Internal reply',
attachmentIds: [],
isInternal: true,
},
{ triggerAgents: false },
)
// Non-author (even team owner) cannot edit
await expect(
assetService.updateComment({
commentId: parent.id,
userId: owner.id,
message: 'Owner edit attempt',
}),
).rejects.toMatchObject({ status: 403 })
// Reply cannot be made public while parent is internal
await expect(
assetService.updateComment({
commentId: reply.id,
userId: author.id,
isInternal: false,
}),
).rejects.toMatchObject({ status: 400 })
// Empty comment without attachments or annotations is rejected
await expect(
assetService.updateComment({
commentId: parent.id,
userId: author.id,
message: ' ',
attachmentIds: [],
}),
).rejects.toMatchObject({ status: 400 })
// Toggling parent Internal -> Public keeps reply's own isInternal flag intact
const toggledParent = await assetService.updateComment({
commentId: parent.id,
userId: author.id,
isInternal: false,
})
expect(toggledParent.isInternal).toBe(false)
expect(toggledParent.replies[0].isInternal).toBe(true)
// Agent comments cannot be edited
const agentUser = await prisma.user.create({
data: {
name: 'Bot',
email: `bot-${Date.now()}-${Math.random()}@test.com`,
type: 'agent',
},
})
const agent = await prisma.agent.create({
data: {
id: agentUser.id,
teamId: (await prisma.project.findUniqueOrThrow({ where: { id: file.projectId! } }))
.teamId,
type: 'chat',
config: { provider: 'openai', model: 'gpt-4' },
},
})
const session = await prisma.agentSession.create({
data: { agentId: agent.id, cwd: '/tmp' },
})
const agentComment = await prisma.assetComment.create({
data: {
assetId: file.id,
creatorId: author.id,
sessionId: session.id,
message: 'Agent generated reply',
},
})
await expect(
assetService.updateComment({
commentId: agentComment.id,
userId: author.id,
message: 'Try edit agent',
}),
).rejects.toMatchObject({ status: 403 })
})
})
})
+207 -12
View File
@@ -743,7 +743,10 @@ export class AssetService {
}
}
async listChildren(req: ListChildrenRequest): Promise<PaginatedData<AssetInfo[]>> {
async listChildren(
req: ListChildrenRequest,
options?: { excludeInternalComments?: boolean },
): Promise<PaginatedData<AssetInfo[]>> {
let typesToQuery: AssetType[]
if (req.assetType === 'file') {
typesToQuery = [AssetType.file, AssetType.version_stack]
@@ -831,6 +834,7 @@ export class AssetService {
const infos = await this.toAssetInfos(assets, undefined, {
includeDeletedChildren: req.showDeleted,
excludeInternalComments: options?.excludeInternalComments,
})
return { data: infos, pageInfo }
@@ -1107,7 +1111,10 @@ export class AssetService {
return this.getAsset({ assetId: asset.id })
}
async getAsset(req: GetAssetRequest): Promise<AssetInfo> {
async getAsset(
req: GetAssetRequest,
options?: { excludeInternalComments?: boolean },
): Promise<AssetInfo> {
const a = await this.prismaClient.asset.findUnique({
where: { id: req.assetId },
include: assetInclude,
@@ -1130,7 +1137,9 @@ export class AssetService {
afs.push({ id: row.id, name: row.name })
}
const infos = await this.toAssetInfos([a])
const infos = await this.toAssetInfos([a], undefined, {
excludeInternalComments: options?.excludeInternalComments,
})
const info = infos[0]
info.ancestorFolders = afs
@@ -2001,16 +2010,39 @@ export class AssetService {
let actualReplyToId = req.replyToId
let parentComment = null
let parentIsInternal = false
if (req.replyToId) {
parentComment = await tx.assetComment.findUnique({
where: { id: req.replyToId },
include: { creator: true },
include: {
creator: true,
replyTo: { select: { id: true, isInternal: true } },
},
})
if (options.shareLinkId) {
if (
!parentComment ||
parentComment.assetId !== a.id ||
parentComment.isInternal ||
parentComment.replyTo?.isInternal
) {
throw new HTTPException(404, { message: 'Comment not found' })
}
}
if (parentComment?.replyToId) {
actualReplyToId = parentComment.replyToId
parentIsInternal = Boolean(parentComment.isInternal || parentComment.replyTo?.isInternal)
} else if (parentComment) {
parentIsInternal = parentComment.isInternal
}
}
const isInternal = options.shareLinkId
? false
: parentIsInternal
? true
: Boolean(req.isInternal)
const attachmentIds = await this.lockCommentAttachments(tx, req.attachmentIds, {
projectId: a.projectId,
userId: req.userId,
@@ -2023,6 +2055,7 @@ export class AssetService {
annotation: req.annotations,
second: req.second,
replyToId: actualReplyToId,
isInternal,
},
})
commentId = comment.id
@@ -2221,6 +2254,145 @@ export class AssetService {
return this.getComment(commentId, userId)
}
async updateComment(params: {
commentId: string
userId: string
message?: string
isInternal?: boolean
second?: number | null
attachmentIds?: string[]
}): Promise<CommentInfo> {
await this.prismaClient.$transaction(async (tx) => {
const comment = await tx.assetComment.findUnique({
where: { id: params.commentId },
select: {
id: true,
creatorId: true,
sessionId: true,
message: true,
annotation: true,
second: true,
isInternal: true,
attachments: { select: { assetId: true } },
replyTo: { select: { isInternal: true } },
asset: { select: { projectId: true } },
},
})
if (!comment) {
throw new HTTPException(404, { message: 'Comment not found' })
}
if (comment.sessionId !== null || comment.creatorId !== params.userId) {
throw new HTTPException(403, { message: 'Only the comment author can edit this comment' })
}
if (comment.replyTo?.isInternal && params.isInternal === false) {
throw new HTTPException(400, {
message: 'Cannot make a reply public when its parent comment is internal',
})
}
const existingAttachmentIds = comment.attachments.map(({ assetId }) => assetId)
const existingSet = new Set(existingAttachmentIds)
let toAdd: string[] = []
let toRemove: string[] = []
let keptCount = existingAttachmentIds.length
if (params.attachmentIds !== undefined) {
const desiredIds = Array.from(new Set(params.attachmentIds))
const desiredSet = new Set(desiredIds)
toAdd = desiredIds.filter((id) => !existingSet.has(id))
toRemove = existingAttachmentIds.filter((id) => !desiredSet.has(id))
keptCount = existingAttachmentIds.filter((id) => desiredSet.has(id)).length
}
const idsToLock = Array.from(new Set([...toAdd, ...toRemove]))
let claimedToAdd: string[] = []
let lockedToRemove: string[] = []
if (idsToLock.length > 0) {
const lockedRows = await tx.$queryRaw<
{ id: string; projectId: string | null; creatorId: string | null }[]
>`
SELECT id, project_id AS "projectId", creator_id AS "creatorId" FROM assets
WHERE id IN (${Prisma.join(idsToLock)}) AND type = 'attachment'
ORDER BY id
FOR NO KEY UPDATE
`
const toAddSet = new Set(toAdd)
const toRemoveSet = new Set(toRemove)
const ownedToAdd = lockedRows
.filter(
(row) =>
toAddSet.has(row.id) &&
row.projectId === comment.asset.projectId &&
row.creatorId === params.userId,
)
.map((row) => row.id)
lockedToRemove = lockedRows.filter((row) => toRemoveSet.has(row.id)).map((row) => row.id)
if (ownedToAdd.length > 0) {
const unclaimed = await tx.asset.findMany({
where: { id: { in: ownedToAdd }, commentAttachments: { none: {} } },
select: { id: true },
})
claimedToAdd = unclaimed.map(({ id }) => id)
}
}
const finalMessage = params.message !== undefined ? params.message : (comment.message ?? '')
const hasAnnotations = Array.isArray(comment.annotation) && comment.annotation.length > 0
const finalAttachmentCount = keptCount + claimedToAdd.length
if (!finalMessage.trim() && finalAttachmentCount === 0 && !hasAnnotations) {
throw new HTTPException(400, { message: 'Comment cannot be empty' })
}
if (toRemove.length > 0) {
await tx.assetCommentAttachment.deleteMany({
where: {
commentId: params.commentId,
assetId: { in: toRemove },
},
})
if (lockedToRemove.length > 0) {
await tx.asset.deleteMany({
where: { id: { in: lockedToRemove }, commentAttachments: { none: {} } },
})
}
}
if (claimedToAdd.length > 0) {
await tx.assetCommentAttachment.createMany({
data: claimedToAdd.map((assetId) => ({ assetId, commentId: params.commentId })),
})
}
const updateData: Prisma.AssetCommentUpdateInput = {}
if (params.message !== undefined) {
updateData.message = params.message
}
if (params.isInternal !== undefined) {
updateData.isInternal = params.isInternal
}
if (params.second !== undefined) {
updateData.second = params.second
}
if (Object.keys(updateData).length > 0) {
await tx.assetComment.update({
where: { id: params.commentId },
data: updateData,
})
}
})
return this.getComment(params.commentId, params.userId)
}
async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise<void> {
const comment = await this.prismaClient.assetComment.findUnique({
where: { id: commentId },
@@ -2283,7 +2455,7 @@ export class AssetService {
})
}
private getCommentInclude() {
private getCommentInclude(options?: { excludeInternal?: boolean }) {
return {
creator: true,
completionLastChangedBy: true,
@@ -2296,6 +2468,7 @@ export class AssetService {
orderBy: { createdAt: 'asc' as const },
},
replies: {
...(options?.excludeInternal ? { where: { isInternal: false } } : {}),
include: {
creator: true,
completionLastChangedBy: true,
@@ -2316,14 +2489,20 @@ export class AssetService {
assetId: string,
params: PaginationParams,
requestingUserId?: string,
options?: { excludeInternal?: boolean },
): Promise<PaginatedData<CommentInfo[]>> {
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
const where: Prisma.AssetCommentWhereInput = {
assetId: resolvedAssetId,
replyToId: null,
...(options?.excludeInternal ? { isInternal: false } : {}),
}
const { data: comments, pageInfo } = await paginateQuery(
async (skip, take) => {
return this.prismaClient.assetComment.findMany({
where: { assetId: resolvedAssetId, replyToId: null },
include: this.getCommentInclude(),
where,
include: this.getCommentInclude(options),
skip,
take,
orderBy: { id: 'asc' },
@@ -2331,7 +2510,7 @@ export class AssetService {
},
async () =>
this.prismaClient.assetComment.count({
where: { assetId: resolvedAssetId, replyToId: null },
where,
}),
params,
)
@@ -2341,12 +2520,20 @@ export class AssetService {
return { data: infos, pageInfo }
}
async listAllComments(assetId: string, requestingUserId?: string): Promise<CommentInfo[]> {
async listAllComments(
assetId: string,
requestingUserId?: string,
options?: { excludeInternal?: boolean },
): Promise<CommentInfo[]> {
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
const comments = await this.prismaClient.assetComment.findMany({
where: { assetId: resolvedAssetId, replyToId: null },
include: this.getCommentInclude(),
where: {
assetId: resolvedAssetId,
replyToId: null,
...(options?.excludeInternal ? { isInternal: false } : {}),
},
include: this.getCommentInclude(options),
orderBy: { id: 'asc' },
})
@@ -2461,9 +2648,10 @@ export class AssetService {
async toAssetInfos(
assets: AssetWithIncludes[],
previewFormat?: PreviewFormat,
options?: { includeDeletedChildren?: boolean },
options?: { includeDeletedChildren?: boolean; excludeInternalComments?: boolean },
): Promise<AssetInfo[]> {
const includeDeletedChildren = options?.includeDeletedChildren ?? false
const excludeInternalComments = options?.excludeInternalComments ?? false
const stackIds = new Set<string>()
for (const a of assets) {
@@ -2553,6 +2741,12 @@ export class AssetService {
by: ['assetId'],
where: {
assetId: { in: Array.from(commentTargetIds) },
...(excludeInternalComments
? {
isInternal: false,
OR: [{ replyToId: null }, { replyTo: { isInternal: false } }],
}
: {}),
},
_count: { _all: true },
})
@@ -3429,6 +3623,7 @@ export class AssetService {
updatedAt: c.updatedAt.toISOString(),
sessionId: c.sessionId,
isCompleted: c.isCompleted,
isInternal: c.isInternal,
completionLastChangedBy,
reactionCounts,
}
+3
View File
@@ -12,6 +12,8 @@ export interface PostCommentParams {
/** Timecode in seconds (or the encoded viewing angle for 3D models). */
second?: number
attachmentIds?: string[]
/** Whether the comment is internal and hidden from public share links (default false). */
isInternal?: boolean
/** Whether mentions of agents start a chat with them (default true). */
triggerAgents?: boolean
}
@@ -31,6 +33,7 @@ export class CommentService {
annotations: params.annotations,
second: params.second,
attachmentIds: params.attachmentIds ?? [],
isInternal: params.isInternal,
},
{ triggerAgents: params.triggerAgents },
)
@@ -240,7 +240,12 @@ describe('collaboration Operations', () => {
message: 'Too dark at the start',
second: 2.5,
})
expect(comment).toEqual({ id: expect.any(String), assetId: file, replyToId: null })
expect(comment).toEqual({
id: expect.any(String),
assetId: file,
replyToId: null,
isInternal: false,
})
const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
assetId: file,
@@ -248,9 +253,17 @@ describe('collaboration Operations', () => {
replyToId: comment.id,
})
expect(reply.replyToId).toBe(comment.id)
expect(reply.isInternal).toBe(false)
const internalComment = await runOperation(createCommentOp, as(reviewer), {
assetId: file,
message: 'Internal budget note',
isInternal: true,
})
expect(internalComment.isInternal).toBe(true)
const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
expect(listed.total).toBe(1)
expect(listed.total).toBe(2)
expect(listed.data).toEqual([
expect.objectContaining({
id: comment.id,
@@ -258,14 +271,21 @@ describe('collaboration Operations', () => {
author: { id: reviewer.id, name: 'Reviewer' },
second: 2.5,
resolved: false,
isInternal: false,
replies: [
expect.objectContaining({
id: reply.id,
message: 'Brightened in v2',
author: { id: owner.id, name: 'Owner' },
isInternal: false,
}),
],
}),
expect.objectContaining({
id: internalComment.id,
message: 'Internal budget note',
isInternal: true,
}),
])
await expect(
@@ -276,7 +296,7 @@ describe('collaboration Operations', () => {
).resolves.toEqual({ commentId: comment.id, resolved: false })
const created = await auditRows(AuditAction.comment_create)
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id])
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id, internalComment.id])
expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
const completed = await auditRows(AuditAction.comment_complete)
expect(completed).toHaveLength(2)
@@ -20,10 +20,16 @@ export const createCommentOp = implementOperation(createComment, {
message: input.message,
replyToId: input.replyToId,
second: input.second,
isInternal: input.isInternal,
// Mentions in comments written by Shumai's own agent must not start more agent runs.
triggerAgents: ctx.via !== 'agent',
})
return { id: comment.id, assetId: comment.assetId, replyToId: input.replyToId ?? null }
return {
id: comment.id,
assetId: comment.assetId,
replyToId: input.replyToId ?? null,
isInternal: comment.isInternal,
}
},
audit: (input, output) => [
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
@@ -15,6 +15,7 @@ function toCommentFields(comment: CommentInfo) {
second: comment.second,
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
attachmentCount: comment.attachments.length,
isInternal: comment.isInternal,
createdAt: comment.createdAt,
}
}