diff --git a/apps/sim/app/api/copilot/feedback/route.ts b/apps/sim/app/api/copilot/feedback/route.ts index bc42f69c40a..0a12a821539 100644 --- a/apps/sim/app/api/copilot/feedback/route.ts +++ b/apps/sim/app/api/copilot/feedback/route.ts @@ -1,12 +1,18 @@ import { db } from '@sim/db' import { copilotFeedback } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { getErrorMessage } from '@sim/utils/errors' import { eq } from 'drizzle-orm' -import { type NextRequest, NextResponse } from 'next/server' +import { NextResponse } from 'next/server' import { submitCopilotFeedbackContract } from '@/lib/api/contracts' -import { parseRequest, validationErrorResponse } from '@/lib/api/server' +import { + defineInternalJsonRoute, + internalJsonPresenters, + internalOrchestrationErrorPolicy, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { submitChatFeedback } from '@/lib/mothership/chat/application/submit-feedback' import { authenticateCopilotRequestSessionOnly, createInternalServerErrorResponse, @@ -17,104 +23,32 @@ import { captureServerEvent } from '@/lib/posthog/server' const logger = createLogger('CopilotFeedbackAPI') -/** - * POST /api/copilot/feedback - * Submit feedback for a copilot interaction - */ -export const POST = withRouteHandler(async (req: NextRequest) => { - const tracker = createRequestTracker() - - try { - // Authenticate user using the same pattern as other copilot routes - const { userId: authenticatedUserId, isAuthenticated } = - await authenticateCopilotRequestSessionOnly() - - if (!isAuthenticated || !authenticatedUserId) { - return createUnauthorizedResponse() - } - - const parsed = await parseRequest( - submitCopilotFeedbackContract, - req, - {}, - { - invalidJson: 'throw', - validationErrorResponse: (error) => { - logger.error('Validation error:', { - requestId: tracker.requestId, - duration: tracker.getDuration(), - errors: error.issues, - }) - return validationErrorResponse(error, 'Invalid request data') - }, - } - ) - if (!parsed.success) return parsed.response - - const { chatId, userQuery, agentResponse, isPositiveFeedback, feedback, workflowYaml } = - parsed.data.body - - logger.info('Processing copilot feedback submission', { - requestId: tracker.requestId, - userId: authenticatedUserId, - chatId, - isPositiveFeedback, - userQueryLength: userQuery.length, - agentResponseLength: agentResponse.length, - hasFeedback: !!feedback, - hasWorkflowYaml: !!workflowYaml, - workflowYamlLength: workflowYaml?.length || 0, +/** Records the caller's rating of an assistant reply in one of their own chats. */ +export const POST = defineInternalJsonRoute({ + contract: submitCopilotFeedbackContract, + operation: submitChatFeedback.operation, + auth: internalSessionAuth, + rateLimit: internalRateLimits.none({ + reason: 'Each rated reply in the caller’s own chat adds one feedback row.', + }), + errorPolicy: internalOrchestrationErrorPolicy, + mapInput: ({ body }) => ({ + chatId: body.chatId, + userQuery: body.userQuery, + agentResponse: body.agentResponse, + isPositive: body.isPositiveFeedback, + feedback: body.feedback, + workflowYaml: body.workflowYaml, + }), + useCase: submitChatFeedback, + present: internalJsonPresenters.withSuccess, + onSuccess: ({ principal, input }) => { + captureServerEvent(principal.userId, 'copilot_feedback_submitted', { + is_positive: input.isPositive, + has_text_feedback: !!input.feedback, + has_workflow_yaml: !!input.workflowYaml, }) - - // Insert feedback into the database - const [feedbackRecord] = await db - .insert(copilotFeedback) - .values({ - userId: authenticatedUserId, - chatId, - userQuery, - agentResponse, - isPositive: isPositiveFeedback, - feedback: feedback || null, - workflowYaml: workflowYaml || null, - }) - .returning() - - logger.info('Successfully saved copilot feedback', { - requestId: tracker.requestId, - feedbackId: feedbackRecord.feedbackId, - userId: authenticatedUserId, - isPositive: isPositiveFeedback, - duration: tracker.getDuration(), - }) - - captureServerEvent(authenticatedUserId, 'copilot_feedback_submitted', { - is_positive: isPositiveFeedback, - has_text_feedback: !!feedback, - has_workflow_yaml: !!workflowYaml, - }) - - return NextResponse.json({ - success: true, - feedbackId: feedbackRecord.feedbackId, - message: 'Feedback submitted successfully', - metadata: { - requestId: tracker.requestId, - duration: tracker.getDuration(), - }, - }) - } catch (error) { - const duration = tracker.getDuration() - - logger.error('Error submitting copilot feedback:', { - requestId: tracker.requestId, - duration, - error: getErrorMessage(error, 'Unknown error'), - stack: error instanceof Error ? error.stack : undefined, - }) - - return createInternalServerErrorResponse('Failed to submit feedback') - } + }, }) /** diff --git a/apps/sim/lib/api/contracts/copilot.ts b/apps/sim/lib/api/contracts/copilot.ts index c5f41ac7fef..61657f7b1a4 100644 --- a/apps/sim/lib/api/contracts/copilot.ts +++ b/apps/sim/lib/api/contracts/copilot.ts @@ -290,11 +290,6 @@ export const submitCopilotFeedbackContract = defineRouteContract({ schema: z.object({ success: z.literal(true), feedbackId: z.string(), - message: z.string(), - metadata: z.object({ - requestId: z.string(), - duration: z.number(), - }), }), }, }) diff --git a/apps/sim/lib/mothership/chat/application/submit-feedback.integration.ts b/apps/sim/lib/mothership/chat/application/submit-feedback.integration.ts new file mode 100644 index 00000000000..cfbda8fb6ab --- /dev/null +++ b/apps/sim/lib/mothership/chat/application/submit-feedback.integration.ts @@ -0,0 +1,141 @@ +/** Drives POST /api/copilot/feedback against real PostgreSQL rows to prove feedback stays on the caller's own chats. */ +import { db } from '@sim/db' +import { + copilotChats, + copilotFeedback, + member, + organization, + permissions, + user, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { authMock, authMockFns } from '@sim/testing/mocks/auth.mock' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { NextRequest } from 'next/server' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { POST } from '@/app/api/copilot/feedback/route' + +vi.mock('@/lib/auth', () => authMock) + +const ownerId = generateId() +const outsiderId = generateId() +const workspaceId = generateId() +const organizationId = generateId() +const workspaceChatId = generateId() +const organizationChatId = generateId() + +function submitAs(userId: string, chatId: string) { + authMockFns.mockGetSession.mockResolvedValueOnce({ + user: { id: userId }, + session: { id: generateId() }, + }) + return POST( + new NextRequest('http://localhost:3000/api/copilot/feedback', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + chatId, + userQuery: 'What changed?', + agentResponse: 'Three files changed.', + isPositiveFeedback: false, + feedback: 'Missed one file', + }), + }) + ) +} + +async function feedbackRows(chatId: string) { + return db + .select({ userId: copilotFeedback.userId }) + .from(copilotFeedback) + .where(eq(copilotFeedback.chatId, chatId)) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [ownerId, outsiderId].map((id) => ({ + id, + name: 'Chat feedback fixture', + email: `${id}@chat-feedback.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Chat feedback fixture', + ownerId, + billedAccountUserId: ownerId, + }) + await db.insert(permissions).values( + [ownerId, outsiderId].map((userId) => ({ + id: generateId(), + userId, + entityType: 'workspace' as const, + entityId: workspaceId, + permissionType: 'admin' as const, + })) + ) + await db.insert(organization).values({ + id: organizationId, + name: 'Chat feedback fixture', + slug: organizationId, + createdAt: now, + }) + await db.insert(member).values( + [ownerId, outsiderId].map((userId) => ({ + id: generateId(), + userId, + organizationId, + role: 'member', + createdAt: now, + })) + ) + await db.insert(copilotChats).values([ + { id: workspaceChatId, userId: ownerId, workspaceId, type: 'mothership' }, + { id: organizationChatId, userId: ownerId, organizationId, type: 'mothership' }, + ]) +}) + +afterAll(async () => { + await db + .delete(copilotChats) + .where(inArray(copilotChats.id, [workspaceChatId, organizationChatId])) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(inArray(user.id, [ownerId, outsiderId])) + await db.$client.end() +}) + +describe('copilot feedback stays on the caller’s own chats', () => { + it('records feedback on the owner’s workspace and organization chats', async () => { + for (const chatId of [workspaceChatId, organizationChatId]) { + const response = await submitAs(ownerId, chatId) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ success: true, feedbackId: expect.any(String) }) + expect(await feedbackRows(chatId)).toEqual([{ userId: ownerId }]) + } + }) + + it('answers a member’s foreign chat exactly like an unknown chat and stores nothing', async () => { + const before = await Promise.all([workspaceChatId, organizationChatId].map(feedbackRows)) + const foreign = await submitAs(outsiderId, workspaceChatId) + const foreignOrganization = await submitAs(outsiderId, organizationChatId) + const unknown = await submitAs(outsiderId, generateId()) + + expect(foreign.status).toBe(404) + expect(foreignOrganization.status).toBe(404) + expect(unknown.status).toBe(404) + const { error } = await unknown.json() + expect(error).toBe('Chat not found') + expect((await foreign.json()).error).toBe(error) + expect((await foreignOrganization.json()).error).toBe(error) + expect(await Promise.all([workspaceChatId, organizationChatId].map(feedbackRows))).toEqual( + before + ) + }) +}) diff --git a/apps/sim/lib/mothership/chat/application/submit-feedback.ts b/apps/sim/lib/mothership/chat/application/submit-feedback.ts new file mode 100644 index 00000000000..9b692d35d88 --- /dev/null +++ b/apps/sim/lib/mothership/chat/application/submit-feedback.ts @@ -0,0 +1,63 @@ +import type { SessionPrincipal } from '@sim/auth/principal' +import { db } from '@sim/db' +import { copilotFeedback } from '@sim/db/schema' +import { defineWorkspaceOperation } from '@/lib/core/application' +import { defineOrganizationOperation } from '@/lib/core/application/organization-operation' +import { defineAuthorizedChatUseCase } from '@/lib/mothership/chat/application/authorized-chat-use-case' +import { resolveOwnedChatContext } from '@/lib/mothership/chat/application/context' + +interface SubmitChatFeedbackInput { + chatId: string + userQuery: string + agentResponse: string + isPositive: boolean + feedback?: string + workflowYaml?: string +} + +/** + * Records the owner's rating of an assistant reply. A chat the caller does not own resolves to + * not found, the same as an unknown id, so feedback never attaches to someone else's chat. + */ +export const submitChatFeedback = defineAuthorizedChatUseCase({ + // permission-group-exempt: rating a reply in the caller's own chat starts no turn and reads nothing new + operation: defineWorkspaceOperation({ + id: 'mothership.chats.submit_feedback', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'none', + principalKinds: ['session'], + }), + /** permission-group-exempt: rating a reply in the caller's own chat starts no turn and reads nothing new. */ + organizationOperation: defineOrganizationOperation({ + id: 'mothership.chats.submit_feedback', + minimumRole: 'member', + capability: 'none', + principalKinds: ['session'], + }), + resolveContext({ + principal, + input, + }: { + principal: SessionPrincipal + input: SubmitChatFeedbackInput + }) { + return resolveOwnedChatContext(principal, input.chatId) + }, + authorizationOptions: {}, + async execute({ context, input }) { + const [{ feedbackId }] = await db + .insert(copilotFeedback) + .values({ + userId: context.userId, + chatId: context.chatId, + userQuery: input.userQuery, + agentResponse: input.agentResponse, + isPositive: input.isPositive, + feedback: input.feedback || null, + workflowYaml: input.workflowYaml || null, + }) + .returning({ feedbackId: copilotFeedback.feedbackId }) + return { feedbackId } + }, +})