(params: {
chatId?: string
userId: string
workflowId?: string
workspaceId?: string
model: string
type?: 'mothership' | 'copilot'
})
| 224 | * Supports both workflow-scoped and workspace-scoped chats. |
| 225 | */ |
| 226 | export async function resolveOrCreateChat(params: { |
| 227 | chatId?: string |
| 228 | userId: string |
| 229 | workflowId?: string |
| 230 | workspaceId?: string |
| 231 | model: string |
| 232 | type?: 'mothership' | 'copilot' |
| 233 | }): Promise<ChatLoadResult> { |
| 234 | const { chatId, userId, workflowId, workspaceId, model, type } = params |
| 235 | |
| 236 | if (workspaceId) { |
| 237 | await assertActiveWorkspaceAccess(workspaceId, userId) |
| 238 | } |
| 239 | |
| 240 | if (chatId) { |
| 241 | const chat = await getAccessibleCopilotChatWithMessages(chatId, userId) |
| 242 | |
| 243 | if (chat) { |
| 244 | if (workflowId && chat.workflowId !== workflowId) { |
| 245 | logger.warn('Copilot chat workflow mismatch', { |
| 246 | chatId, |
| 247 | userId, |
| 248 | requestWorkflowId: workflowId, |
| 249 | chatWorkflowId: chat.workflowId, |
| 250 | }) |
| 251 | return { chatId, chat: null, conversationHistory: [], isNew: false } |
| 252 | } |
| 253 | |
| 254 | if (workspaceId && chat.workspaceId !== workspaceId) { |
| 255 | logger.warn('Copilot chat workspace mismatch', { |
| 256 | chatId, |
| 257 | userId, |
| 258 | requestWorkspaceId: workspaceId, |
| 259 | chatWorkspaceId: chat.workspaceId, |
| 260 | }) |
| 261 | return { chatId, chat: null, conversationHistory: [], isNew: false } |
| 262 | } |
| 263 | |
| 264 | if (chat.workflowId) { |
| 265 | const activeWorkflow = await getActiveWorkflowRecord(chat.workflowId) |
| 266 | if (!activeWorkflow) { |
| 267 | logger.warn('Copilot chat workflow no longer active', { |
| 268 | chatId, |
| 269 | userId, |
| 270 | workflowId: chat.workflowId, |
| 271 | }) |
| 272 | return { chatId, chat: null, conversationHistory: [], isNew: false } |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | return { |
| 278 | chatId, |
| 279 | chat: chat ?? null, |
| 280 | conversationHistory: chat && Array.isArray(chat.messages) ? chat.messages : [], |
| 281 | isNew: false, |
| 282 | } |
| 283 | } |
no test coverage detected