|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { copilotChats } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { and, desc, eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { getAccessibleCopilotChat } from '@/lib/copilot/chat/lifecycle' |
| 7 | +import { |
| 8 | + authenticateCopilotRequestSessionOnly, |
| 9 | + createBadRequestResponse, |
| 10 | + createInternalServerErrorResponse, |
| 11 | + createUnauthorizedResponse, |
| 12 | +} from '@/lib/copilot/request/http' |
| 13 | +import { authorizeWorkflowByWorkspacePermission } from '@/lib/workflows/utils' |
| 14 | +import { assertActiveWorkspaceAccess } from '@/lib/workspaces/permissions/utils' |
| 15 | + |
| 16 | +const logger = createLogger('CopilotChatAPI') |
| 17 | + |
| 18 | +function transformChat(chat: { |
| 19 | + id: string |
| 20 | + title: string | null |
| 21 | + model: string | null |
| 22 | + messages: unknown |
| 23 | + planArtifact?: unknown |
| 24 | + config?: unknown |
| 25 | + conversationId?: string | null |
| 26 | + resources?: unknown |
| 27 | + createdAt: Date | null |
| 28 | + updatedAt: Date | null |
| 29 | +}) { |
| 30 | + return { |
| 31 | + id: chat.id, |
| 32 | + title: chat.title, |
| 33 | + model: chat.model, |
| 34 | + messages: Array.isArray(chat.messages) ? chat.messages : [], |
| 35 | + messageCount: Array.isArray(chat.messages) ? chat.messages.length : 0, |
| 36 | + planArtifact: chat.planArtifact || null, |
| 37 | + config: chat.config || null, |
| 38 | + ...('conversationId' in chat ? { activeStreamId: chat.conversationId || null } : {}), |
| 39 | + ...('resources' in chat |
| 40 | + ? { resources: Array.isArray(chat.resources) ? chat.resources : [] } |
| 41 | + : {}), |
| 42 | + createdAt: chat.createdAt, |
| 43 | + updatedAt: chat.updatedAt, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +export async function GET(req: NextRequest) { |
| 48 | + try { |
| 49 | + const { searchParams } = new URL(req.url) |
| 50 | + const workflowId = searchParams.get('workflowId') |
| 51 | + const workspaceId = searchParams.get('workspaceId') |
| 52 | + const chatId = searchParams.get('chatId') |
| 53 | + |
| 54 | + const { userId: authenticatedUserId, isAuthenticated } = |
| 55 | + await authenticateCopilotRequestSessionOnly() |
| 56 | + if (!isAuthenticated || !authenticatedUserId) { |
| 57 | + return createUnauthorizedResponse() |
| 58 | + } |
| 59 | + |
| 60 | + if (chatId) { |
| 61 | + const chat = await getAccessibleCopilotChat(chatId, authenticatedUserId) |
| 62 | + if (!chat) { |
| 63 | + return NextResponse.json({ success: false, error: 'Chat not found' }, { status: 404 }) |
| 64 | + } |
| 65 | + |
| 66 | + logger.info(`Retrieved chat ${chatId}`) |
| 67 | + return NextResponse.json({ success: true, chat: transformChat(chat) }) |
| 68 | + } |
| 69 | + |
| 70 | + if (!workflowId && !workspaceId) { |
| 71 | + return createBadRequestResponse('workflowId, workspaceId, or chatId is required') |
| 72 | + } |
| 73 | + |
| 74 | + if (workspaceId) { |
| 75 | + await assertActiveWorkspaceAccess(workspaceId, authenticatedUserId) |
| 76 | + } |
| 77 | + |
| 78 | + if (workflowId) { |
| 79 | + const authorization = await authorizeWorkflowByWorkspacePermission({ |
| 80 | + workflowId, |
| 81 | + userId: authenticatedUserId, |
| 82 | + action: 'read', |
| 83 | + }) |
| 84 | + if (!authorization.allowed) { |
| 85 | + return createUnauthorizedResponse() |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + const scopeFilter = workflowId |
| 90 | + ? eq(copilotChats.workflowId, workflowId) |
| 91 | + : eq(copilotChats.workspaceId, workspaceId!) |
| 92 | + |
| 93 | + const chats = await db |
| 94 | + .select({ |
| 95 | + id: copilotChats.id, |
| 96 | + title: copilotChats.title, |
| 97 | + model: copilotChats.model, |
| 98 | + messages: copilotChats.messages, |
| 99 | + planArtifact: copilotChats.planArtifact, |
| 100 | + config: copilotChats.config, |
| 101 | + createdAt: copilotChats.createdAt, |
| 102 | + updatedAt: copilotChats.updatedAt, |
| 103 | + }) |
| 104 | + .from(copilotChats) |
| 105 | + .where(and(eq(copilotChats.userId, authenticatedUserId), scopeFilter)) |
| 106 | + .orderBy(desc(copilotChats.updatedAt)) |
| 107 | + |
| 108 | + const scope = workflowId ? `workflow ${workflowId}` : `workspace ${workspaceId}` |
| 109 | + logger.info(`Retrieved ${chats.length} chats for ${scope}`) |
| 110 | + |
| 111 | + return NextResponse.json({ |
| 112 | + success: true, |
| 113 | + chats: chats.map(transformChat), |
| 114 | + }) |
| 115 | + } catch (error) { |
| 116 | + logger.error('Error fetching copilot chats:', error) |
| 117 | + return createInternalServerErrorResponse('Failed to fetch chats') |
| 118 | + } |
| 119 | +} |
0 commit comments