chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Tests for copilot chats list API route
|
||||
*
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { copilotHttpMock, copilotHttpMockFns } from '@sim/testing'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockSelectDistinctOn, mockFrom, mockLeftJoin, mockWhere, mockOrderBy } = vi.hoisted(() => ({
|
||||
mockSelectDistinctOn: vi.fn(),
|
||||
mockFrom: vi.fn(),
|
||||
mockLeftJoin: vi.fn(),
|
||||
mockWhere: vi.fn(),
|
||||
mockOrderBy: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@sim/db', () => ({
|
||||
db: {
|
||||
selectDistinctOn: mockSelectDistinctOn,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('drizzle-orm', () => ({
|
||||
and: vi.fn((...conditions: unknown[]) => ({ conditions, type: 'and' })),
|
||||
eq: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'eq' })),
|
||||
or: vi.fn((...conditions: unknown[]) => ({ conditions, type: 'or' })),
|
||||
inArray: vi.fn((field: unknown, values: unknown) => ({ field, values, type: 'inArray' })),
|
||||
isNull: vi.fn((field: unknown) => ({ field, type: 'isNull' })),
|
||||
desc: vi.fn((field: unknown) => ({ field, type: 'desc' })),
|
||||
sql: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/request/http', () => copilotHttpMock)
|
||||
|
||||
vi.mock('@/lib/workspaces/utils', () => ({
|
||||
listAccessibleWorkspaceRowsForUser: vi
|
||||
.fn()
|
||||
.mockResolvedValue([
|
||||
{ workspace: { id: 'workspace-123', createdAt: new Date() }, permissionType: 'admin' },
|
||||
]),
|
||||
}))
|
||||
|
||||
import { GET } from '@/app/api/copilot/chats/route'
|
||||
|
||||
describe('Copilot Chats List API Route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockSelectDistinctOn.mockReturnValue({ from: mockFrom })
|
||||
mockFrom.mockReturnValue({ leftJoin: mockLeftJoin })
|
||||
mockLeftJoin.mockReturnValue({ leftJoin: mockLeftJoin, where: mockWhere })
|
||||
mockWhere.mockReturnValue({ orderBy: mockOrderBy })
|
||||
mockOrderBy.mockResolvedValue([])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('GET', () => {
|
||||
it('should return 401 when user is not authenticated', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: null,
|
||||
isAuthenticated: false,
|
||||
})
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
const responseData = await response.json()
|
||||
expect(responseData).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('should return empty chats array when user has no chats', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: 'user-123',
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
mockOrderBy.mockResolvedValueOnce([])
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const responseData = await response.json()
|
||||
expect(responseData).toEqual({
|
||||
success: true,
|
||||
chats: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('should return list of chats for authenticated user', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: 'user-123',
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
const mockChats = [
|
||||
{
|
||||
id: 'chat-1',
|
||||
title: 'First Chat',
|
||||
workflowId: 'workflow-1',
|
||||
updatedAt: new Date('2024-01-02'),
|
||||
},
|
||||
{
|
||||
id: 'chat-2',
|
||||
title: 'Second Chat',
|
||||
workflowId: 'workflow-2',
|
||||
updatedAt: new Date('2024-01-01'),
|
||||
},
|
||||
]
|
||||
mockOrderBy.mockResolvedValueOnce(mockChats)
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const responseData = await response.json()
|
||||
expect(responseData.success).toBe(true)
|
||||
expect(responseData.chats).toHaveLength(2)
|
||||
expect(responseData.chats[0].id).toBe('chat-1')
|
||||
expect(responseData.chats[0].title).toBe('First Chat')
|
||||
expect(responseData.chats[1].id).toBe('chat-2')
|
||||
})
|
||||
|
||||
it('should return chats ordered by updatedAt descending', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: 'user-123',
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
const mockChats = [
|
||||
{
|
||||
id: 'newest-chat',
|
||||
title: 'Newest',
|
||||
workflowId: 'workflow-1',
|
||||
updatedAt: new Date('2024-01-10'),
|
||||
},
|
||||
{
|
||||
id: 'older-chat',
|
||||
title: 'Older',
|
||||
workflowId: 'workflow-2',
|
||||
updatedAt: new Date('2024-01-05'),
|
||||
},
|
||||
{
|
||||
id: 'oldest-chat',
|
||||
title: 'Oldest',
|
||||
workflowId: 'workflow-3',
|
||||
updatedAt: new Date('2024-01-01'),
|
||||
},
|
||||
]
|
||||
mockOrderBy.mockResolvedValueOnce(mockChats)
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const responseData = await response.json()
|
||||
expect(responseData.chats[0].id).toBe('newest-chat')
|
||||
expect(responseData.chats[2].id).toBe('oldest-chat')
|
||||
})
|
||||
|
||||
it('should handle chats with null workflowId', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: 'user-123',
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
const mockChats = [
|
||||
{
|
||||
id: 'chat-no-workflow',
|
||||
title: 'Chat without workflow',
|
||||
workflowId: null,
|
||||
updatedAt: new Date('2024-01-01'),
|
||||
},
|
||||
]
|
||||
mockOrderBy.mockResolvedValueOnce(mockChats)
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const responseData = await response.json()
|
||||
expect(responseData.chats[0].workflowId).toBeNull()
|
||||
})
|
||||
|
||||
it('should handle database errors gracefully', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: 'user-123',
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
mockOrderBy.mockRejectedValueOnce(new Error('Database connection failed'))
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
const responseData = await response.json()
|
||||
expect(responseData.error).toBe('Failed to fetch user chats')
|
||||
})
|
||||
|
||||
it('should only return chats belonging to authenticated user', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: 'user-123',
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
const mockChats = [
|
||||
{
|
||||
id: 'my-chat',
|
||||
title: 'My Chat',
|
||||
workflowId: 'workflow-1',
|
||||
updatedAt: new Date('2024-01-01'),
|
||||
},
|
||||
]
|
||||
mockOrderBy.mockResolvedValueOnce(mockChats)
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
await GET(request as any)
|
||||
|
||||
expect(mockSelectDistinctOn).toHaveBeenCalled()
|
||||
expect(mockWhere).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should return 401 when userId is null despite isAuthenticated being true', async () => {
|
||||
copilotHttpMockFns.mockAuthenticateCopilotRequestSessionOnly.mockResolvedValueOnce({
|
||||
userId: null,
|
||||
isAuthenticated: true,
|
||||
})
|
||||
|
||||
const request = new Request('http://localhost:3000/api/copilot/chats')
|
||||
const response = await GET(request as any)
|
||||
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import { db } from '@sim/db'
|
||||
import { copilotChats, workflow } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { authorizeWorkflowByWorkspacePermission } from '@sim/platform-authz/workflow'
|
||||
import { and, desc, eq, inArray, isNull, or } from 'drizzle-orm'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { createWorkflowCopilotChatContract } from '@/lib/api/contracts/copilot'
|
||||
import { parseRequest, validationErrorResponse } from '@/lib/api/server'
|
||||
import { resolveOrCreateChat } from '@/lib/copilot/chat/lifecycle'
|
||||
import { chatPubSub } from '@/lib/copilot/chat-status'
|
||||
import {
|
||||
authenticateCopilotRequestSessionOnly,
|
||||
createBadRequestResponse,
|
||||
createForbiddenResponse,
|
||||
createInternalServerErrorResponse,
|
||||
createUnauthorizedResponse,
|
||||
} from '@/lib/copilot/request/http'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import {
|
||||
assertActiveWorkspaceAccess,
|
||||
isWorkspaceAccessDeniedError,
|
||||
} from '@/lib/workspaces/permissions/utils'
|
||||
import { listAccessibleWorkspaceRowsForUser } from '@/lib/workspaces/utils'
|
||||
|
||||
const logger = createLogger('CopilotChatsListAPI')
|
||||
|
||||
const DEFAULT_COPILOT_MODEL = 'claude-opus-4-6'
|
||||
|
||||
export const GET = withRouteHandler(async (_request: NextRequest) => {
|
||||
try {
|
||||
const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly()
|
||||
if (!isAuthenticated || !userId) {
|
||||
return createUnauthorizedResponse()
|
||||
}
|
||||
|
||||
// Active accessible workspaces (explicit + org-derived). Using the active
|
||||
// scope keeps the archived-workspace exclusion the old join-based query had.
|
||||
const accessibleRows = await listAccessibleWorkspaceRowsForUser(userId)
|
||||
const accessibleWorkspaceIds = accessibleRows.map((row) => row.workspace.id)
|
||||
const inAccessibleWorkspace =
|
||||
accessibleWorkspaceIds.length > 0
|
||||
? or(
|
||||
inArray(workflow.workspaceId, accessibleWorkspaceIds),
|
||||
and(
|
||||
isNull(copilotChats.workflowId),
|
||||
inArray(copilotChats.workspaceId, accessibleWorkspaceIds)
|
||||
)
|
||||
)
|
||||
: undefined
|
||||
|
||||
const visibleChats = await db
|
||||
.selectDistinctOn([copilotChats.id], {
|
||||
id: copilotChats.id,
|
||||
title: copilotChats.title,
|
||||
workflowId: copilotChats.workflowId,
|
||||
workspaceId: copilotChats.workspaceId,
|
||||
activeStreamId: copilotChats.conversationId,
|
||||
updatedAt: copilotChats.updatedAt,
|
||||
})
|
||||
.from(copilotChats)
|
||||
.leftJoin(workflow, eq(copilotChats.workflowId, workflow.id))
|
||||
.where(
|
||||
and(
|
||||
eq(copilotChats.userId, userId),
|
||||
or(
|
||||
and(isNull(copilotChats.workflowId), isNull(copilotChats.workspaceId)),
|
||||
inAccessibleWorkspace
|
||||
),
|
||||
or(isNull(workflow.id), isNull(workflow.archivedAt))
|
||||
)
|
||||
)
|
||||
.orderBy(copilotChats.id, desc(copilotChats.updatedAt))
|
||||
|
||||
const sorted = [...visibleChats].sort(
|
||||
(a, b) => new Date(b.updatedAt!).getTime() - new Date(a.updatedAt!).getTime()
|
||||
)
|
||||
|
||||
logger.info(`Retrieved ${sorted.length} chats for user ${userId}`)
|
||||
|
||||
return NextResponse.json({ success: true, chats: sorted })
|
||||
} catch (error) {
|
||||
logger.error('Error fetching user copilot chats:', error)
|
||||
return createInternalServerErrorResponse('Failed to fetch user chats')
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* POST /api/copilot/chats
|
||||
* Creates an empty workflow-scoped copilot chat (same lifecycle as {@link resolveOrCreateChat}).
|
||||
* Matches mothership's POST /api/mothership/chats pattern so the client always selects a real row id.
|
||||
*/
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly()
|
||||
if (!isAuthenticated || !userId) {
|
||||
return createUnauthorizedResponse()
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(
|
||||
createWorkflowCopilotChatContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: (error) =>
|
||||
validationErrorResponse(error, 'workspaceId and workflowId are required'),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
const { workspaceId, workflowId } = parsed.data.body
|
||||
|
||||
await assertActiveWorkspaceAccess(workspaceId, userId)
|
||||
|
||||
const authorization = await authorizeWorkflowByWorkspacePermission({
|
||||
workflowId,
|
||||
userId,
|
||||
action: 'read',
|
||||
})
|
||||
if (!authorization.allowed || !authorization.workflow) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: authorization.message ?? 'Forbidden' },
|
||||
{ status: authorization.status }
|
||||
)
|
||||
}
|
||||
|
||||
if (authorization.workflow.workspaceId !== workspaceId) {
|
||||
return createBadRequestResponse('workflow does not belong to this workspace')
|
||||
}
|
||||
|
||||
const result = await resolveOrCreateChat({
|
||||
userId,
|
||||
workflowId,
|
||||
workspaceId,
|
||||
model: DEFAULT_COPILOT_MODEL,
|
||||
type: 'copilot',
|
||||
})
|
||||
|
||||
if (!result.chatId) {
|
||||
return createInternalServerErrorResponse('Failed to create chat')
|
||||
}
|
||||
|
||||
chatPubSub?.publishStatusChanged({ workspaceId, chatId: result.chatId, type: 'created' })
|
||||
|
||||
return NextResponse.json({ success: true, id: result.chatId })
|
||||
} catch (error) {
|
||||
if (isWorkspaceAccessDeniedError(error)) {
|
||||
return createForbiddenResponse('Workspace access denied')
|
||||
}
|
||||
logger.error('Error creating workflow copilot chat:', error)
|
||||
return createInternalServerErrorResponse('Failed to create chat')
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user