|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { copilotChats } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { generateId } from '@sim/utils/id' |
| 5 | +import { eq } from 'drizzle-orm' |
| 6 | +import { type NextRequest, NextResponse } from 'next/server' |
| 7 | +import { z } from 'zod' |
| 8 | +import type { PersistedMessage } from '@/lib/copilot/chat/persisted-message' |
| 9 | +import { SIM_AGENT_API_URL } from '@/lib/copilot/constants' |
| 10 | +import { fetchGo } from '@/lib/copilot/request/go/fetch' |
| 11 | +import { |
| 12 | + authenticateCopilotRequestSessionOnly, |
| 13 | + createBadRequestResponse, |
| 14 | + createInternalServerErrorResponse, |
| 15 | + createNotFoundResponse, |
| 16 | + createUnauthorizedResponse, |
| 17 | +} from '@/lib/copilot/request/http' |
| 18 | +import type { MothershipResource } from '@/lib/copilot/resources/types' |
| 19 | +import { taskPubSub } from '@/lib/copilot/tasks' |
| 20 | +import { env } from '@/lib/core/config/env' |
| 21 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 22 | +import { captureServerEvent } from '@/lib/posthog/server' |
| 23 | +import { assertActiveWorkspaceAccess } from '@/lib/workspaces/permissions/utils' |
| 24 | + |
| 25 | +const logger = createLogger('ForkChatAPI') |
| 26 | + |
| 27 | +const ForkChatSchema = z.object({ |
| 28 | + upToMessageId: z.string().min(1), |
| 29 | +}) |
| 30 | + |
| 31 | +/** |
| 32 | + * POST /api/mothership/chats/[chatId]/fork |
| 33 | + * Creates a new chat branched from the given chat, keeping messages up to and |
| 34 | + * including the specified message. Resources and copilot-side state are copied. |
| 35 | + */ |
| 36 | +export const POST = withRouteHandler( |
| 37 | + async (request: NextRequest, { params }: { params: Promise<{ chatId: string }> }) => { |
| 38 | + try { |
| 39 | + const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly() |
| 40 | + if (!isAuthenticated || !userId) { |
| 41 | + return createUnauthorizedResponse() |
| 42 | + } |
| 43 | + |
| 44 | + const { chatId } = await params |
| 45 | + const body = await request.json() |
| 46 | + const { upToMessageId } = ForkChatSchema.parse(body) |
| 47 | + |
| 48 | + // Load parent chat and verify ownership. |
| 49 | + const [parent] = await db |
| 50 | + .select() |
| 51 | + .from(copilotChats) |
| 52 | + .where(eq(copilotChats.id, chatId)) |
| 53 | + .limit(1) |
| 54 | + |
| 55 | + if (!parent || parent.userId !== userId || parent.type !== 'mothership') { |
| 56 | + return createNotFoundResponse('Chat not found') |
| 57 | + } |
| 58 | + |
| 59 | + if (parent.workspaceId) { |
| 60 | + await assertActiveWorkspaceAccess(parent.workspaceId, userId) |
| 61 | + } |
| 62 | + |
| 63 | + // Find the fork point in the Sim-side messages array. |
| 64 | + const messages = Array.isArray(parent.messages) ? (parent.messages as PersistedMessage[]) : [] |
| 65 | + const forkIdx = messages.findIndex((m) => m.id === upToMessageId) |
| 66 | + if (forkIdx < 0) { |
| 67 | + return createBadRequestResponse('Message not found in chat') |
| 68 | + } |
| 69 | + const forkedMessages = messages.slice(0, forkIdx + 1) |
| 70 | + |
| 71 | + // Resources are stored as a jsonb array on the chat row — copy them directly. |
| 72 | + const parentResources = Array.isArray(parent.resources) |
| 73 | + ? (parent.resources as MothershipResource[]) |
| 74 | + : [] |
| 75 | + |
| 76 | + const newId = generateId() |
| 77 | + const baseTitle = (parent.title ?? 'New task').replace(/ \| Fork$/, '') |
| 78 | + const title = `${baseTitle} | Fork` |
| 79 | + const now = new Date() |
| 80 | + |
| 81 | + const [newChat] = await db |
| 82 | + .insert(copilotChats) |
| 83 | + .values({ |
| 84 | + id: newId, |
| 85 | + userId, |
| 86 | + workspaceId: parent.workspaceId, |
| 87 | + type: parent.type, |
| 88 | + title, |
| 89 | + model: parent.model, |
| 90 | + messages: forkedMessages, |
| 91 | + resources: parentResources, |
| 92 | + previewYaml: parent.previewYaml, |
| 93 | + planArtifact: parent.planArtifact, |
| 94 | + config: parent.config, |
| 95 | + conversationId: null, |
| 96 | + updatedAt: now, |
| 97 | + lastSeenAt: now, |
| 98 | + }) |
| 99 | + .returning({ id: copilotChats.id, workspaceId: copilotChats.workspaceId }) |
| 100 | + |
| 101 | + if (!newChat) { |
| 102 | + return createInternalServerErrorResponse('Failed to create forked chat') |
| 103 | + } |
| 104 | + |
| 105 | + // Clone copilot-service conversation state (messages, active_messages, memory files). |
| 106 | + // Best-effort: if the copilot service doesn't have a row for the source chat yet, skip. |
| 107 | + try { |
| 108 | + const copilotHeaders: Record<string, string> = { 'Content-Type': 'application/json' } |
| 109 | + if (env.COPILOT_API_KEY) { |
| 110 | + copilotHeaders['x-api-key'] = env.COPILOT_API_KEY |
| 111 | + } |
| 112 | + const copilotRes = await fetchGo(`${SIM_AGENT_API_URL}/api/chats/fork`, { |
| 113 | + method: 'POST', |
| 114 | + headers: copilotHeaders, |
| 115 | + body: JSON.stringify({ |
| 116 | + sourceChatId: chatId, |
| 117 | + newChatId: newId, |
| 118 | + upToMessageId, |
| 119 | + userId, |
| 120 | + }), |
| 121 | + spanName: 'sim → go /api/chats/fork', |
| 122 | + operation: 'fork_chat', |
| 123 | + }) |
| 124 | + if (!copilotRes.ok) { |
| 125 | + const text = await copilotRes.text().catch(() => '') |
| 126 | + logger.warn('Copilot fork returned non-OK', { status: copilotRes.status, body: text }) |
| 127 | + } |
| 128 | + } catch (err) { |
| 129 | + // The copilot service may not have a row for this chat if no messages |
| 130 | + // have been sent yet, or if it's unreachable. Log and continue. |
| 131 | + logger.warn('Failed to fork copilot-service conversation, skipping', { err }) |
| 132 | + } |
| 133 | + |
| 134 | + if (newChat.workspaceId) { |
| 135 | + taskPubSub?.publishStatusChanged({ |
| 136 | + workspaceId: newChat.workspaceId, |
| 137 | + chatId: newId, |
| 138 | + type: 'created', |
| 139 | + }) |
| 140 | + } |
| 141 | + |
| 142 | + captureServerEvent( |
| 143 | + userId, |
| 144 | + 'task_forked', |
| 145 | + { workspace_id: parent.workspaceId ?? '', source_chat_id: chatId }, |
| 146 | + { groups: { workspace: parent.workspaceId ?? '' } } |
| 147 | + ) |
| 148 | + |
| 149 | + return NextResponse.json({ success: true, id: newId }) |
| 150 | + } catch (error) { |
| 151 | + if (error instanceof z.ZodError) { |
| 152 | + return createBadRequestResponse('upToMessageId is required') |
| 153 | + } |
| 154 | + logger.error('Error forking chat:', error) |
| 155 | + return createInternalServerErrorResponse('Failed to fork chat') |
| 156 | + } |
| 157 | + } |
| 158 | +) |
0 commit comments