-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Feat/persist resources (WIP) #3553
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
TheodoreSpeaks
merged 9 commits into
feat/mothership-copilot
from
feat/persist-resources
Mar 13, 2026
+1,658
−678
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c6c6310
Make resources persist to backend
0681c46
Use colored squares for workflows
544af06
Add click and drag functionality to resource
a18b01a
Fix expanding panel logic
a0e7a98
Reduce duplication, reading resource also opens up resource panel
9ff87c1
Move resource dropdown to own file
a66b306
Merge branch 'feat/mothership-copilot' into feat/persist-resources
419e1a1
Handle renamed resources
847c899
Clicking already open tab should just switch to tab
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| import { db } from '@sim/db' | ||
| import { copilotChats } from '@sim/db/schema' | ||
| import { createLogger } from '@sim/logger' | ||
| import { and, eq, sql } from 'drizzle-orm' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { z } from 'zod' | ||
| import type { ChatResource, ResourceType } from '@/lib/copilot/resources' | ||
| import { | ||
| authenticateCopilotRequestSessionOnly, | ||
| createBadRequestResponse, | ||
| createInternalServerErrorResponse, | ||
| createNotFoundResponse, | ||
| createUnauthorizedResponse, | ||
| } from '@/lib/copilot/request-helpers' | ||
|
|
||
| const logger = createLogger('CopilotChatResourcesAPI') | ||
|
|
||
| const VALID_RESOURCE_TYPES = new Set<ResourceType>(['table', 'file', 'workflow', 'knowledgebase']) | ||
| const GENERIC_TITLES = new Set(['Table', 'File', 'Workflow', 'Knowledge Base']) | ||
|
|
||
| const AddResourceSchema = z.object({ | ||
| chatId: z.string(), | ||
| resource: z.object({ | ||
| type: z.enum(['table', 'file', 'workflow', 'knowledgebase']), | ||
| id: z.string(), | ||
| title: z.string(), | ||
| }), | ||
| }) | ||
|
|
||
| const RemoveResourceSchema = z.object({ | ||
| chatId: z.string(), | ||
| resourceType: z.enum(['table', 'file', 'workflow', 'knowledgebase']), | ||
| resourceId: z.string(), | ||
| }) | ||
|
|
||
| const ReorderResourcesSchema = z.object({ | ||
| chatId: z.string(), | ||
| resources: z.array( | ||
| z.object({ | ||
| type: z.enum(['table', 'file', 'workflow', 'knowledgebase']), | ||
| id: z.string(), | ||
| title: z.string(), | ||
| }) | ||
| ), | ||
| }) | ||
|
|
||
| export async function POST(req: NextRequest) { | ||
| try { | ||
| const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly() | ||
| if (!isAuthenticated || !userId) { | ||
| return createUnauthorizedResponse() | ||
| } | ||
|
|
||
| const body = await req.json() | ||
| const { chatId, resource } = AddResourceSchema.parse(body) | ||
|
|
||
| if (!VALID_RESOURCE_TYPES.has(resource.type)) { | ||
| return createBadRequestResponse(`Invalid resource type: ${resource.type}`) | ||
| } | ||
|
|
||
| const [chat] = await db | ||
| .select({ resources: copilotChats.resources }) | ||
| .from(copilotChats) | ||
| .where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, userId))) | ||
| .limit(1) | ||
|
|
||
| if (!chat) { | ||
| return createNotFoundResponse('Chat not found or unauthorized') | ||
| } | ||
|
|
||
| const existing = Array.isArray(chat.resources) ? (chat.resources as ChatResource[]) : [] | ||
| const key = `${resource.type}:${resource.id}` | ||
| const prev = existing.find((r) => `${r.type}:${r.id}` === key) | ||
|
|
||
| let merged: ChatResource[] | ||
| if (prev) { | ||
| if (GENERIC_TITLES.has(prev.title) && !GENERIC_TITLES.has(resource.title)) { | ||
| merged = existing.map((r) => (`${r.type}:${r.id}` === key ? { ...r, title: resource.title } : r)) | ||
| } else { | ||
| merged = existing | ||
| } | ||
| } else { | ||
| merged = [...existing, resource] | ||
| } | ||
|
|
||
| await db | ||
| .update(copilotChats) | ||
| .set({ resources: sql`${JSON.stringify(merged)}::jsonb`, updatedAt: new Date() }) | ||
| .where(eq(copilotChats.id, chatId)) | ||
|
|
||
| logger.info('Added resource to chat', { chatId, resource }) | ||
|
|
||
| return NextResponse.json({ success: true, resources: merged }) | ||
| } catch (error) { | ||
| if (error instanceof z.ZodError) { | ||
| return createBadRequestResponse(error.errors.map((e) => e.message).join(', ')) | ||
| } | ||
| logger.error('Error adding chat resource:', error) | ||
| return createInternalServerErrorResponse('Failed to add resource') | ||
| } | ||
| } | ||
|
|
||
| export async function PATCH(req: NextRequest) { | ||
| try { | ||
| const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly() | ||
| if (!isAuthenticated || !userId) { | ||
| return createUnauthorizedResponse() | ||
| } | ||
|
|
||
| const body = await req.json() | ||
| const { chatId, resources: newOrder } = ReorderResourcesSchema.parse(body) | ||
|
|
||
| const [chat] = await db | ||
| .select({ resources: copilotChats.resources }) | ||
| .from(copilotChats) | ||
| .where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, userId))) | ||
| .limit(1) | ||
|
|
||
| if (!chat) { | ||
| return createNotFoundResponse('Chat not found or unauthorized') | ||
| } | ||
|
|
||
| const existing = Array.isArray(chat.resources) ? (chat.resources as ChatResource[]) : [] | ||
| const existingKeys = new Set(existing.map((r) => `${r.type}:${r.id}`)) | ||
| const newKeys = new Set(newOrder.map((r) => `${r.type}:${r.id}`)) | ||
|
|
||
| if (existingKeys.size !== newKeys.size || ![...existingKeys].every((k) => newKeys.has(k))) { | ||
| return createBadRequestResponse('Reordered resources must match existing resources') | ||
| } | ||
|
|
||
| await db | ||
| .update(copilotChats) | ||
| .set({ resources: sql`${JSON.stringify(newOrder)}::jsonb`, updatedAt: new Date() }) | ||
| .where(eq(copilotChats.id, chatId)) | ||
|
|
||
| logger.info('Reordered resources for chat', { chatId, count: newOrder.length }) | ||
|
|
||
| return NextResponse.json({ success: true, resources: newOrder }) | ||
| } catch (error) { | ||
| if (error instanceof z.ZodError) { | ||
| return createBadRequestResponse(error.errors.map((e) => e.message).join(', ')) | ||
| } | ||
| logger.error('Error reordering chat resources:', error) | ||
| return createInternalServerErrorResponse('Failed to reorder resources') | ||
| } | ||
| } | ||
|
|
||
| export async function DELETE(req: NextRequest) { | ||
| try { | ||
| const { userId, isAuthenticated } = await authenticateCopilotRequestSessionOnly() | ||
| if (!isAuthenticated || !userId) { | ||
| return createUnauthorizedResponse() | ||
| } | ||
|
|
||
| const body = await req.json() | ||
| const { chatId, resourceType, resourceId } = RemoveResourceSchema.parse(body) | ||
|
|
||
| const [chat] = await db | ||
| .select({ resources: copilotChats.resources }) | ||
| .from(copilotChats) | ||
| .where(and(eq(copilotChats.id, chatId), eq(copilotChats.userId, userId))) | ||
| .limit(1) | ||
|
|
||
| if (!chat) { | ||
| return createNotFoundResponse('Chat not found or unauthorized') | ||
| } | ||
|
|
||
| const existing = Array.isArray(chat.resources) ? (chat.resources as ChatResource[]) : [] | ||
| const key = `${resourceType}:${resourceId}` | ||
| const merged = existing.filter((r) => `${r.type}:${r.id}` !== key) | ||
|
|
||
| await db | ||
| .update(copilotChats) | ||
| .set({ resources: sql`${JSON.stringify(merged)}::jsonb`, updatedAt: new Date() }) | ||
| .where(eq(copilotChats.id, chatId)) | ||
|
|
||
| logger.info('Removed resource from chat', { chatId, resourceType, resourceId }) | ||
|
|
||
| return NextResponse.json({ success: true, resources: merged }) | ||
| } catch (error) { | ||
| if (error instanceof z.ZodError) { | ||
| return createBadRequestResponse(error.errors.map((e) => e.message).join(', ')) | ||
| } | ||
| logger.error('Error removing chat resource:', error) | ||
| return createInternalServerErrorResponse('Failed to remove resource') | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.