Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions apps/sim/app/api/copilot/chat/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { createLogger } from '@sim/logger'
import { and, desc, eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { getLatestRunForStream } from '@/lib/copilot/async-runs/repository'
import { buildEffectiveChatTranscript } from '@/lib/copilot/chat/effective-transcript'
import { getAccessibleCopilotChat } from '@/lib/copilot/chat/lifecycle'
import { normalizeMessage } from '@/lib/copilot/chat/persisted-message'
import {
authenticateCopilotRequestSessionOnly,
createBadRequestResponse,
Expand Down Expand Up @@ -113,11 +115,23 @@ export async function GET(req: NextRequest) {
}
}

const normalizedMessages = Array.isArray(chat.messages)
? chat.messages
.filter((message): message is Record<string, unknown> => Boolean(message))
.map(normalizeMessage)
: []
const effectiveMessages = buildEffectiveChatTranscript({
messages: normalizedMessages,
activeStreamId: chat.conversationId || null,
...(streamSnapshot ? { streamSnapshot } : {}),
})

logger.info(`Retrieved chat ${chatId}`)
return NextResponse.json({
success: true,
chat: {
...transformChat(chat),
messages: effectiveMessages,
...(streamSnapshot ? { streamSnapshot } : {}),
},
})
Expand Down
160 changes: 160 additions & 0 deletions apps/sim/app/api/copilot/chat/stop/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/**
* @vitest-environment node
*/
import { NextRequest } from 'next/server'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const {
mockGetSession,
mockSelect,
mockFrom,
mockWhereSelect,
mockLimit,
mockUpdate,
mockSet,
mockWhereUpdate,
mockReturning,
mockPublishStatusChanged,
mockSql,
} = vi.hoisted(() => ({
mockGetSession: vi.fn(),
mockSelect: vi.fn(),
mockFrom: vi.fn(),
mockWhereSelect: vi.fn(),
mockLimit: vi.fn(),
mockUpdate: vi.fn(),
mockSet: vi.fn(),
mockWhereUpdate: vi.fn(),
mockReturning: vi.fn(),
mockPublishStatusChanged: vi.fn(),
mockSql: vi.fn((strings: TemplateStringsArray, ...values: unknown[]) => ({ strings, values })),
}))

vi.mock('@/lib/auth', () => ({
getSession: mockGetSession,
}))

vi.mock('@sim/db', () => ({
db: {
select: mockSelect,
update: mockUpdate,
},
}))

vi.mock('@sim/db/schema', () => ({
copilotChats: {
id: 'id',
userId: 'userId',
workspaceId: 'workspaceId',
messages: 'messages',
conversationId: 'conversationId',
},
}))

vi.mock('drizzle-orm', () => ({
and: vi.fn((...conditions: unknown[]) => ({ conditions, type: 'and' })),
eq: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'eq' })),
sql: mockSql,
}))

vi.mock('@/lib/copilot/tasks', () => ({
taskPubSub: {
publishStatusChanged: mockPublishStatusChanged,
},
}))

import { POST } from '@/app/api/copilot/chat/stop/route'

