From 9e2389c39a191fc08acc9901644b1153df67f57a Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Thu, 3 Dec 2026 01:35:52 +0800 Subject: [PATCH 1/2] Make the admin reset reseed what it says `POST /api/admin/reset` accepted a `reseed` flag and always declined to act on it, because the seed script ran its own top-level IIFE with its own PrismaClient and could not be imported. Export `seed(prisma)` from the seed module and move the CLI bootstrap to `seed-cli.ts`, so importing the module no longer seeds anything by itself. The reset route now calls `seed(prisma)` with the client it already holds and reports `reseeded: true`. The seed runs after the reset transaction has committed: a failure there is reported and the reset stands. Co-Authored-By: Claude Code --- .../web/src/__tests__/admin-reset-api.test.ts | 59 +++++++++++++++++++ apps/web/src/app/api/admin/reset/route.ts | 20 ++++--- packages/outpost/db/src/seed-cli.ts | 20 +++++++ packages/outpost/db/src/seed.ts | 24 ++++---- packages/outpost/package.json | 8 ++- 5 files changed, 108 insertions(+), 23 deletions(-) create mode 100644 packages/outpost/db/src/seed-cli.ts diff --git a/apps/web/src/__tests__/admin-reset-api.test.ts b/apps/web/src/__tests__/admin-reset-api.test.ts index 6e065ab6..d3c6fe57 100644 --- a/apps/web/src/__tests__/admin-reset-api.test.ts +++ b/apps/web/src/__tests__/admin-reset-api.test.ts @@ -24,6 +24,11 @@ vi.mock('@copilotkit/outpost/db', () => ({ vi.mock('@copilotkit/outpost/shared', () => ({ verifyPassword: vi.fn() })); +const mockSeed = vi.fn(); +vi.mock('@copilotkit/outpost/db/seed', () => ({ + seed: (...a: unknown[]) => mockSeed(...a), +})); + import { POST } from '@/app/api/admin/reset/route'; import { authOptions } from '@/lib/auth'; @@ -69,4 +74,58 @@ describe('POST /api/admin/reset', () => { authOptions.callbacks!.jwt!({ token: { memberId: 'admin-1', sv: 3 } } as never), ).resolves.toMatchObject({ memberId: 'admin-1' }); }); + + it('seeds the database when reseed is requested', async () => { + mockSeed.mockResolvedValue(undefined); + + const res = await POST( + new Request('http://localhost:3000/api/admin/reset', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ confirmation: 'RESET', reseed: true }), + }), + ); + + expect(res.status).toBe(200); + expect(mockSeed).toHaveBeenCalledTimes(1); + // The seed runs on the client the route already holds, not a new one. + expect(mockSeed.mock.calls[0][0]).toEqual( + expect.objectContaining({ teamMember: expect.anything() }), + ); + await expect(res.json()).resolves.toEqual({ success: true, reseeded: true }); + }); + + it('does not seed when reseed is not requested', async () => { + const res = await POST( + new Request('http://localhost:3000/api/admin/reset', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ confirmation: 'RESET' }), + }), + ); + + expect(res.status).toBe(200); + expect(mockSeed).not.toHaveBeenCalled(); + await expect(res.json()).resolves.toEqual({ success: true, reseeded: false }); + }); + + it('reports a failed seed without discarding the reset', async () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + mockSeed.mockRejectedValue(new Error('seed failed')); + + const res = await POST( + new Request('http://localhost:3000/api/admin/reset', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ confirmation: 'RESET', reseed: true }), + }), + ); + + expect(res.status).toBe(200); + expect(errorSpy).toHaveBeenCalled(); + const body = await res.json(); + expect(body.reseeded).toBe(false); + expect(body.note).toContain('npx prisma db seed'); + errorSpy.mockRestore(); + }); }); diff --git a/apps/web/src/app/api/admin/reset/route.ts b/apps/web/src/app/api/admin/reset/route.ts index 4d3f4fa5..f6d7735d 100644 --- a/apps/web/src/app/api/admin/reset/route.ts +++ b/apps/web/src/app/api/admin/reset/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from 'next/server'; import { prisma } from '@copilotkit/outpost/db'; +import { seed } from '@copilotkit/outpost/db/seed'; import { requireAdmin } from '@/lib/require-admin'; export async function POST(request: Request) { @@ -59,19 +60,24 @@ export async function POST(request: Request) { }); }); - // Handle optional re-seed + // Handle optional re-seed. The seed runs after the reset transaction has + // committed: it writes its own rows, and a failure there must not roll + // back a reset the admin already asked for. let reseeded = false; + let reseedNote: string | undefined; if (reseed) { - // The seed script uses a top-level async IIFE with its own PrismaClient, - // so it cannot be cleanly imported. Manual re-seed is required. - reseeded = false; + try { + await seed(prisma); + reseeded = true; + } catch (error) { + console.error('[POST /api/admin/reset] Re-seed failed:', error); + reseedNote = 'The database was reset, but re-seeding failed. Run: npx prisma db seed'; + } } return NextResponse.json({ success: true, reseeded, - ...(!reseeded && reseed - ? { note: 'Manual re-seed required. Run: npx prisma db seed' } - : {}), + ...(reseedNote ? { note: reseedNote } : {}), }); } diff --git a/packages/outpost/db/src/seed-cli.ts b/packages/outpost/db/src/seed-cli.ts new file mode 100644 index 00000000..df480593 --- /dev/null +++ b/packages/outpost/db/src/seed-cli.ts @@ -0,0 +1,20 @@ +import { PrismaClient } from '@prisma/client'; +import { seed } from './seed.js'; + +/** + * CLI entry point: `pnpm db:seed` / `prisma db seed`. + * + * Importing `seed.ts` itself only defines the seed function, so this file + * owns the client and the process lifecycle. + */ +const prisma = new PrismaClient(); + +seed(prisma) + .then(async () => { + await prisma.$disconnect(); + }) + .catch(async (e) => { + console.error(e); + await prisma.$disconnect(); + process.exit(1); + }); diff --git a/packages/outpost/db/src/seed.ts b/packages/outpost/db/src/seed.ts index a49e93de..1c1bbea8 100644 --- a/packages/outpost/db/src/seed.ts +++ b/packages/outpost/db/src/seed.ts @@ -1,9 +1,15 @@ -import { PrismaClient } from '@prisma/client'; +import type { PrismaClient } from '@prisma/client'; import { hashPassword } from '@copilotkit/outpost/shared'; -const prisma = new PrismaClient(); - -async function main() { +/** + * Seed the database with the demo dataset. + * + * The client is a parameter so a caller can seed with the Prisma instance it + * already holds — `POST /api/admin/reset` passes its own — instead of this + * module creating a second connection. The CLI entry point lives in + * `seed-cli.ts` so importing this file never seeds anything by itself. + */ +export async function seed(prisma: PrismaClient) { console.log('Seeding database...'); // Hash the dev password once, reuse for all seed team members @@ -526,13 +532,3 @@ async function main() { console.log(` - ${slaData.length} SLA configs`); console.log(` - 3 agents`); } - -main() - .then(async () => { - await prisma.$disconnect(); - }) - .catch(async (e) => { - console.error(e); - await prisma.$disconnect(); - process.exit(1); - }); diff --git a/packages/outpost/package.json b/packages/outpost/package.json index be74ac3a..a6260ae4 100644 --- a/packages/outpost/package.json +++ b/packages/outpost/package.json @@ -8,6 +8,10 @@ "types": "./db/dist/index.d.ts", "import": "./db/dist/index.js" }, + "./db/seed": { + "types": "./db/dist/seed.d.ts", + "import": "./db/dist/seed.js" + }, "./ai": { "types": "./ai/dist/index.d.ts", "import": "./ai/dist/index.js" @@ -40,7 +44,7 @@ "test": "vitest run", "db:generate": "prisma generate --schema=db/prisma/schema.prisma", "db:push": "prisma db push --schema=db/prisma/schema.prisma", - "db:seed": "tsx db/src/seed.ts", + "db:seed": "tsx db/src/seed-cli.ts", "db:studio": "prisma studio --schema=db/prisma/schema.prisma" }, "dependencies": { @@ -73,6 +77,6 @@ }, "prisma": { "schema": "db/prisma/schema.prisma", - "seed": "tsx db/src/seed.ts" + "seed": "tsx db/src/seed-cli.ts" } } From 3a8f0eb391bd0b0a9026735b485870b7139f4d52 Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Thu, 3 Dec 2026 01:56:20 +0800 Subject: [PATCH 2/2] Format the seed file the CI format check covers The seed script was not Prettier-formatted before this branch, and the CI format check runs on every file a PR touches, so it would fail here. Formatting only; no behaviour change. Co-Authored-By: Claude Code --- packages/outpost/db/src/seed.ts | 139 +++++++++++++++++++++++++------- 1 file changed, 108 insertions(+), 31 deletions(-) diff --git a/packages/outpost/db/src/seed.ts b/packages/outpost/db/src/seed.ts index 1c1bbea8..c3ab37e9 100644 --- a/packages/outpost/db/src/seed.ts +++ b/packages/outpost/db/src/seed.ts @@ -163,7 +163,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-A1B2', title: 'CopilotKit agent not responding after deploy', - description: 'After deploying to production, our CopilotKit agent stops responding to user messages. Works fine locally.', + description: + 'After deploying to production, our CopilotKit agent stops responding to user messages. Works fine locally.', status: 'OPEN' as const, priority: 'CRITICAL' as const, type: 'BUG' as const, @@ -176,7 +177,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-C3D4', title: 'How to configure multi-agent setup?', - description: 'Looking for guidance on setting up multiple agents with CopilotKit. The docs mention it but no examples.', + description: + 'Looking for guidance on setting up multiple agents with CopilotKit. The docs mention it but no examples.', status: 'IN_PROGRESS' as const, priority: 'MEDIUM' as const, type: 'QUESTION' as const, @@ -189,7 +191,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-E5F6', title: 'Feature request: Streaming support for tool calls', - description: 'It would be great to have streaming support when tools are executing, so users can see progress.', + description: + 'It would be great to have streaming support when tools are executing, so users can see progress.', status: 'OPEN' as const, priority: 'LOW' as const, type: 'FEATURE_REQUEST' as const, @@ -201,7 +204,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-G7H8', title: 'Integration failing with Next.js 15', - description: 'Getting hydration errors when using CopilotKit with Next.js 15 app router. Stack trace attached.', + description: + 'Getting hydration errors when using CopilotKit with Next.js 15 app router. Stack trace attached.', status: 'WAITING_ON_TEAM' as const, priority: 'HIGH' as const, type: 'INTEGRATION_HELP' as const, @@ -214,7 +218,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-J9K1', title: 'Billing inquiry - upgrade from Pro to Enterprise', - description: 'We need to upgrade our plan. Currently on Pro but need enterprise features for SOC2 compliance.', + description: + 'We need to upgrade our plan. Currently on Pro but need enterprise features for SOC2 compliance.', status: 'WAITING_ON_CUSTOMER' as const, priority: 'MEDIUM' as const, type: 'ACCOUNT_ISSUE' as const, @@ -226,7 +231,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-L2M3', title: 'useCopilotAction hook not triggering', - description: 'The useCopilotAction hook is registered but never gets called. Using React 18 with Vite.', + description: + 'The useCopilotAction hook is registered but never gets called. Using React 18 with Vite.', status: 'OPEN' as const, priority: 'HIGH' as const, type: 'BUG' as const, @@ -238,7 +244,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-N4P5', title: 'Custom UI component rendering question', - description: 'How do we render custom React components in the CopilotKit chat? Docs are unclear on this.', + description: + 'How do we render custom React components in the CopilotKit chat? Docs are unclear on this.', status: 'RESOLVED' as const, priority: 'LOW' as const, type: 'QUESTION' as const, @@ -250,7 +257,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-Q6R7', title: 'Memory leak in long-running agent sessions', - description: 'After ~2 hours of continuous agent interaction, memory usage grows unbounded. Need investigation.', + description: + 'After ~2 hours of continuous agent interaction, memory usage grows unbounded. Need investigation.', status: 'IN_PROGRESS' as const, priority: 'CRITICAL' as const, type: 'BUG' as const, @@ -262,7 +270,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-S8T9', title: 'Request for Python SDK', - description: 'Our backend is Python-based. Would love a Python SDK for CopilotKit server-side integration.', + description: + 'Our backend is Python-based. Would love a Python SDK for CopilotKit server-side integration.', status: 'OPEN' as const, priority: 'MEDIUM' as const, type: 'FEATURE_REQUEST' as const, @@ -274,7 +283,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-U1V2', title: 'CORS error when connecting to self-hosted runtime', - description: 'Getting CORS errors when the frontend tries to connect to our self-hosted CopilotKit runtime.', + description: + 'Getting CORS errors when the frontend tries to connect to our self-hosted CopilotKit runtime.', status: 'OPEN' as const, priority: 'HIGH' as const, type: 'INTEGRATION_HELP' as const, @@ -286,7 +296,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-W3X4', title: 'Webhook delivery failures', - description: 'Our webhook endpoint is receiving duplicate events and some events are missing.', + description: + 'Our webhook endpoint is receiving duplicate events and some events are missing.', status: 'IN_PROGRESS' as const, priority: 'HIGH' as const, type: 'BUG' as const, @@ -298,7 +309,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-Y5Z6', title: 'Agent context not persisting across sessions', - description: 'When a user closes and reopens the chat, all previous context is lost. Need persistent memory.', + description: + 'When a user closes and reopens the chat, all previous context is lost. Need persistent memory.', status: 'OPEN' as const, priority: 'MEDIUM' as const, type: 'FEATURE_REQUEST' as const, @@ -310,7 +322,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-A7B8', title: 'TypeScript type errors after v1.5 upgrade', - description: 'After upgrading to CopilotKit 1.5, getting type mismatches in useCopilotChat.', + description: + 'After upgrading to CopilotKit 1.5, getting type mismatches in useCopilotChat.', status: 'RESOLVED' as const, priority: 'MEDIUM' as const, type: 'BUG' as const, @@ -323,7 +336,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-C9D1', title: 'Rate limiting configuration for production', - description: 'Need guidance on configuring rate limits for our production deployment with ~10k daily users.', + description: + 'Need guidance on configuring rate limits for our production deployment with ~10k daily users.', status: 'WAITING_ON_CUSTOMER' as const, priority: 'MEDIUM' as const, type: 'QUESTION' as const, @@ -347,7 +361,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-G4H5', title: 'Documentation missing for ag-ui protocol', - description: 'The ag-ui protocol docs seem incomplete. Missing sections on error handling and reconnection.', + description: + 'The ag-ui protocol docs seem incomplete. Missing sections on error handling and reconnection.', status: 'OPEN' as const, priority: 'MEDIUM' as const, type: 'QUESTION' as const, @@ -359,7 +374,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-J6K7', title: 'Agent tool execution timeout', - description: 'Tool calls are timing out after 30s. Need to increase timeout or add retry logic.', + description: + 'Tool calls are timing out after 30s. Need to increase timeout or add retry logic.', status: 'CLOSED' as const, priority: 'LOW' as const, type: 'BUG' as const, @@ -372,7 +388,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-L8M9', title: 'Request for GraphQL API support', - description: 'Would be great to have first-class GraphQL support alongside REST for the runtime API.', + description: + 'Would be great to have first-class GraphQL support alongside REST for the runtime API.', status: 'OPEN' as const, priority: 'LOW' as const, type: 'FEATURE_REQUEST' as const, @@ -384,7 +401,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-N1P2', title: 'Multi-tenant setup best practices', - description: 'Building a SaaS with CopilotKit. Need guidance on isolating agent contexts per tenant.', + description: + 'Building a SaaS with CopilotKit. Need guidance on isolating agent contexts per tenant.', status: 'IN_PROGRESS' as const, priority: 'HIGH' as const, type: 'INTEGRATION_HELP' as const, @@ -396,7 +414,8 @@ export async function seed(prisma: PrismaClient) { { displayId: 'TKT-Q3R4', title: 'Chat widget styling broken in dark mode', - description: 'The CopilotKit chat widget has contrast issues in dark mode. Text is nearly invisible.', + description: + 'The CopilotKit chat widget has contrast issues in dark mode. Text is nearly invisible.', status: 'OPEN' as const, priority: 'MEDIUM' as const, type: 'BUG' as const, @@ -415,16 +434,72 @@ export async function seed(prisma: PrismaClient) { // ─── Messages ─────────────────────────────────────────────────────── const messageData = [ - { ticketId: tickets[0].id, author: users[0].name, content: 'This started happening right after we deployed v2.1.0 to production.', type: 'USER' as const }, - { ticketId: tickets[0].id, author: 'Outpost AI', content: 'I found a similar issue reported in #431. The fix involves updating the runtime configuration to include the new API endpoint. Let me check if this applies to your case.', type: 'BOT' as const, isAiGenerated: true }, - { ticketId: tickets[0].id, author: teamMembers[2].name, content: 'Looking into this now. Can you share your runtime config?', type: 'USER' as const }, - { ticketId: tickets[1].id, author: users[1].name, content: 'I have two agents: one for code generation and one for documentation. How do I route between them?', type: 'USER' as const }, - { ticketId: tickets[1].id, author: teamMembers[0].name, content: 'Check out the multi-agent guide at docs.copilotkit.ai/guides/multi-agent. You can use the agentName parameter.', type: 'USER' as const }, - { ticketId: tickets[3].id, author: users[2].name, content: 'Here is the full stack trace from the hydration error.', type: 'USER' as const }, - { ticketId: tickets[3].id, author: 'System', content: 'Ticket escalated to engineering team.', type: 'SYSTEM' as const }, - { ticketId: tickets[7].id, author: users[3].name, content: 'Memory grows from 200MB to 2GB over 2 hours. Chrome DevTools heap snapshot attached.', type: 'USER' as const }, - { ticketId: tickets[7].id, author: teamMembers[2].name, content: 'This looks like it could be related to event listener cleanup. Investigating.', type: 'USER' as const }, - { ticketId: tickets[10].id, author: users[0].name, content: 'We are seeing about 15% of webhook events being duplicated.', type: 'USER' as const }, + { + ticketId: tickets[0].id, + author: users[0].name, + content: 'This started happening right after we deployed v2.1.0 to production.', + type: 'USER' as const, + }, + { + ticketId: tickets[0].id, + author: 'Outpost AI', + content: + 'I found a similar issue reported in #431. The fix involves updating the runtime configuration to include the new API endpoint. Let me check if this applies to your case.', + type: 'BOT' as const, + isAiGenerated: true, + }, + { + ticketId: tickets[0].id, + author: teamMembers[2].name, + content: 'Looking into this now. Can you share your runtime config?', + type: 'USER' as const, + }, + { + ticketId: tickets[1].id, + author: users[1].name, + content: + 'I have two agents: one for code generation and one for documentation. How do I route between them?', + type: 'USER' as const, + }, + { + ticketId: tickets[1].id, + author: teamMembers[0].name, + content: + 'Check out the multi-agent guide at docs.copilotkit.ai/guides/multi-agent. You can use the agentName parameter.', + type: 'USER' as const, + }, + { + ticketId: tickets[3].id, + author: users[2].name, + content: 'Here is the full stack trace from the hydration error.', + type: 'USER' as const, + }, + { + ticketId: tickets[3].id, + author: 'System', + content: 'Ticket escalated to engineering team.', + type: 'SYSTEM' as const, + }, + { + ticketId: tickets[7].id, + author: users[3].name, + content: + 'Memory grows from 200MB to 2GB over 2 hours. Chrome DevTools heap snapshot attached.', + type: 'USER' as const, + }, + { + ticketId: tickets[7].id, + author: teamMembers[2].name, + content: + 'This looks like it could be related to event listener cleanup. Investigating.', + type: 'USER' as const, + }, + { + ticketId: tickets[10].id, + author: users[0].name, + content: 'We are seeing about 15% of webhook events being duplicated.', + type: 'USER' as const, + }, ]; for (const data of messageData) { @@ -448,7 +523,8 @@ export async function seed(prisma: PrismaClient) { prisma.docArticle.create({ data: { title: 'Quick Start with CopilotKit', - content: 'This guide walks you through setting up CopilotKit in your Next.js application...', + content: + 'This guide walks you through setting up CopilotKit in your Next.js application...', status: 'PUBLISHED', categoryId: categories[0].id, sourceUrl: 'https://docs.copilotkit.ai/quickstart', @@ -466,7 +542,8 @@ export async function seed(prisma: PrismaClient) { prisma.docArticle.create({ data: { title: 'Multi-Agent Setup Guide', - content: 'Learn how to configure and orchestrate multiple agents with CopilotKit...', + content: + 'Learn how to configure and orchestrate multiple agents with CopilotKit...', status: 'DRAFT', categoryId: categories[2].id, },