Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M5-006): conversation module: service + trpc into core

ralph7ce7a6f22a6b
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 00d37c920..b0c282393 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -215,6 +215,22 @@ export {
listRefreshableCohortIds,
updateCohortMembership,
} from './modules/cohort/cohort.service';
+// Moved from @openpanel/db's services/conversation.service.ts (M5-006) —
+// packages/trpc's conversation router, apps/api's live chat route and this
+// package's own assistant.routes.ts stub call these directly. packages/db
+// keeps a re-export shim (unlike cohort, M5-003): both non-trpc call sites
+// still reach it through `@openpanel/db`'s barrel.
+export type {
+ IServiceChatMessage,
+ IServiceConversation,
+ IServiceConversationWithMessages,
+} from './modules/conversation/conversation.service';
+export {
+ deleteConversation,
+ getConversationById,
+ listConversations,
+ upsertConversationTitle,
+} from './modules/conversation/conversation.service';
// Dissolved from @openpanel/db's src/gsc.ts + services/gsc.service.ts
// (M5-002) — apps/worker's gsc job file, apps/api's gsc OAuth callback
// controller and packages/trpc's gsc router call these directly, the same
diff --git a/packages/core/src/modules/conversation/conversation.rpc.test.ts b/packages/core/src/modules/conversation/conversation.rpc.test.ts
new file mode 100644
index 000000000..c8cb5e777
--- /dev/null
+++ b/packages/core/src/modules/conversation/conversation.rpc.test.ts
@@ -0,0 +1,59 @@
+// Only the "is anyone logged in" boundary is exercised here — no database.
+// The access-check + ownership logic ride on @openpanel/db (lazy-loaded, see
+// conversation.service.ts's header); wiring this router end-to-end against a
+// real Postgres is P6's (protectedProcedure) job, not this one's — see
+// conversation.rpc.ts's header.
+
+import { expect, test } from 'bun:test';
+import { stubHttpCtx } from '../../../test/rpc-fixtures';
+import { makeTrpcContext } from '../../rpc/base';
+import type { CookieOptions } from '../../shared/cookie';
+import { conversationRouter } from './conversation.rpc';
+
+const COOKIE_OPTIONS: CookieOptions = {
+ domain: '.openpanel.dev',
+ secure: true,
+ sameSite: 'lax',
+ httpOnly: true,
+ path: '/',
+};
+
+// EMPTY_SESSION's shape (packages/db/src/services/auth-session.service.ts) —
+// `TrpcContext.session` is never literally `null`, only its `userId` is.
+const EMPTY_SESSION = { session: null, user: null, userId: null };
+
+async function anonCaller() {
+ const { ctx } = stubHttpCtx({}, EMPTY_SESSION);
+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {
+ cookieOptions: COOKIE_OPTIONS,
+ });
+ return conversationRouter.createCaller(trpcCtx);
+}
+
+test('list rejects an unauthenticated caller before touching a project', async () => {
+ const caller = await anonCaller();
+ await expect(caller.list({ projectId: 'proj_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('get rejects an unauthenticated caller before reading a conversation', async () => {
+ const caller = await anonCaller();
+ await expect(caller.get({ id: 'conv_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
+
+test('rename rejects an unauthenticated caller before touching a conversation', async () => {
+ const caller = await anonCaller();
+ await expect(
+ caller.rename({ id: 'conv_1', title: 'New title', projectId: 'proj_1' })
+ ).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+});
+
+test('delete rejects an unauthenticated caller before deleting a conversation', async () => {
+ const caller = await anonCaller();
+ await expect(caller.delete({ id: 'conv_1' })).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+});
diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.ts
new file mode 100644
index 000000000..3aca98310
--- /dev/null
+++ b/packages/core/src/modules/conversation/conversation.rpc.ts
@@ -0,0 +1,166 @@
+// Ported from packages/trpc/src/routers/conversation.ts (M5-006).
+//
+// V1's `protectedProcedure` — the logger/session-scope/rate-limit middleware
+// stack — lands in core with auth (rpc/base.ts: "those need the resolved
+// Session shape and the access rules, so they land with auth (P6)"). Until
+// then this router does its own minimal "is anyone logged in" check inline,
+// exactly like V1's `enforceUserIsAuthed`. V1 keeps serving the live route
+// through packages/trpc's own `protectedProcedure` (full stack included) and
+// delegates its handler bodies to core's conversation functions
+// (DELEGATE PATTERN) — this module has no queue/ClickHouse compute of its
+// own, so there is no `ctx.services.conversation`, same as `assistant`.
+//
+// The per-project access ladder itself IS shared: `./src/access.ts` binds
+// core's shared/access.ts ladder to @openpanel/db's real lookups, the same
+// way packages/trpc/src/access.ts does for V1.
+
+import { z } from 'zod';
+import { createTRPCRouter, procedure } from '../../rpc/base';
+import { TRPCAccessError, TRPCNotFoundError } from '../../rpc/errors';
+import {
+ deleteConversation,
+ getConversationById,
+ listConversations,
+ upsertConversationTitle,
+} from './conversation.service';
+
+const LIST_LIMIT_MIN = 1;
+const LIST_LIMIT_MAX = 200;
+const LIST_LIMIT_DEFAULT = 50;
+const TITLE_MIN_LENGTH = 1;
+const TITLE_MAX_LENGTH = 80;
+
+function loadAccessChecks() {
+ return import('./src/access');
+}
+
+function loadOrganizationService() {
+ return import('@openpanel/db/src/services/organization.service');
+}
+
+function requireLogin(userId: string | null | undefined): string {
+ if (!userId) {
+ throw new TRPCAccessError('Not authenticated');
+ }
+ return userId;
+}
+
+/**
+ * Conversation management — listing, fetching, renaming, deleting.
+ * Conversation creation is implicit (lazy) on the first message via the
+ * /ai/agents/* route, so there's no `create` here.
+ *
+ * All procedures enforce ownership via `userId === session.userId` so a
+ * user can never read or mutate another user's conversations.
+ */
+export const conversationRouter = createTRPCRouter({
+ list: procedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ limit: z
+ .number()
+ .min(LIST_LIMIT_MIN)
+ .max(LIST_LIMIT_MAX)
+ .default(LIST_LIMIT_DEFAULT),
+ })
+ )
+ .query(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({
+ userId,
+ projectId: input.projectId,
+ level: 'read',
+ });
+
+ return listConversations({
+ projectId: input.projectId,
+ userId,
+ limit: input.limit,
+ });
+ }),
+
+ get: procedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const conv = await getConversationById(input.id, { withMessages: true });
+ if (!conv || conv.userId !== userId) {
+ throw new TRPCNotFoundError('Conversation not found');
+ }
+ return conv;
+ }),
+
+ rename: procedure
+ // A conversation belongs to the caller, not to the project - titling your
+ // own chat is not a project mutation. Ownership is enforced below.
+ .meta({ readOnlyMutation: true })
+ .input(
+ z.object({
+ id: z.string(),
+ title: z.string().min(TITLE_MIN_LENGTH).max(TITLE_MAX_LENGTH),
+ /**
+ * Required so we can create the row if the titler finishes
+ * before the agent's first persistence save. When the row
+ * already exists this is ignored — the ownership check
+ * below still applies. `organizationId` is derived from the
+ * project, not trusted from the client.
+ */
+ projectId: z.string(),
+ })
+ )
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+
+ // If the conversation already exists, enforce ownership. If it
+ // doesn't, verify the caller has access to the project being
+ // created under before letting the upsert create a fresh row.
+ const conv = await getConversationById(input.id);
+ if (conv) {
+ if (conv.userId !== userId) {
+ throw new TRPCNotFoundError('Conversation not found');
+ }
+ } else {
+ const { requireProjectAccess } = await loadAccessChecks();
+ await requireProjectAccess({
+ userId,
+ projectId: input.projectId,
+ level: 'read',
+ });
+ }
+
+ // Derive organizationId from the project — we never trust a
+ // client-supplied value here, even if the caller has access to
+ // the project (they'd still be able to tag the conversation with
+ // an unrelated org id).
+ const { getOrganizationByProjectIdCached } =
+ await loadOrganizationService();
+ const organization = await getOrganizationByProjectIdCached(
+ input.projectId
+ );
+ if (!organization) {
+ throw new TRPCNotFoundError('Project not found');
+ }
+
+ return upsertConversationTitle({
+ id: input.id,
+ title: input.title,
+ projectId: input.projectId,
+ organizationId: organization.id,
+ userId,
+ });
+ }),
+
+ delete: procedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ const userId = requireLogin(ctx.session.userId);
+ const conv = await getConversationById(input.id);
+ if (!conv || conv.userId !== userId) {
+ throw new TRPCNotFoundError('Conversation not found');
+ }
+ await deleteConversation(input.id);
+ return { success: true };
+ }),
+});
diff --git a/packages/core/src/modules/conversation/conversation.service.test.ts b/packages/core/src/modules/conversation/conversation.service.test.ts
new file mode 100644
index 000000000..21c25dc8d
--- /dev/null
+++ b/packages/core/src/modules/conversation/conversation.service.test.ts
@@ -0,0 +1,231 @@
+// conversation.service.ts's db access is lazy (`await import(...)` inside
+// each function — see the file's header), which is exactly what makes
+// `mock.module` work here with no import-time side effects to race: every
+// mock below is registered before the subject's first call, not before its
+// (side-effect-free) import.
+
+import { beforeAll, beforeEach, expect, mock, test } from 'bun:test';
+
+interface FakeConversation {
+ id: string;
+ title: string | null;
+ projectId: string;
+ organizationId: string;
+ userId: string;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+interface FakeMessage {
+ id: string;
+ conversationId: string;
+ role: string;
+ parts: unknown;
+ createdAt: Date;
+}
+
+const conversationStore = new Map<string, FakeConversation>();
+const messagesByConversation = new Map<string, FakeMessage[]>();
+
+function makeConversation(
+ overrides: Partial<FakeConversation> & { id: string }
+): FakeConversation {
+ const epoch = new Date('2026-09-03T00:00:00.000Z');
+ return {
+ title: null,
+ projectId: 'proj_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ createdAt: epoch,
+ updatedAt: epoch,
+ ...overrides,
+ };
+}
+
+const conversation = {
+ findUnique: mock(
+ async ({
+ where: { id },
+ include,
+ }: {
+ where: { id: string };
+ include?: { messages?: unknown };
+ }) => {
+ const conv = conversationStore.get(id);
+ if (!conv) {
+ return null;
+ }
+ if (include?.messages) {
+ return { ...conv, messages: messagesByConversation.get(id) ?? [] };
+ }
+ return conv;
+ }
+ ),
+ findMany: mock(
+ async ({
+ where,
+ take,
+ }: {
+ where: { projectId: string; userId: string };
+ take?: number;
+ }) => {
+ const rows = [...conversationStore.values()]
+ .filter(
+ (c) => c.projectId === where.projectId && c.userId === where.userId
+ )
+ .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
+ return take ? rows.slice(0, take) : rows;
+ }
+ ),
+ upsert: mock(
+ async ({
+ where: { id },
+ create,
+ update,
+ }: {
+ where: { id: string };
+ create: FakeConversation;
+ update: { title: string };
+ }) => {
+ const existing = conversationStore.get(id);
+ const next = existing
+ ? { ...existing, ...update, updatedAt: new Date() }
+ : makeConversation(create);
+ conversationStore.set(id, next);
+ return next;
+ }
+ ),
+ delete: mock(async ({ where: { id } }: { where: { id: string } }) => {
+ conversationStore.delete(id);
+ messagesByConversation.delete(id);
+ }),
+};
+
+mock.module('@openpanel/db/src/prisma-client', () => ({
+ db: { conversation },
+}));
+
+let subject: typeof import('./conversation.service');
+beforeAll(async () => {
+ subject = await import('./conversation.service');
+});
+
+beforeEach(() => {
+ conversationStore.clear();
+ messagesByConversation.clear();
+});
+
+test('getConversationById returns null for a missing conversation', async () => {
+ expect(await subject.getConversationById('missing')).toBeNull();
+});
+
+test('getConversationById returns the row without messages by default', async () => {
+ conversationStore.set('conv_1', makeConversation({ id: 'conv_1' }));
+ const result = await subject.getConversationById('conv_1');
+ expect(result).not.toBeNull();
+ expect(result).not.toHaveProperty('messages');
+});
+
+test('getConversationById includes ordered messages when asked', async () => {
+ conversationStore.set('conv_1', makeConversation({ id: 'conv_1' }));
+ messagesByConversation.set('conv_1', [
+ {
+ id: 'm1',
+ conversationId: 'conv_1',
+ role: 'user',
+ parts: {},
+ createdAt: new Date('2026-09-01T00:00:00.000Z'),
+ },
+ ]);
+ const result = await subject.getConversationById('conv_1', {
+ withMessages: true,
+ });
+ expect(result).toMatchObject({ id: 'conv_1', messages: [{ id: 'm1' }] });
+});
+
+test('listConversations scopes to project and user, newest first', async () => {
+ conversationStore.set(
+ 'conv_old',
+ makeConversation({
+ id: 'conv_old',
+ updatedAt: new Date('2026-09-01T00:00:00.000Z'),
+ })
+ );
+ conversationStore.set(
+ 'conv_new',
+ makeConversation({
+ id: 'conv_new',
+ updatedAt: new Date('2026-09-02T00:00:00.000Z'),
+ })
+ );
+ conversationStore.set(
+ 'conv_other_user',
+ makeConversation({ id: 'conv_other_user', userId: 'user_2' })
+ );
+
+ const result = await subject.listConversations({
+ projectId: 'proj_1',
+ userId: 'user_1',
+ });
+ expect(result.map((c) => c.id)).toEqual(['conv_new', 'conv_old']);
+});
+
+test('listConversations defaults to a limit of 50', async () => {
+ const CONVERSATION_COUNT = 60;
+ const DEFAULT_LIMIT = 50;
+ for (const i of Array.from({ length: CONVERSATION_COUNT }, (_, idx) => idx)) {
+ conversationStore.set(`conv_${i}`, makeConversation({ id: `conv_${i}` }));
+ }
+ const result = await subject.listConversations({
+ projectId: 'proj_1',
+ userId: 'user_1',
+ });
+ expect(result).toHaveLength(DEFAULT_LIMIT);
+});
+
+test('upsertConversationTitle creates the row when it does not exist yet', async () => {
+ const result = await subject.upsertConversationTitle({
+ id: 'conv_new',
+ title: 'Hello',
+ projectId: 'proj_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ });
+ expect(result).toMatchObject({
+ id: 'conv_new',
+ title: 'Hello',
+ userId: 'user_1',
+ });
+});
+
+test('upsertConversationTitle only updates the title on an existing row', async () => {
+ // The race this upsert guards against: the row already exists under a
+ // different owner (the agent's save won first) — only the title changes.
+ conversationStore.set(
+ 'conv_1',
+ makeConversation({
+ id: 'conv_1',
+ projectId: 'proj_other',
+ userId: 'user_other',
+ })
+ );
+ const result = await subject.upsertConversationTitle({
+ id: 'conv_1',
+ title: 'Renamed',
+ projectId: 'proj_1',
+ organizationId: 'org_1',
+ userId: 'user_1',
+ });
+ expect(result).toMatchObject({
+ id: 'conv_1',
+ title: 'Renamed',
+ projectId: 'proj_other',
+ userId: 'user_other',
+ });
+});
+
+test('deleteConversation removes the row', async () => {
+ conversationStore.set('conv_1', makeConversation({ id: 'conv_1' }));
+ await subject.deleteConversation('conv_1');
+ expect(conversationStore.has('conv_1')).toBe(false);
+});
diff --git a/packages/core/src/modules/conversation/conversation.service.ts b/packages/core/src/modules/conversation/conversation.service.ts
new file mode 100644
index 000000000..e0c10d939
--- /dev/null
+++ b/packages/core/src/modules/conversation/conversation.service.ts
@@ -0,0 +1,94 @@
+// Moved from packages/db/src/services/conversation.service.ts (M5-006).
+// packages/db keeps a re-export shim (unlike cohort/import, M5-003/004):
+// apps/api's live chat route and this package's own assistant.routes.ts stub
+// both still reach these through `@openpanel/db`'s barrel.
+//
+// db access is LAZY, not a static top-level import — see insight.service.ts's
+// header for the full reasoning (jobs.registry.ts and services.ts pull this
+// module into the eager barrel chain nearly every core test file reaches, and
+// constructing @openpanel/db's clients at import time would spawn a
+// pino-pretty transport worker thread per test file).
+
+import type {
+ ChatMessage,
+ Conversation,
+ Prisma,
+} from '@openpanel/db/src/prisma-client';
+
+export type IServiceConversation = Conversation;
+export type IServiceChatMessage = ChatMessage;
+export type IServiceConversationWithMessages = Prisma.ConversationGetPayload<{
+ include: { messages: true };
+}>;
+
+const DEFAULT_LIST_LIMIT = 50;
+
+function loadDb() {
+ return import('@openpanel/db/src/prisma-client').then((m) => m.db);
+}
+
+export async function getConversationById(
+ id: string,
+ options: { withMessages?: boolean } = {}
+): Promise<IServiceConversation | IServiceConversationWithMessages | null> {
+ const db = await loadDb();
+ if (options.withMessages) {
+ return db.conversation.findUnique({
+ where: { id },
+ include: {
+ messages: { orderBy: { createdAt: 'asc' } },
+ },
+ });
+ }
+ return db.conversation.findUnique({ where: { id } });
+}
+
+export async function listConversations(input: {
+ projectId: string;
+ userId: string;
+ limit?: number;
+}): Promise<IServiceConversation[]> {
+ const db = await loadDb();
+ return db.conversation.findMany({
+ where: {
+ projectId: input.projectId,
+ userId: input.userId,
+ },
+ orderBy: { updatedAt: 'desc' },
+ take: input.limit ?? DEFAULT_LIST_LIMIT,
+ });
+}
+
+/**
+ * Set the title on a conversation, creating the row if it doesn't
+ * exist yet. Used by the chat titler: on the first turn we stream a
+ * title in parallel with the agent run, and the titler may finish
+ * before the agent's `ConversationStore.save()` has inserted the row.
+ * This upsert makes that race harmless — the row ends up with the
+ * right owner + title regardless of which side finishes first.
+ */
+export async function upsertConversationTitle(input: {
+ id: string;
+ title: string;
+ projectId: string;
+ organizationId: string;
+ userId: string;
+}): Promise<IServiceConversation> {
+ const db = await loadDb();
+ return db.conversation.upsert({
+ where: { id: input.id },
+ create: {
+ id: input.id,
+ title: input.title,
+ projectId: input.projectId,
+ organizationId: input.organizationId,
+ userId: input.userId,
+ },
+ update: { title: input.title },
+ });
+}
+
+export async function deleteConversation(id: string): Promise<void> {
+ const db = await loadDb();
+ await db.conversation.delete({ where: { id } });
+}
diff --git a/packages/core/src/modules/conversation/src/access.ts b/packages/core/src/modules/conversation/src/access.ts
new file mode 100644
index 000000000..de4a4168e
--- /dev/null
+++ b/packages/core/src/modules/conversation/src/access.ts
@@ -0,0 +1,21 @@
+// Binds core's shared/access.ts ladder to @openpanel/db's real lookups, for
+// this module's own router — the same binding packages/trpc/src/access.ts
+// does for V1, self-contained here because the general core -> db binding
+// itself moves with auth (P6), not this wave.
+
+import {
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectAccess,
+} from '@openpanel/db/src/services/access.service';
+import { getProjectById } from '@openpanel/db/src/services/project.service';
+import { createAccessChecks } from '../../../shared/access';
+
+const checks = createAccessChecks({
+ getProjectAccess,
+ canWriteProject,
+ getOrganizationAccess,
+ getProjectById,
+});
+
+export const requireProjectAccess = checks.requireProjectAccess;
diff --git a/packages/core/src/rpc.router.ts b/packages/core/src/rpc.router.ts
index 35d37a036..7f50649da 100644
--- a/packages/core/src/rpc.router.ts
+++ b/packages/core/src/rpc.router.ts
@@ -6,6 +6,7 @@
import { chatRouter } from './modules/assistant/assistant.rpc';
import { cohortRouter } from './modules/cohort/cohort.rpc';
+import { conversationRouter } from './modules/conversation/conversation.rpc';
import { gscRouter } from './modules/gsc/gsc.rpc';
import { healthRouter } from './modules/health/health.rpc';
import { importRouter } from './modules/import/import.rpc';
@@ -19,6 +20,7 @@ export const appRouter = createTRPCRouter({
cohort: cohortRouter,
import: importRouter,
chat: chatRouter,
+ conversation: conversationRouter,
});
export type AppRouter = typeof appRouter;
diff --git a/packages/db/src/services/conversation.service.ts b/packages/db/src/services/conversation.service.ts
index 8beff4ada..4e8fbd08a 100644
--- a/packages/db/src/services/conversation.service.ts
+++ b/packages/db/src/services/conversation.service.ts
@@ -1,70 +1,15 @@
-import type { ChatMessage, Conversation, Prisma } from '../prisma-client';
-import { db } from '../prisma-client';
-
-export type IServiceConversation = Conversation;
-export type IServiceChatMessage = ChatMessage;
-export type IServiceConversationWithMessages = Prisma.ConversationGetPayload<{
- include: { messages: true };
-}>;
-
-export async function getConversationById(
- id: string,
- options: { withMessages?: boolean } = {},
-): Promise<IServiceConversation | IServiceConversationWithMessages | null> {
- if (options.withMessages) {
- return db.conversation.findUnique({
- where: { id },
- include: {
- messages: { orderBy: { createdAt: 'asc' } },
- },
- });
- }
- return db.conversation.findUnique({ where: { id } });
-}
-
-export async function listConversations(input: {
- projectId: string;
- userId: string;
- limit?: number;
-}): Promise<IServiceConversation[]> {
- return db.conversation.findMany({
- where: {
- projectId: input.projectId,
- userId: input.userId,
- },
- orderBy: { updatedAt: 'desc' },
- take: input.limit ?? 50,
- });
-}
-
-/**
- * Set the title on a conversation, creating the row if it doesn't
- * exist yet. Used by the chat titler: on the first turn we stream a
- * title in parallel with the agent run, and the titler may finish
- * before the agent's `ConversationStore.save()` has inserted the row.
- * This upsert makes that race harmless — the row ends up with the
- * right owner + title regardless of which side finishes first.
- */
-export async function upsertConversationTitle(input: {
- id: string;
- title: string;
- projectId: string;
- organizationId: string;
- userId: string;
-}): Promise<IServiceConversation> {
- return db.conversation.upsert({
- where: { id: input.id },
- create: {
- id: input.id,
- title: input.title,
- projectId: input.projectId,
- organizationId: input.organizationId,
- userId: input.userId,
- },
- update: { title: input.title },
- });
-}
-
-export async function deleteConversation(id: string): Promise<void> {
- await db.conversation.delete({ where: { id } });
-}
+// Moved to @openpanel/core's conversation module (M5-006). Re-exported here
+// for existing `@openpanel/db` importers (apps/api's live chat route,
+// core's own assistant.routes.ts stub) — same shape as
+// packages/db/src/services/gsc.service.ts since M5-002.
+export type {
+ IServiceChatMessage,
+ IServiceConversation,
+ IServiceConversationWithMessages,
+} from '@openpanel/core';
+export {
+ deleteConversation,
+ getConversationById,
+ listConversations,
+ upsertConversationTitle,
+} from '@openpanel/core';
diff --git a/packages/trpc/src/routers/conversation.ts b/packages/trpc/src/routers/conversation.ts
index f81056faf..87aca56a9 100644
--- a/packages/trpc/src/routers/conversation.ts
+++ b/packages/trpc/src/routers/conversation.ts
@@ -1,14 +1,18 @@
-import { TRPCError } from '@trpc/server';
-import { z } from 'zod';
-
+// Dissolved into @openpanel/core's conversation module (M5-006): the CRUD
+// itself moved to packages/core/src/modules/conversation/conversation.service.ts.
+// This router stays (DELEGATE PATTERN) — it keeps V1's protectedProcedure
+// stack (session/access/logger/rate-limit middleware) and delegates every
+// handler body to core's conversation functions, same as cohort's router
+// does for its compute functions (M5-003).
import {
deleteConversation,
getConversationById,
- getOrganizationByProjectIdCached,
listConversations,
upsertConversationTitle,
-} from '@openpanel/db';
-
+} from '@openpanel/core';
+import { getOrganizationByProjectIdCached } from '@openpanel/db';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
import { getProjectAccess, requireProjectAccess } from '../access';
import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
@@ -27,7 +31,7 @@ export const conversationRouter = createTRPCRouter({
z.object({
projectId: z.string(),
limit: z.number().min(1).max(200).default(50),
- }),
+ })
)
.query(async ({ input, ctx }) => {
const access = await getProjectAccess({
@@ -49,7 +53,10 @@ export const conversationRouter = createTRPCRouter({
.query(async ({ input, ctx }) => {
const conv = await getConversationById(input.id, { withMessages: true });
if (!conv || conv.userId !== ctx.session.userId) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Conversation not found' });
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Conversation not found',
+ });
}
return conv;
}),
@@ -70,7 +77,7 @@ export const conversationRouter = createTRPCRouter({
* project, not trusted from the client.
*/
projectId: z.string(),
- }),
+ })
)
.mutation(async ({ input, ctx }) => {
// If the conversation already exists, enforce ownership. If it
@@ -96,7 +103,7 @@ export const conversationRouter = createTRPCRouter({
// the project (they'd still be able to tag the conversation with
// an unrelated org id).
const organization = await getOrganizationByProjectIdCached(
- input.projectId,
+ input.projectId
);
if (!organization) {
throw new TRPCError({
@@ -118,7 +125,10 @@ export const conversationRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
const conv = await getConversationById(input.id);
if (!conv || conv.userId !== ctx.session.userId) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Conversation not found' });
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Conversation not found',
+ });
}
await deleteConversation(input.id);
return { success: true };