Skip to content

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

ralph(M15-106): Per-module fixes: packages/core/src/modules/conversation - R2, R13 and the findings no rule covers

ralph1de0589b0649
diff --git a/apps/start/src/components/chat/chat-drawer-header.tsx b/apps/start/src/components/chat/chat-drawer-header.tsx
index 73cbeeb26..eb53ea8ea 100644
--- a/apps/start/src/components/chat/chat-drawer-header.tsx
+++ b/apps/start/src/components/chat/chat-drawer-header.tsx
@@ -8,6 +8,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useTRPC } from '@/integrations/trpc/react';
+import { CONVERSATION_LIST_LIMIT_DEFAULT } from '@openpanel/core/modules/conversation/conversation.constants';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { MessageSquarePlusIcon, Trash2Icon, XIcon } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
@@ -34,7 +35,10 @@ export function ChatDrawerHeader({
useChatState();
const { data: conversations } = useQuery(
- trpc.conversation.list.queryOptions({ projectId, limit: 50 }),
+ trpc.conversation.list.queryOptions({
+ projectId,
+ limit: CONVERSATION_LIST_LIMIT_DEFAULT,
+ }),
);
const deleteMutation = useMutation(
diff --git a/apps/start/src/components/chat/title-stream.tsx b/apps/start/src/components/chat/title-stream.tsx
index de0be5072..55d0dc061 100644
--- a/apps/start/src/components/chat/title-stream.tsx
+++ b/apps/start/src/components/chat/title-stream.tsx
@@ -1,4 +1,5 @@
import type { AppClient } from '@/agents/client';
+import { CONVERSATION_TITLE_MAX_LENGTH } from '@openpanel/core/modules/conversation/conversation.constants';
/**
* Stream a conversation title from the backend `__titler` agent.
@@ -37,11 +38,11 @@ export async function streamTitle(
const maybe = event as { type?: string; delta?: string };
if (maybe.type === 'TEXT_MESSAGE_CONTENT' && typeof maybe.delta === 'string') {
accumulated += maybe.delta;
- onDelta(accumulated.trim().slice(0, 80));
+ onDelta(accumulated.trim().slice(0, CONVERSATION_TITLE_MAX_LENGTH));
}
}
if (signal?.aborted) return null;
- return accumulated.trim().slice(0, 80) || null;
+ return accumulated.trim().slice(0, CONVERSATION_TITLE_MAX_LENGTH) || null;
} catch (err) {
console.error('[chat] title stream failed', err);
return null;
diff --git a/packages/core/src/modules/conversation/conversation.constants.ts b/packages/core/src/modules/conversation/conversation.constants.ts
new file mode 100644
index 000000000..5fc2f9b19
--- /dev/null
+++ b/packages/core/src/modules/conversation/conversation.constants.ts
@@ -0,0 +1,9 @@
+// Shared with the frontend (chat-drawer-header.tsx, title-stream.tsx) so the
+// page size / title length and the zod defaults never drift apart (ADR-022
+// R8, "Not covered by any rule" #3 in docs/review/conversation.md).
+//
+// Isomorphic by the AGENTS.md rule: zod and nothing else.
+
+export const CONVERSATION_LIST_LIMIT_DEFAULT = 50;
+export const CONVERSATION_TITLE_MIN_LENGTH = 1;
+export const CONVERSATION_TITLE_MAX_LENGTH = 80;
diff --git a/packages/core/src/modules/conversation/conversation.rpc.test.ts b/packages/core/src/modules/conversation/conversation.rpc.test.ts
index c8cb5e777..c5587dada 100644
--- a/packages/core/src/modules/conversation/conversation.rpc.test.ts
+++ b/packages/core/src/modules/conversation/conversation.rpc.test.ts
@@ -37,13 +37,6 @@ test('list rejects an unauthenticated caller before touching a project', async (
});
});
-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(
diff --git a/packages/core/src/modules/conversation/conversation.rpc.ts b/packages/core/src/modules/conversation/conversation.rpc.ts
index 56d21345f..b0f241cc6 100644
--- a/packages/core/src/modules/conversation/conversation.rpc.ts
+++ b/packages/core/src/modules/conversation/conversation.rpc.ts
@@ -5,8 +5,8 @@
// the input parser, exactly as V1 does. `enforceAccess` reads the raw,
// pre-zod input and only a TOP-LEVEL `projectId` (ADR-011) — `list` and
// `rename` both take one, so their project access is already enforced
-// before the handler runs. `get` and `delete` take only `id`, invisible to
-// `enforceAccess`, so their ownership check stays in the handler.
+// before the handler runs. `delete` takes only `id`, invisible to
+// `enforceAccess`, so its ownership check stays in the handler.
//
// `ctx.services.conversation` carries this module's factory (M10-004).
//
@@ -17,17 +17,21 @@ import { z } from 'zod';
import { createTRPCRouter, protectedProcedure } from '../../rpc/base';
import { TRPCNotFoundError } from '../../rpc/errors';
import { getOrganizationByProjectIdCached } from '../organization/organization.service';
-import { DEFAULT_LIST_LIMIT } from './conversation.service';
+import {
+ CONVERSATION_LIST_LIMIT_DEFAULT,
+ CONVERSATION_TITLE_MAX_LENGTH,
+ CONVERSATION_TITLE_MIN_LENGTH,
+} from './conversation.constants';
const LIST_LIMIT_MIN = 1;
const LIST_LIMIT_MAX = 200;
-const TITLE_MIN_LENGTH = 1;
-const TITLE_MAX_LENGTH = 80;
/**
- * Conversation management — listing, fetching, renaming, deleting.
+ * Conversation management — listing, renaming, deleting.
* Conversation creation is implicit (lazy) on the first message via the
- * /ai/agents/* route, so there's no `create` here.
+ * /ai/agents/* route, so there's no `create` here. Fetching a single
+ * conversation's content also goes through that route (`assistant.routes.ts`),
+ * not this router — there is no `get` (ADR-022 R2, docs/review/conversation.md R2-a).
*
* All procedures enforce ownership via `userId === session.userId` so a
* user can never read or mutate another user's conversations.
@@ -41,7 +45,7 @@ export const conversationRouter = createTRPCRouter({
.number()
.min(LIST_LIMIT_MIN)
.max(LIST_LIMIT_MAX)
- .default(DEFAULT_LIST_LIMIT),
+ .default(CONVERSATION_LIST_LIMIT_DEFAULT),
})
)
.query(({ input, ctx }) =>
@@ -52,20 +56,6 @@ export const conversationRouter = createTRPCRouter({
})
),
- get: protectedProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- const userId = ctx.session.userId;
- const conv = await ctx.services.conversation.getConversationById(
- input.id,
- { withMessages: true }
- );
- if (!conv || conv.userId !== userId) {
- throw new TRPCNotFoundError('Conversation not found');
- }
- return conv;
- }),
-
rename: protectedProcedure
// A conversation belongs to the caller, not to the project - titling your
// own chat is not a project mutation. Ownership is enforced below.
@@ -73,7 +63,10 @@ export const conversationRouter = createTRPCRouter({
.input(
z.object({
id: z.string(),
- title: z.string().min(TITLE_MIN_LENGTH).max(TITLE_MAX_LENGTH),
+ title: z
+ .string()
+ .min(CONVERSATION_TITLE_MIN_LENGTH)
+ .max(CONVERSATION_TITLE_MAX_LENGTH),
/**
* Required so we can create the row if the titler finishes
* before the agent's first persistence save. When the row
diff --git a/packages/core/src/modules/conversation/conversation.service.ts b/packages/core/src/modules/conversation/conversation.service.ts
index 514283c5d..d80381eb7 100644
--- a/packages/core/src/modules/conversation/conversation.service.ts
+++ b/packages/core/src/modules/conversation/conversation.service.ts
@@ -7,6 +7,7 @@ import type {
Prisma,
} from '@openpanel/db/src/prisma-client';
import type { ServiceDeps, Services } from '../../services';
+import { CONVERSATION_LIST_LIMIT_DEFAULT } from './conversation.constants';
export type IServiceConversation = Conversation;
export type IServiceChatMessage = ChatMessage;
@@ -14,10 +15,7 @@ export type IServiceConversationWithMessages = Prisma.ConversationGetPayload<{
include: { messages: true };
}>;
-// Shared with conversation.rpc.ts's zod default, so the two never drift.
-export const DEFAULT_LIST_LIMIT = 50;
-
-export async function getConversationById(
+async function getConversationByIdImpl(
deps: ServiceDeps,
id: string,
options: { withMessages?: boolean } = {}
@@ -33,6 +31,27 @@ export async function getConversationById(
return deps.db.conversation.findUnique({ where: { id } });
}
+// Overloaded so a caller's static type matches what it actually asked for,
+// instead of the three-way union every call used to get regardless of
+// `options` (docs/review/conversation.md, "Not covered by any rule" #4).
+export function getConversationById(
+ deps: ServiceDeps,
+ id: string,
+ options: { withMessages: true }
+): Promise<IServiceConversationWithMessages | null>;
+export function getConversationById(
+ deps: ServiceDeps,
+ id: string,
+ options?: { withMessages?: false }
+): Promise<IServiceConversation | null>;
+export function getConversationById(
+ deps: ServiceDeps,
+ id: string,
+ options?: { withMessages?: boolean }
+): Promise<IServiceConversation | IServiceConversationWithMessages | null> {
+ return getConversationByIdImpl(deps, id, options);
+}
+
export async function listConversations(
deps: ServiceDeps,
input: {
@@ -47,7 +66,7 @@ export async function listConversations(
userId: input.userId,
},
orderBy: { updatedAt: 'desc' },
- take: input.limit ?? DEFAULT_LIST_LIMIT,
+ take: input.limit ?? CONVERSATION_LIST_LIMIT_DEFAULT,
});
}
@@ -93,12 +112,26 @@ export function createConversationService(
deps: ServiceDeps,
_services: () => Services
) {
+ // Re-declared (not just re-exported) so the bound version a caller
+ // actually reaches through `ctx.services.conversation` keeps the same
+ // per-call narrowing as the standalone export above.
+ function boundGetConversationById(
+ id: string,
+ options: { withMessages: true }
+ ): Promise<IServiceConversationWithMessages | null>;
+ function boundGetConversationById(
+ id: string,
+ options?: { withMessages?: false }
+ ): Promise<IServiceConversation | null>;
+ function boundGetConversationById(
+ id: string,
+ options?: { withMessages?: boolean }
+ ): Promise<IServiceConversation | IServiceConversationWithMessages | null> {
+ return getConversationByIdImpl(deps, id, options);
+ }
+
return {
- getConversationById: (
- id: string,
- options?: { withMessages?: boolean }
- ): ReturnType<typeof getConversationById> =>
- getConversationById(deps, id, options),
+ getConversationById: boundGetConversationById,
listConversations: (
input: Parameters<typeof listConversations>[1]
): Promise<IServiceConversation[]> => listConversations(deps, input),