function createRequest(body: Record<string, unknown>) {
return new NextRequest('http://localhost:3000/api/copilot/chat/stop', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
}

describe('copilot chat stop route', () => {
beforeEach(() => {
vi.clearAllMocks()

mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })

mockLimit.mockResolvedValue([
{
workspaceId: 'ws-1',
messages: [{ id: 'stream-1', role: 'user', content: 'hello' }],
},
])
mockWhereSelect.mockReturnValue({ limit: mockLimit })
mockFrom.mockReturnValue({ where: mockWhereSelect })
mockSelect.mockReturnValue({ from: mockFrom })

mockReturning.mockResolvedValue([{ workspaceId: 'ws-1' }])
mockWhereUpdate.mockReturnValue({ returning: mockReturning })
mockSet.mockReturnValue({ where: mockWhereUpdate })
mockUpdate.mockReturnValue({ set: mockSet })
})

it('returns 401 when unauthenticated', async () => {
mockGetSession.mockResolvedValueOnce(null)

const response = await POST(
createRequest({
chatId: 'chat-1',
streamId: 'stream-1',
content: '',
})
)

expect(response.status).toBe(401)
expect(await response.json()).toEqual({ error: 'Unauthorized' })
})

it('is a no-op when the chat is missing', async () => {
mockLimit.mockResolvedValueOnce([])

const response = await POST(
createRequest({
chatId: 'missing-chat',
streamId: 'stream-1',
content: '',
})
)

expect(response.status).toBe(200)
expect(await response.json()).toEqual({ success: true })
expect(mockUpdate).not.toHaveBeenCalled()
})

it('appends a stopped assistant message even with no content', async () => {
const response = await POST(
createRequest({
chatId: 'chat-1',
streamId: 'stream-1',
content: '',
})
)

expect(response.status).toBe(200)
expect(await response.json()).toEqual({ success: true })

const setArg = mockSet.mock.calls[0]?.[0]
expect(setArg).toBeTruthy()
expect(setArg.conversationId).toBeNull()
expect(setArg.messages).toBeTruthy()

const appendedPayload = JSON.parse(setArg.messages.values[1] as string)
expect(appendedPayload).toHaveLength(1)
expect(appendedPayload[0]).toMatchObject({
role: 'assistant',
content: '',
contentBlocks: [{ type: 'complete', status: 'cancelled' }],
})

expect(mockPublishStatusChanged).toHaveBeenCalledWith({
workspaceId: 'ws-1',
chatId: 'chat-1',
type: 'completed',
})
})
})
14 changes: 9 additions & 5 deletions apps/sim/app/api/copilot/chat/stop/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { normalizeMessage, type PersistedMessage } from '@/lib/copilot/chat/persisted-message'
import { taskPubSub } from '@/lib/copilot/tasks'
import { generateId } from '@/lib/core/utils/uuid'

const logger = createLogger('CopilotChatStopAPI')

Expand Down Expand Up @@ -70,7 +71,6 @@ export async function POST(req: NextRequest) {
}

const { chatId, streamId, content, contentBlocks } = StopSchema.parse(await req.json())

const [row] = await db
.select({
workspaceId: copilotChats.workspaceId,
Expand Down Expand Up @@ -106,14 +106,18 @@ export async function POST(req: NextRequest) {

const hasContent = content.trim().length > 0
const hasBlocks = Array.isArray(contentBlocks) && contentBlocks.length > 0

if ((hasContent || hasBlocks) && canAppendAssistant) {
const synthesizedStoppedBlocks = hasBlocks
? contentBlocks
: hasContent
? [{ type: 'text', channel: 'assistant', content }, { type: 'stopped' }]
: [{ type: 'stopped' }]
if (canAppendAssistant) {
const normalized = normalizeMessage({
id: crypto.randomUUID(),
id: generateId(),
role: 'assistant',
content,
timestamp: new Date().toISOString(),
...(hasBlocks ? { contentBlocks } : {}),
contentBlocks: synthesizedStoppedBlocks,
})
const assistantMessage: PersistedMessage = normalized
setClause.messages = sql`${copilotChats.messages} || ${JSON.stringify([assistantMessage])}::jsonb`
Expand Down
15 changes: 14 additions & 1 deletion apps/sim/app/api/mothership/chats/[chatId]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { and, eq, sql } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getLatestRunForStream } from '@/lib/copilot/async-runs/repository'
import { buildEffectiveChatTranscript } from '@/lib/copilot/chat/effective-transcript'
import { getAccessibleCopilotChat } from '@/lib/copilot/chat/lifecycle'
import { normalizeMessage } from '@/lib/copilot/chat/persisted-message'
import {
authenticateCopilotRequestSessionOnly,
createBadRequestResponse,
Expand Down Expand Up @@ -93,12 +95,23 @@ export async function GET(
}
}

const normalizedMessages = Array.isArray(chat.messages)
? chat.messages
.filter((message): message is Record<string, unknown> => Boolean(message))
.map(normalizeMessage)
: []
const effectiveMessages = buildEffectiveChatTranscript({
messages: normalizedMessages,
activeStreamId: chat.conversationId || null,
...(streamSnapshot ? { streamSnapshot } : {}),
})

return NextResponse.json({
success: true,
chat: {
id: chat.id,
title: chat.title,
messages: Array.isArray(chat.messages) ? chat.messages : [],
messages: effectiveMessages,
conversationId: chat.conversationId || null,
resources: Array.isArray(chat.resources) ? chat.resources : [],
createdAt: chat.createdAt,
Expand Down
Loading
Loading