π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(database): split the 5833-line MessageModel into cohesive modules (#21132)
Arvin Xu4ee655dd0878
diff --git a/packages/database/src/models/__tests__/messages/message.fileUrlConcurrency.test.ts b/packages/database/src/models/__tests__/messages/message.fileUrlConcurrency.test.tsnew file mode 100644index 00000000000..7c6827c9cc7--- /dev/null+++ b/packages/database/src/models/__tests__/messages/message.fileUrlConcurrency.test.ts@@ -0,0 +1,79 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { files, messages, messagesFiles, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { MessageModel } from '../../message';+import { FILE_URL_POST_PROCESS_CONCURRENCY } from '../../message/attachments';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'message-file-url-concurrency-test';+const messageModel = new MessageModel(serverDB, userId);+const FILE_COUNT = FILE_URL_POST_PROCESS_CONCURRENCY + 5;+const fileIds = Array.from({ length: FILE_COUNT }, (_, index) => `fuc-file-${index}`);++/** Presigner that records the peak number of in-flight calls. */+const createTrackingPostProcessUrl = () => {+ let inFlight = 0;+ const stats = { calls: 0, maxInFlight: 0 };+ const postProcessUrl = async (path: string | null, file: { id?: string | null }) => {+ stats.calls += 1;+ inFlight += 1;+ stats.maxInFlight = Math.max(stats.maxInFlight, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 5));+ inFlight -= 1;+ return `https://cdn.example.com/${file.id}/${path}`;+ };+ return { postProcessUrl, stats };+};++beforeEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(messages).values({+ content: 'message with many attachments',+ id: 'fuc-message',+ role: 'user',+ userId,+ });+ await serverDB+ .insert(files)+ .values(+ fileIds.map((id) => ({ fileType: 'image/png', id, name: id, size: 100, url: 'raw', userId })),+ );+ await serverDB+ .insert(messagesFiles)+ .values(fileIds.map((fileId) => ({ fileId, messageId: 'fuc-message', userId })));+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+});++describe('MessageModel attachment URL post-processing', () => {+ it('caps concurrent postProcessUrl calls in query', async () => {+ const { postProcessUrl, stats } = createTrackingPostProcessUrl();++ const [message] = await messageModel.query({}, { postProcessUrl });++ expect(stats.calls).toBe(FILE_COUNT);+ expect(stats.maxInFlight).toBeLessThanOrEqual(FILE_URL_POST_PROCESS_CONCURRENCY);+ expect(message.imageList).toHaveLength(FILE_COUNT);+ for (const image of message.imageList ?? []) {+ expect(image.url).toBe(`https://cdn.example.com/${image.id}/raw`);+ }+ });++ it('caps concurrent postProcessUrl calls in queryByIds', async () => {+ const { postProcessUrl, stats } = createTrackingPostProcessUrl();++ const [message] = await messageModel.queryByIds(['fuc-message'], { postProcessUrl });++ expect(stats.calls).toBe(FILE_COUNT);+ expect(stats.maxInFlight).toBeLessThanOrEqual(FILE_URL_POST_PROCESS_CONCURRENCY);+ expect(message.imageList).toHaveLength(FILE_COUNT);+ });+});diff --git a/packages/database/src/models/__tests__/messages/message.publicApi.test.ts b/packages/database/src/models/__tests__/messages/message.publicApi.test.tsnew file mode 100644index 00000000000..0c7f1f66b86--- /dev/null+++ b/packages/database/src/models/__tests__/messages/message.publicApi.test.ts@@ -0,0 +1,161 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import * as messageModule from '../../message';+import { MessageModel } from '../../message';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'message-public-api-user';++beforeEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.insert(users).values([{ id: userId }]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+});++/**+ * Every public instance method of `MessageModel`. They are bound arrow+ * properties, so callers may destructure them or pass them around detached.+ */+const PUBLIC_INSTANCE_METHODS = [+ 'addFiles',+ 'batchCreate',+ 'batchDeleteByAgentId',+ 'count',+ 'countApproximate',+ 'countByTopic',+ 'countGroupByTopic',+ 'countUpTo',+ 'countWords',+ 'create',+ 'createMessageQuery',+ 'createUserAndAssistantMessages',+ 'deleteAllMessages',+ 'deleteMessage',+ 'deleteMessageQuery',+ 'deleteMessages',+ 'deleteMessagesBySession',+ 'deleteMessageTranslate',+ 'deleteMessageTTS',+ 'findById',+ 'findByClientId',+ 'findFirstAssistantInTopic',+ 'findLatestAssistantByOperationId',+ 'findLatestAssistantMessageByThread',+ 'findLatestPluginStateInTopic',+ 'findMessagePlugin',+ 'findMessageQueriesById',+ 'findShareVisitorMessageIds',+ 'findToolMessageIdByToolCallId',+ 'findTrashedByIds',+ 'findVerifyMessageByOperationId',+ 'getHeatmaps',+ 'getLastMainThreadSpineMessageId',+ 'getLatestNonToolMessageId',+ 'getLatestSpineMessageId',+ 'getThreadParentMessages',+ 'getTokenHeatmaps',+ 'hasMoreThanN',+ 'hasTopicMessages',+ 'isMessageDescendantOf',+ 'listMessagePluginsByIds',+ 'listMessagePluginsByTopic',+ 'listMessagePluginsForOperation',+ 'purgeMessages',+ 'query',+ 'queryAll',+ 'queryByIds',+ 'queryByKeyword',+ 'queryBySessionId',+ 'queryForVisitor',+ 'queryLastUserMessageByTopics',+ 'queryTopicMessagesByCursor',+ 'queryTopicMessageTree',+ 'queryTopicTranscript',+ 'queryWithWhere',+ 'rankModels',+ 'resolveHumanApproval',+ 'restoreHumanApproval',+ 'restoreMessages',+ 'softDeleteMessages',+ 'softDeleteTopicless',+ 'topicMessageStats',+ 'update',+ 'updateMessagePlugin',+ 'updateMetadata',+ 'updatePluginState',+ 'updateToolArguments',+ 'updateToolMessage',+ 'updateTranslate',+ 'updateTTS',+] as const;++describe('MessageModel public API', () => {+ it('exposes every public method as an own function property', () => {+ const model = new MessageModel(serverDB, userId);++ for (const name of PUBLIC_INSTANCE_METHODS) {+ expect(Object.prototype.hasOwnProperty.call(model, name), name).toBe(true);+ expect(typeof model[name], name).toBe('function');+ }+ });++ it('keeps updateMessageRAG on the prototype and checkUsersHaveMessages static', () => {+ expect(typeof MessageModel.prototype.updateMessageRAG).toBe('function');+ expect(typeof MessageModel.checkUsersHaveMessages).toBe('function');+ });++ it('keeps the runtime exports of the module entry', () => {+ expect(Object.keys(messageModule).sort()).toEqual([+ 'HumanApprovalAlreadyResolvedError',+ 'MessageModel',+ 'redactCreatorPrivateBlob',+ 'sanitizeVisitorError',+ 'toVisitorMessage',+ ]);+ });++ it('runs detached methods against the instance scope', async () => {+ const model = new MessageModel(serverDB, userId);+ const { count, create, deleteMessage, findById, queryByIds, update } = model;++ const created = await create({ content: 'hello', role: 'user' });+ await update(created.id, { content: 'hello again' });++ expect((await findById(created.id))?.content).toBe('hello again');+ expect((await queryByIds([created.id])).map((m) => m.id)).toEqual([created.id]);+ expect(await count()).toBe(1);++ await deleteMessage(created.id);++ expect(await findById(created.id)).toBeUndefined();+ expect(await count()).toBe(0);+ });++ it('scopes detached methods to the constructing user', async () => {+ const otherUserId = 'message-public-api-other';+ await serverDB.delete(users).where(eq(users.id, otherUserId));+ await serverDB.insert(users).values([{ id: otherUserId }]);++ try {+ const created = await new MessageModel(serverDB, userId).create({+ content: 'mine',+ role: 'user',+ });+ const { count, findById } = new MessageModel(serverDB, otherUserId);++ expect(await findById(created.id)).toBeUndefined();+ expect(await count()).toBe(0);+ } finally {+ await serverDB.delete(users).where(eq(users.id, otherUserId));+ }+ });+});diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.tsindex 5888bbd8397..c4aefe4197e 100644--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts@@ -8,6 +8,7 @@ import { getTestDB } from '../../../core/getTestDB';import { agents, embeddings, files, messages, sessions, topics, users } from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { MessageModel } from '../../message';+import { MessageScope } from '../../message/scope';import { codeEmbedding } from '../fixtures/embedding';const serverDB: LobeChatDatabase = await getTestDB();@@ -233,11 +234,12 @@ describe('MessageModel Statistics Tests', () => {describe('genId', () => {it('should generate unique message IDs', () => {- const model = new MessageModel(serverDB, userId);- // @ts-ignore - accessing private method for testing- const id1 = model.genId();- // @ts-ignore - accessing private method for testing- const id2 = model.genId();+ // genId lives on the shared scope every MessageModel sub-domain extends+ const scope = new MessageScope(serverDB, userId);+ // @ts-ignore - accessing protected method for testing+ const id1 = scope.genId();+ // @ts-ignore - accessing protected method for testing+ const id2 = scope.genId();expect(id1).toHaveLength(22);expect(id2).toHaveLength(22);diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsdeleted file mode 100644index 0f5721e45f3..00000000000--- a/packages/database/src/models/message.ts+++ /dev/null@@ -1,5833 +0,0 @@-import { INBOX_SESSION_ID } from '@lobechat/const';-import { parse } from '@lobechat/conversation-flow';-import type {- AssistantContentBlock,- ChatAudioItem,- ChatFileItem,- ChatImageItem,- ChatMessageError,- ChatMessageExtra,- ChatToolPayload,- ChatTranslate,- ChatTTS,- ChatVideoItem,- CreateMessageParams,- DBMessageItem,- HeterogeneousToolStateSnapshot,- IThreadType,- MessageMetadata,- MessagePluginItem,- ModelRankItem,- ModelReasoning,- ModelUsage,- NewMessageQueryParams,- QueryMessageParams,- TaskDetail,- ThreadStatus,- UIChatMessage,- UISignalCallbacksBlock,- UpdateMessageParams,- UpdateMessageRAGParams,- WorkAccessScope,- WorkSummaryItem,-} from '@lobechat/types';-import {- AgentRuntimeErrorType,- ChatErrorType,- MessageGroupType,- ThreadType,-} from '@lobechat/types';-import type { TimingSink } from '@lobechat/utils';-import {- getDurationMs,- logTimingSink as logTiming,- readAudioDurationMs,- runTimedSinkStage as runTimedStage,-} from '@lobechat/utils';-import { isPlainRecord } from '@lobechat/utils/object';-import type { HeatmapsProps } from '@lobehub/charts';-import dayjs from 'dayjs';-import type { SQL } from 'drizzle-orm';-import {- and,- asc,- count,- desc,- eq,- getTableColumns,- gt,- gte,- inArray,- isNotNull,- isNull,- lt,- lte,- ne,- not,- or,- sql,-} from 'drizzle-orm';--import { clampToolIdentifier } from '@/utils/clampToolIdentifier';-import { merge } from '@/utils/merge';-import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';-import { today } from '@/utils/time';--import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';-import {- agents,- agentsToSessions,- chunks,- documents,- embeddings,- fileChunks,- files,- messageGroups,- messagePlugins,- messageQueries,- messageQueryChunks,- messages,- messagesFiles,- messageTranslates,- messageTTS,- threads,- topics,- users,-} from '../schemas';-import type { LobeChatDatabase, Transaction } from '../type';-import { sanitizeBm25Query } from '../utils/bm25';-import { notCopiedTranscript } from '../utils/copiedTranscript';-import { notFileBackedPlaceholder } from '../utils/fileBackedPlaceholder';-import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';-import { idGenerator } from '../utils/idGenerator';-import { inJsonStringArray } from '../utils/inJsonStringArray';-import { documentOriginalCharCount } from '../utils/originalCharCount';-import { searchableMessage } from '../utils/searchableMessage';-import { notShareVisitorMessage, notShareVisitorTopicRef } from '../utils/shareVisitor';-import { isTrashed, restoreStamp, type SoftDeleteOptions, trashStamp } from '../utils/softDelete';-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';-import { recomputeTopicUsage } from './topicUsage';-import { WorkModel } from './work';--/**- * Parsed-document columns attached to chat file items. `originalCharCount` is only set when the- * stored text was cut at parse time; prompts use it to tell the model the text is incomplete.- * Selected as a scalar so the rest of `metadata` never leaves the database.- */-const fileDocumentColumns = {- content: documents.content,- fileId: documents.fileId,- originalCharCount: documentOriginalCharCount().mapWith(Number),-};--/**- * A file can own more than one document (`parseDocument` writes a page-editor copy next to the parse- * cache). Every reader picks the oldest, matching `DocumentModel.findByFileId`, so a preview and the- * `readAttachment` pages that continue it come from the same text.- */-const fileDocumentsOrder = [asc(documents.createdAt), asc(documents.id)];--type FileDocumentsMap = Record<string, { content: string; originalCharCount?: number }>;--const toFileDocumentsMap = (- rows: { content: string | null; fileId: string | null; originalCharCount: number | null }[],-): FileDocumentsMap =>- rows.reduce<FileDocumentsMap>((acc, doc) => {- // Rows arrive oldest first (see `fileDocumentsOrder`); keep the first so the prompt shows the- // same document `DocumentModel.findByFileId` β and therefore `readAttachment` β pages through.- if (doc.fileId && !(doc.fileId in acc)) {- acc[doc.fileId] = {- content: doc.content as string,- originalCharCount: doc.originalCharCount ?? undefined,- };- }- return acc;- }, {});--const createChatImageItem = ({- fileType,- id,- metadata,- name,- url,-}: {- fileType?: string | null;- id: string;- metadata: unknown;- name: string;- url: string;-}): ChatImageItem => {- const imageMetadata = isPlainRecord(metadata) ? metadata : {};- const toPositiveNumber = (value: unknown) =>- typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;- const height = toPositiveNumber(imageMetadata.height);- const ratio = toPositiveNumber(imageMetadata.ratio);- const width = toPositiveNumber(imageMetadata.width);-- return {- alt: name,- ...(height && { height }),- id,- ...(fileType && { mimeType: fileType }),- ...(ratio && { ratio }),- url,- ...(width && { width }),- };-};--export class HumanApprovalAlreadyResolvedError extends Error {- constructor(messageId: string) {- super(`Human approval is no longer pending for tool message ${messageId}`);- this.name = 'HumanApprovalAlreadyResolvedError';- }-}--export interface HumanApprovalResolution {- /** Conditional owner checked by rollback; never accepted as client authority. */- claimedResolutionRequestId?: string;- content?: string;- id: string;- intervention: Record<string, unknown>;- pluginError?: MessagePluginItem['error'] | null;- pluginState?: Record<string, unknown> | null;- replacePluginState?: boolean;-}--/**- * Read the operation-final Work root id stamped on a message's metadata by the- * Work registry (`metadata.work.rootOperationId`). Mirrors the client-side- * `getOperationFinalRootId` without importing from the app layer.- */-const getMessageWorkRootId = (metadata: unknown): string | undefined => {- const rootOperationId = (metadata as { work?: { rootOperationId?: unknown } } | null)?.work- ?.rootOperationId;- return typeof rootOperationId === 'string' && rootOperationId ? rootOperationId : undefined;-};--/**- * Options for querying messages with relations- */-export interface QueryMessagesOptions {- /**- * Opt IN to agent-share visitor rows for this call, overriding the default- * `ownership()` visitor exclusion. Combined via OR with the instance's- * `includeShareVisitor` flag, so an instance already opted in stays opted- * in and a default-scoped instance can still be widened per-call (this is- * how {@link MessageModel.queryForVisitor} works before the share-runtime- * routers switch to constructing the model with `{ includeShareVisitor:- * true }`).- */- allowShareVisitor?: boolean;- /**- * Round-cursor for loading older history (see `QueryMessageParams.before`):- * only rows strictly older than this `(createdAt, id)` tuple are fetched.- */- before?: { createdAt: Date; id: string };- /**- * Current page number (0-indexed)- */- current?: number;- /**- * Constrain MessageGroup assembly to an explicit `[from, before)` time window- * instead of loading every group in the topic (or deriving the window from the- * fetched rows). Set by cursor pagination so consecutive pages partition the- * topic's groups exactly once: a scroll-up page neither repeats group nodes nor- * drops the ones dated between (or older than) its mainline rows. Either bound- * may be omitted to leave that side open. Bounds are lossless microsecond- * timestamp strings compared with a `::timestamptz` cast.- */- groupNodeWindow?: MessageGroupNodeWindow;- /**- * Opt-in for `file` work summaries in the payload (see- * `QueryMessageParams.includeFileWorks`).- */- includeFileWorks?: boolean;- /**- * Number of messages per page- */- pageSize?: number;- /**- * Post-process function for file URLs- */- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;- /**- * Skip the Work-summary assembly (see `QueryMessageParams.skipWorks`).- */- skipWorks?: boolean;- timing?: ModelTimingContext;- /**- * Topic ID for MessageGroup aggregation queries- */- topicId?: string;- /**- * Custom where condition for message filtering- */- where?: SQL;- /**- * Agent Share boundary for the Work-summary assembly. Omitted = ordinary- * scope, which never resolves a share visitor's Works; the share read path- * passes `agentShareWorkAccessScope(...)` so a visitor gets exactly the- * Works registered from their own share topic.- */- workAccessScope?: WorkAccessScope;-}--export interface TopicTranscriptMessage {- agentId: string | null;- content: string | null;- createdAt: Date;- error: ChatMessageError | null;- id: string;- messageGroupId: string | null;- metadata: MessageMetadata | null;- model: string | null;- parentId: string | null;- pluginError: unknown;- provider: string | null;- reasoning: ModelReasoning | null;- role: string;- threadId: string | null;- toolCallId: string | null;- tools: ChatToolPayload[] | null;- usage: ModelUsage | null;-}--export interface TopicTranscriptResult {- items: TopicTranscriptMessage[];- total: number;-}--/**- * Round-boundary cursor for {@link MessageModel.queryTopicMessagesByCursor}. Points- * at a mainline `user` message (a round start); paging older fetches the rounds- * strictly before it.- */-export interface MessageRoundCursor {- createdAt: string;- id: string;-}--export interface QueryTopicByCursorParams {- /**- * Ignored: a concrete topic is the conversation boundary and may hold rows- * from several agents/sessions (e.g. `callAgent` replies), same as `query`.- * Accepted only so callers can forward their usual query params.- */- agentId?: string | null;- /** Hard cap on rows walked when resolving the round window (safety, ~rows). */- countBudget?: number;- /** Omit for the initial (newest) page; pass a prior `nextCursor` to load older. */- cursor?: MessageRoundCursor | null;- /** Group chat topic: rows carry the group id, same filter as `query`. */- groupId?: string | null;- /** See {@link QueryMessageParams.includeFileWorks}. */- includeFileWorks?: boolean;- /** How many rounds to load per page (the current round is always whole). */- roundLimit?: number;- /** Ignored for the same reason as `agentId`. */- sessionId?: string | null;- skipWorks?: boolean;- topicId: string;-}--export interface TopicMessagesByCursorResult {- hasMore: boolean;- messages: UIChatMessage[];- /** Cursor to load the previous (older) page, or null when at the topic start. */- nextCursor: MessageRoundCursor | null;-}--/** Default rounds per cursor page. */-const DEFAULT_ROUND_LIMIT = 10;-/** Default safety cap on rows scanned per cursor page. */-const DEFAULT_ROUND_COUNT_BUDGET = 2000;-/**- * Row ceiling for the cursor path's underlying `queryWithWhere` fetch. The `where`- * already bounds rows to the resolved round window; this only prevents an- * unbounded scan and keeps `queryWithWhere`'s newest-first trim disabled (the- * result stays below `pageSize`, so the trim guard never fires).- */-const CURSOR_PAGE_CEILING = 100_000;--/** Half-open `[from, before)` MessageGroup window; see `groupNodeWindow`. */-export interface MessageGroupNodeWindow {- before?: string | null;- from?: string | null;-}--export interface ModelTimingContext extends TimingSink {}--interface MessageRelatedFile {- fileType: string | null;- id: string;- messageId: string;- metadata: unknown;- name: string | null;- size: number | null;- url: string;-}--const materializeChatAudioItem = ({- fileType,- id,- metadata,- name,- url,-}: MessageRelatedFile): ChatAudioItem => {- const value = isPlainRecord(metadata) ? metadata : {};- const durationMs = readAudioDurationMs(metadata);-- return {- alt: name!,- ...(typeof value.codec === 'string' ? { codec: value.codec } : {}),- ...(durationMs === undefined ? {} : { durationMs }),- id,- ...(typeof value.mimeType === 'string'- ? { mimeType: value.mimeType }- : fileType- ? { mimeType: fileType }- : {}),- url,- };-};--interface MessageChunkRelation {- fileId: string;- filename: string | null;- fileType: string | null;- fileUrl: string | null;- id: string | null;- messageId: string | null;- similarity: string | null;- text: string | null;-}--interface MessageQueryRelation {- id: string;- messageId: string;- rewriteQuery: string | null;- userQuery: string | null;-}--interface MessageThreadRelation {- metadata: unknown;- sourceMessageId: string | null;- status: string | null;- threadId: string;- title: string | null;-}--interface ActiveBranchSnapshot {- activeBranchId?: string;- activeBranchIndex: number;- metadata: Record<PropertyKey, unknown>;- parentId: string;- wasOptimistic: boolean;-}--interface MessageFileRelations {- documentsMap: FileDocumentsMap;- relatedFileList: MessageRelatedFile[];-}--interface CreateUserAndAssistantMessagesParams {- assistantMessage: CreateMessageParams;- userMessage: CreateMessageParams;-}--interface CreateUserAndAssistantMessagesOptions {- /**- * Ids minted by the caller (the client) for the pair. Either side may be- * omitted, in which case this model mints that one β an older client that- * sends no ids keeps working unchanged.- *- * Honouring a caller-supplied id is what lets the UI render the pair under- * its final ids immediately, instead of showing placeholders and re-keying- * them once this insert returns.- */- ids?: {- assistantMessageId?: string;- userMessageId?: string;- };- timing?: ModelTimingContext;-}--interface CreateMessageInsertParams {- createdAt?: CreateMessageParams['createdAt'];- fromModel?: CreateMessageParams['model'];- fromProvider?: CreateMessageParams['provider'];- message: Omit<- CreateMessageParams,- | 'createdAt'- | 'fileChunks'- | 'files'- | 'model'- | 'plugin'- | 'pluginIntervention'- | 'pluginState'- | 'provider'- | 'ragQueryId'- | 'updatedAt'- >;- updatedAt?: CreateMessageParams['updatedAt'];-}--interface CreateMessageRelationParams {- fileChunks?: CreateMessageParams['fileChunks'];- files?: CreateMessageParams['files'];- plugin?: CreateMessageParams['plugin'];- pluginError?: CreateMessageParams['pluginError'];- pluginIntervention?: CreateMessageParams['pluginIntervention'];- pluginState?: CreateMessageParams['pluginState'];- ragQueryId?: CreateMessageParams['ragQueryId'];-}--interface SplitCreateMessageParams {- insert: CreateMessageInsertParams;- relations: CreateMessageRelationParams;-}--/**- * Shared, ownership-scoped filters for the analytics queries- * (count / countGroupByTopic / topicMessageStats). All of these are- * applied on top of the workspace ownership predicate, so the resulting- * query never leaks across `userId Γ workspace`.- */-export interface MessageAnalyticsFilters {- agentId?: string;- endDate?: string;- range?: [string, string];- role?: string;- startDate?: string;- topicId?: string;-}--/** A single `{ topicId, count }` row from a per-topic count aggregation. */-export interface TopicMessageCountItem {- count: number;- topicId: string;-}--/**- * Distribution of message counts per topic, computed server-side.- * Mirrors what a `SELECT count(*) ... GROUP BY topic_id` + percentile- * aggregation would produce, so the CLI receives only the summary instead- * of paginating raw rows.- */-export interface TopicMessageStats {- /** Per distinct message-count value, how many topics have it. Ascending. */- histogram: { topics: number; userCount: number }[];- max: number;- mean: number;- median: number;- min: number;- /** Number of topics with exactly one matching message ("one-shot"). */- oneshot: number;- /** oneshot / topics, in [0, 1]. 0 when there are no topics. */- oneshotRatio: number;- p90: number;- p99: number;- /** Number of topics that have at least one matching message. */- topics: number;- /** Total matching messages across all topics. */- totalMessages: number;-}--/**- * Linear-interpolation percentile over an ascending-sorted array, matching- * PostgreSQL's `percentile_cont`. Returns 0 for an empty input.- */-const percentileCont = (sorted: number[], q: number): number => {- const n = sorted.length;- if (n === 0) return 0;- if (n === 1) return sorted[0];- const rank = q * (n - 1);- const lo = Math.floor(rank);- const hi = Math.ceil(rank);- if (lo === hi) return sorted[lo];- return sorted[lo] + (sorted[hi] - sorted[lo]) * (rank - lo);-};--/** Reduce a list of per-topic message counts into a {@link TopicMessageStats}. */-const computeTopicMessageStats = (counts: number[]): TopicMessageStats => {- const topics = counts.length;- if (topics === 0) {- return {- histogram: [],- max: 0,- mean: 0,- median: 0,- min: 0,- oneshot: 0,- oneshotRatio: 0,- p90: 0,- p99: 0,- topics: 0,- totalMessages: 0,- };- }-- const sorted = [...counts].sort((a, b) => a - b);- const totalMessages = sorted.reduce((acc, c) => acc + c, 0);- const oneshot = sorted.filter((c) => c === 1).length;-- const bucket = new Map<number, number>();- for (const c of sorted) bucket.set(c, (bucket.get(c) ?? 0) + 1);- const histogram = [...bucket.entries()]- .sort(([a], [b]) => a - b)- .map(([userCount, topicCount]) => ({ topics: topicCount, userCount }));-- return {- histogram,- max: sorted[topics - 1],- mean: totalMessages / topics,- median: percentileCont(sorted, 0.5),- min: sorted[0],- oneshot,- oneshotRatio: oneshot / topics,- p90: percentileCont(sorted, 0.9),- p99: percentileCont(sorted, 0.99),- topics,- totalMessages,- };-};--// **************** Agent Share (visitor-scoped projections) *************** //--/**- * Opt-in escape hatch for the write paths that legitimately act on agent-share- * visitor rows. Visitor messages are stored under the creator's `userId`, so- * ownership alone cannot tell a creator action apart from a runtime action;- * mutation entry points therefore fail closed and only the agent runtime (which- * drives visitor turns under the creator's identity) passes this.- */-export interface ShareVisitorWriteOptions {- includeShareVisitor?: boolean;-}--/**- * Constructor options for {@link MessageModel} β mirrors the twin flag on- * {@link import('./topic').TopicModelOptions}. When `includeShareVisitor` is- * true, the instance's `ownership()` predicate no longer excludes agent-share- * visitor messages; the escape hatch that per-call {@link ShareVisitorWriteOptions}- * used to be the only way to grant. Share-only surfaces should set this at- * construction and stop threading per-call opt-ins through their code.- */-export interface MessageModelOptions {- includeShareVisitor?: boolean;-}--/**- * Per-share switches that relax {@link toVisitorMessage}'s default redaction.- * Both default to `false` (strip everything), so a caller that forgets to pass- * options gets the fail-closed projection.- */-export interface VisitorRedactionOptions {- /**- * `AgentShareConfig.showErrorDetails`. When false, a run failure is- * projected down to a generic classified `type` (see- * {@link sanitizeVisitorError}) instead of the raw- * message/provider/budget/upstream-body payload `formatErrorForState`- * builds.- */- showErrorDetails?: boolean;- /**- * `AgentShareConfig.showModelInfo`. When false, the creator's model /- * provider choice and the token/cost snapshot are stripped everywhere they- * appear, at any nesting depth.- */- showModelInfo?: boolean;-}--/**- * Fields on {@link UIChatMessage} that are safe to forward to an agent-share- * visitor verbatim: the message's OWN presentational content (text,- * attachments, tool activity, RAG citations) and structural links WITHIN the- * same shared topic (thread/group/parent ids). None of these describe the- * creator's account, billing, or model/provider choice.- *- * This is an ALLOWLIST, not a denylist, and that direction is deliberate:- * `UIChatMessage` is a ~40-field DTO shared with the normal (non-share) chat- * read path, so new fields land on it regularly as chat features ship. A- * denylist fails OPEN on every such addition β a new field reaches visitors by- * default until someone remembers to also strip it here. An allowlist fails- * CLOSED: a new field is absent from the visitor DTO until a human- * deliberately adds it below.- *- * Deliberately included despite being an id: `agentId` (the visitor already- * knows which agent they are talking to β that's the whole premise of the- * share link), `sessionId`/`traceId`/`observationId` (opaque ids scoped to- * THIS execution of the visitor's OWN turn, reused by client actions such as- * translate/regenerate that the share UI shares with normal chat).- */-const VISITOR_MESSAGE_ALLOWED_KEYS = [- 'id',- 'role',- 'content',- 'createdAt',- 'updatedAt',- 'editorData',- 'fileList',- 'files',- 'imageList',- 'videoList',- 'audioList',- 'chunksList',- 'plugin',- 'pluginIntervention',- 'tool_call_id',- 'tools',- 'reasoning',- 'search',- 'ragQuery',- 'ragQueryId',- 'ragRawQuery',- 'parentId',- 'threadId',- 'topicId',- 'groupId',- 'targetId',- 'agentId',- 'sessionId',- 'quotaId',- 'branch',- 'tasks',- 'performance',- 'observationId',- 'traceId',-] as const satisfies readonly (keyof UIChatMessage)[];--type VisitorAllowedKey = (typeof VISITOR_MESSAGE_ALLOWED_KEYS)[number];--const pickAllowedKeys = (message: UIChatMessage): Pick<UIChatMessage, VisitorAllowedKey> => {- const picked = {} as Pick<UIChatMessage, VisitorAllowedKey>;- for (const key of VISITOR_MESSAGE_ALLOWED_KEYS) {- if (key in message) (picked as Record<string, unknown>)[key] = message[key];- }- return picked;-};--/** Keep translate/TTS (visitor-facing rendering), drop the model snapshot. */-const sanitizeVisitorExtra = (extra: ChatMessageExtra | undefined): ChatMessageExtra | undefined =>- extra ? { translate: extra.translate, tts: extra.tts } : extra;--/**- * Shape shared by `pinnedMessages` entries and `compareGroup.children` entries- * (`queryMessageGroupNodes` builds them with this exact narrow projection,- * then casts the whole node `as unknown as UIChatMessage`, so- * `UIChatMessage['pinnedMessages']` / `UIChatMessage['children']`'s declared- * types do not describe them at runtime). Neither carries `sender`/`usage`,- * only the model snapshot needs stripping.- *- * NOTE: on a `compressedGroup` node, `children` is NOT this narrow shape β it- * lives inside `compressedMessages[].children` (an `AssistantContentBlock[]`- * produced by `FlatListBuilder`) and carries `usage`, `error`, `tools`,- * `metadata`, `performance`, and possibly nested `council` messages with- * `sender`. See `toVisitorMessage` for the recursion that sanitizes those.- */-interface VisitorGroupSnapshotProjection {- content: string | null;- createdAt: Date | number;- id: string;- model: string | null;- provider: string | null;- role: string;-}--const sanitizeVisitorGroupSnapshots = (- items: VisitorGroupSnapshotProjection[],-): VisitorGroupSnapshotProjection[] =>- items.map((item) => ({ ...item, model: null, provider: null }));--/** Cost/token figures are the same class of creator spend data as `usage`. */-const sanitizeVisitorTaskDetail = (taskDetail: TaskDetail | undefined): TaskDetail | undefined => {- if (!taskDetail) return taskDetail;- const {- totalCost: _totalCost,- totalTokens: _totalTokens,- totalToolCalls: _totalToolCalls,- ...rest- } = taskDetail;- return rest;-};--/**- * Key names that identify the CREATOR's model/provider choice or spend/token- * data wherever they occur inside an unbounded per-tool blob- * (`pluginState`/`pluginError`, live Gateway event payloads). A builtin tool's- * server runtime writes whatever shape it wants into `state`/error payloads β- * e.g. `lobe-agent`'s `analyzeMedia` writes `{ model, provider, usage }`- * straight into it β so unlike a short, fully enumerable list of top-level- * `UIChatMessage` fields there is no finite set of "every tool's state shape"- * to allowlist by hand: a new tool, or a new field on an existing tool's- * `state`, must be safe BY DEFAULT. Recursing this fixed key set is the- * fail-closed trade-off.- */-const CREATOR_PRIVATE_BLOB_KEYS = new Set([- 'model',- 'provider',- 'usage',- 'cost',- 'totalCost',- 'totalTokens',- 'promptTokens',- 'completionTokens',- 'inputTokens',- 'outputTokens',- // `AgentRuntimeService.publishSubAgentProgress`'s live `step_complete`- // (`subagent_progress` phase) reads these off `state.usage.llm.tokens` under- // the `total*` spelling rather than `inputTokens`/`outputTokens` β same- // class of creator token-spend data, different key name.- 'totalInputTokens',- 'totalOutputTokens',-]);--/**- * Recursively strip {@link CREATOR_PRIVATE_BLOB_KEYS} from an unbounded- * JSON-like value at ANY nesting depth. Only descends into plain- * objects/arrays (`isPlainRecord` already excludes `Date`/`Error`/class- * instances) β anything else is returned as-is, since it cannot itself carry a- * nested creator-identity field.- *- * Exported so `GatewayStreamNotifier`'s live Gateway-push chokepoint can apply- * the SAME key set to `stream_start` (`model`/`provider`), `tool_end`- * (`result`/`payload`, which can carry a tool's `state`), and `step_complete`- * (`subagent_progress`'s sibling `model`/`totalCost`/token fields) β the live- * WS payload equivalents of the persisted blobs this function was written for.- */-export const redactCreatorPrivateBlob = <T>(value: T): T => {- if (Array.isArray(value)) return value.map((item) => redactCreatorPrivateBlob(item)) as T;- if (!isPlainRecord(value)) return value;-- const result: Record<string, unknown> = {};- for (const [key, nested] of Object.entries(value)) {- if (CREATOR_PRIVATE_BLOB_KEYS.has(key)) continue;- result[key] = redactCreatorPrivateBlob(nested);- }- return result as T;-};--/**- * `ChatMessageError.type` codes that are safe to forward to a visitor- * VERBATIM, `message` included β because they are purpose-built,- * business-level codes whose throw sites already write a clean, generic- * `message` (never string-concatenated from a raw upstream payload) and whose- * NAME itself says nothing about the creator's provider/model/account: "this- * shared agent hit its per-topic turn cap", not "OpenAI rejected key sk-β¦".- * Every other code β including the LEGITIMATE quota/rate-limit codes, whose- * `message`/`body` are still built by `formatErrorForState` from the raw- * upstream error β is projected to {@link VISITOR_PUBLIC_ERROR_TYPE}. Kept as- * a narrow allowlist (fail closed) rather than an exclude list of "known- * provider-identifying codes": some codes leak the provider through the TYPE- * NAME alone (`OllamaServiceUnavailable`, `InvalidBedrockCredentials`, β¦), so- * a denylist would need to enumerate those and would miss the next one a- * model-runtime change adds.- */-const VISITOR_SAFE_ERROR_TYPES = new Set<string>([- ChatErrorType.ShareTurnLimitExceeded,- ChatErrorType.ShareTopicLimitExceeded,- ChatErrorType.ShareSpendLimitExceeded,- ChatErrorType.ShareHeterogeneousAgentUnsupported,- ChatErrorType.AgentShareProviderNotSupported,-]);--/**- * Public fallback `type` for any `ChatMessageError` whose code is not in- * {@link VISITOR_SAFE_ERROR_TYPES}. Reuses the existing generic- * `AgentRuntimeError` bucket (already localized) rather than minting a new- * code: the visitor only needs "the run failed, retry or contact the creator",- * never which of the ~60 specific runtime codes fired.- */-const VISITOR_PUBLIC_ERROR_TYPE = AgentRuntimeErrorType.AgentRuntimeError;--/**- * Sanitize a `ChatMessageError` for a visitor β PROJECTION, not the recursive- * {@link redactCreatorPrivateBlob} used for `pluginState`/`pluginError`.- * `body` has no stable set of key names to strip: it is free-form per error- * source and `formatErrorForState` deliberately copies `provider`, `budget`,- * and the raw upstream diagnostic onto it for exactly the failures a visitor- * can trigger on demand (bad key, exhausted quota, upstream 500) β so- * recursing a fixed key set would miss the next shape a new error source- * introduces. Dropping `body` wholesale and keeping only a classified `type`- * (+ `message` for the allowlisted codes) fails closed instead: the client- * re-derives its localized copy, alert styling, and error-card variant from- * `type` alone.- *- * Bypassed entirely when the share sets `showErrorDetails` β the creator has- * then explicitly opted into showing visitors the raw failure.- */-export const sanitizeVisitorError = (- error: ChatMessageError | null | undefined,- options: VisitorRedactionOptions = {},-): ChatMessageError | null | undefined => {- if (!error) return error;- if (options.showErrorDetails) return error;-- const type = error.type as unknown;- if (typeof type === 'string' && VISITOR_SAFE_ERROR_TYPES.has(type)) {- return { message: error.message, type: error.type };- }-- return { type: VISITOR_PUBLIC_ERROR_TYPE };-};--/**- * `signalCallbacks[].callbacks[]` is a denormalized per-callback snapshot built- * by `FlatListBuilder`, carrying a bare `model`/`provider` pair per callback- * turn β same leak class as `pinnedMessages`/`children`'s group-node- * snapshots.- */-const sanitizeVisitorSignalCallbacks = (- signalCallbacks: UISignalCallbacksBlock[] | undefined,-): UISignalCallbacksBlock[] | undefined =>- signalCallbacks?.map((block) => ({- ...block,- callbacks: block.callbacks.map((callback) => ({- ...callback,- model: undefined,- provider: undefined,- })),- }));--/**- * `taskCompletions[]` blocks are denormalized post-task-summary snapshots built- * by `FlatListBuilder`, each carrying its own `usage` β the same class of- * creator spend data as the top-level `usage` field.- */-const sanitizeVisitorTaskCompletions = (- taskCompletions: AssistantContentBlock[] | undefined,-): AssistantContentBlock[] | undefined =>- taskCompletions?.map(({ usage: _usage, ...rest }) => rest);--/**- * `metadata.usage` / `metadata.cost` are the pre-migration duplicates of the- * (denied) top-level `usage` field β kept on the type only so legacy rows- * written before the dedicated `usage` column still type-check.- * `queryWithWhere` itself falls back to `metadata.usage` for those rows, so- * leaving `metadata` unsanitized would let the exact spend snapshot back in- * through a legacy row's `metadata` blob. Every other `metadata` field is this- * message's own presentational state and passes through untouched.- */-const sanitizeVisitorMetadata = (- metadata: MessageMetadata | null | undefined,-): MessageMetadata | null | undefined => {- if (!metadata) return metadata;- const { usage: _usage, cost: _cost, ...rest } = metadata;- return rest;-};--/**- * Project Work summaries for a share visitor. A visitor run executes as the- * creator, so `userId` / `workspaceId` on every Work are the CREATOR's account- * and workspace β dropped unconditionally, like the message-level `sender`.- * The version spend snapshot is the creator's billing figure and follows the- * `showModelInfo` gate (`stripSpend`).- *- * The identity keys are omitted rather than nulled (`userId` is non-nullable on- * `WorkItem`); no visitor-facing Work surface reads them.- */-const sanitizeVisitorWorks = (- works: WorkSummaryItem[] | undefined,- { stripSpend }: { stripSpend: boolean },-): WorkSummaryItem[] | undefined =>- works?.map((work) => {- const { userId: _userId, workspaceId: _workspaceId, ...rest } = work;- const visible = stripSpend- ? {- ...rest,- event: { ...rest.event, cumulativeCost: null, cumulativeUsage: null },- totalCost: null,- }- : rest;- return visible as WorkSummaryItem;- });--/**- * Strip creator-only fields from a message row before it reaches an- * agent-share visitor. Creator account identity never crosses the share- * boundary; the creator's model/provider/spend choices cross it only when the- * share sets `showModelInfo`, and raw error payloads only when it sets- * `showErrorDetails` ({@link VisitorRedactionOptions}).- *- * Built from {@link VISITOR_MESSAGE_ALLOWED_KEYS} plus explicit handling for- * the fields that need transformation rather than a plain allow/deny.- */-export const toVisitorMessage = (- message: UIChatMessage,- options: VisitorRedactionOptions = {},-): UIChatMessage => {- const stripModelInfo = !options.showModelInfo;-- return {- ...pickAllowedKeys(message),- // `sender` is the CREATOR's account identity β never gated by any config- // flag, since no share setting is about exposing whose account runs the- // agent.- sender: null,- extra: stripModelInfo ? sanitizeVisitorExtra(message.extra) : message.extra,- metadata: stripModelInfo ? sanitizeVisitorMetadata(message.metadata) : message.metadata,- // Unbounded per-tool blobs: a tool runtime controls everything inside- // them, so a fixed field allowlist can't classify their contents β the- // creator-identity key set is recursed out instead.- pluginError: stripModelInfo- ? redactCreatorPrivateBlob(message.pluginError)- : message.pluginError,- pluginState: stripModelInfo- ? redactCreatorPrivateBlob(message.pluginState)- : message.pluginState,- // Projected, not redacted β see `sanitizeVisitorError`.- error: sanitizeVisitorError(message.error, options),- ...(stripModelInfo- ? {- model: undefined,- provider: undefined,- signalCallbacks: sanitizeVisitorSignalCallbacks(message.signalCallbacks),- taskCompletions: sanitizeVisitorTaskCompletions(message.taskCompletions),- taskDetail: sanitizeVisitorTaskDetail(message.taskDetail),- usage: undefined,- }- : {- model: message.model,- provider: message.provider,- signalCallbacks: message.signalCallbacks,- taskCompletions: message.taskCompletions,- taskDetail: message.taskDetail,- usage: message.usage,- }),- // Work summaries reach a visitor only when the query ran under their share- // scope (see `queryForVisitor`), so every item here was registered from- // this visitor's own topic. Creator identity is always dropped; spend- // follows the `showModelInfo` gate β see `sanitizeVisitorWorks`.- works: sanitizeVisitorWorks(message.works, { stripSpend: stripModelInfo }),- // A compacted topic nests raw rows under the group node, and group chat- // nests member messages, so anything less than a full recursive sanitize- // would leave the creator's identity on everything inside it.- ...(message.compressedMessages && {- compressedMessages: message.compressedMessages.map((nested) =>- toVisitorMessage(nested, options),- ),- }),- ...(message.members && {- members: message.members.map((nested) => toVisitorMessage(nested, options)),- }),- // `pinnedMessages` is only ever the narrow group-node projection (see- // `queryMessageGroupNodes` in the Compression branch). Emit it in both- // modes β sanitized when the model snapshot is not shared, otherwise- // untouched.- ...(message.pinnedMessages && {- pinnedMessages: stripModelInfo- ? (sanitizeVisitorGroupSnapshots(- message.pinnedMessages as unknown as VisitorGroupSnapshotProjection[],- ) as unknown as UIChatMessage['pinnedMessages'])- : message.pinnedMessages,- }),- // `children` is polymorphic: a `compareGroup` node carries the same bare- // {id, role, model, provider, content, createdAt} snapshot as- // `pinnedMessages`; an `assistantGroup` node (produced inside- // `compressedMessages` by `FlatListBuilder`) carries full- // `AssistantContentBlock[]` with `usage`, `tools`, `error`, `metadata`,- // `performance`, and possibly nested `council` messages with `sender` β- // so a compareGroup-only narrow sanitize would let all of those through- // for an assistantGroup child. Route by the PARENT `role` and recurse- // assistantGroup children through `toVisitorMessage` itself so the- // allowlist / error projection / usage & metadata stripping / council- // recursion all apply.- ...(message.children && {- children:- message.role === 'compareGroup'- ? stripModelInfo- ? (sanitizeVisitorGroupSnapshots(- message.children as unknown as VisitorGroupSnapshotProjection[],- ) as unknown as UIChatMessage['children'])- : message.children- : ((message.children as unknown as UIChatMessage[]).map((child) =>- toVisitorMessage(child, options),- ) as unknown as UIChatMessage['children']),- }),- // `AssistantContentBlock.council` on a nested assistantGroup child is a- // `Message[]` of the supervisor's broadcast members, each carrying its- // own `sender` / model / usage. `pickAllowedKeys` drops `council`- // outright (fail closed), so re-attach a recursively sanitized copy- // whenever the source carried one.- ...((message as unknown as { council?: unknown }).council !== undefined &&- ({- council: ((message as unknown as { council?: UIChatMessage[] }).council ?? []).map(- (member) => toVisitorMessage(member, options),- ),- } as unknown as Partial<UIChatMessage>)),- } as UIChatMessage;-};--export interface SoftDeletedMessage {- /** Live children that were re-parented away from this message at trash time. */- childIds: string[];- content: string | null;- id: string;- /** Pulled in as a tool companion of a requested message (never a root of its own). */- isCompanion: boolean;- /**- * For a companion: the requested message whose tool call produced it, so the- * caller can file it under the right root. `null` for requested rows.- */- ownerId: string | null;- parentId: string | null;- projectId: string | null;- role: string;- topicId: string | null;-}--export class MessageModel {- private userId: string;- private db: LobeChatDatabase;- private ftsSearchCandidateSource?: FtsSearchCandidateSource;- private workspaceId?: string;- /**- * When true, {@link ownership} (and by extension every creator-scoped- * read/write below) stops ANDing {@link notShareVisitorMessage}. Reserved- * for surfaces that are share-runtime by design (agent-share visitor- * router, share-scoped abuse guards) and for the agent runtime paths that- * persist or clean up a visitor turn under the CREATOR's identity.- * Defaults to false so every ordinary creator-facing caller fails closed.- */- private includeShareVisitor: boolean;-- constructor(- db: LobeChatDatabase,- userId: string,- workspaceId?: string,- ftsSearchCandidateSource?: FtsSearchCandidateSource,- options: MessageModelOptions = {},- ) {- this.userId = userId;- this.db = db;- this.workspaceId = workspaceId;- this.ftsSearchCandidateSource = ftsSearchCandidateSource;- this.includeShareVisitor = options.includeShareVisitor ?? false;- }-- /**- * Workspace/user scope plus the live parent-topic fence, WITHOUT the visitor- * exclusion. Topic-less rows remain valid. Backing store for- * {@link ownership} and the escape hatch for methods that resolve the- * effective visitor gate per-call ({@link deleteMessage},- * {@link deleteMessages}, {@link query} via `allowShareVisitor`, β¦).- */- private workspaceScope = () =>- and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),- or(- isNull(messages.topicId),- inArray(- messages.topicId,- this.db- .select({ id: topics.id })- .from(topics)- .where(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- ),- ),- ),- );-- /**- * Default visitor exclusion applied by {@link ownership} β see- * `notShareVisitorMessage` in `../utils/shareVisitor`. Returns `undefined`- * when the instance was constructed with `includeShareVisitor: true`.- */- private notShareVisitor = () => (this.includeShareVisitor ? undefined : notShareVisitorMessage());-- private ownership = () => and(this.workspaceScope(), this.notShareVisitor());-- /**- * One indexed lookup of a topic's `senderId` in this user/workspace scope- * (`buildWorkspaceWhere` on `topics`). Returned once and reused: every row- * that belongs to a topic shares that topic's visitor/creator identity, so- * once the topic itself has been classified the per-row NOT EXISTS predicate- * from {@link notShareVisitorMessage} is redundant for the rest of the same- * call. Callers pass the resolved verdict downstream (as- * `allowShareVisitor: true` for a verified creator topic) to swap the- * relevant `ownership()` sites over to plain `workspaceScope()`.- *- * Fails closed: returns `'visitor'` when the topic doesn't exist under this- * scope OR carries a non-null `senderId`, so an unauthorized topicId gets- * the same empty result as before.- */- private resolveTopicVisitorScope = async (topicId: string): Promise<'creator' | 'visitor'> => {- const rows = await this.db- .select({ senderId: topics.senderId })- .from(topics)- .where(- and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- eq(topics.id, topicId),- ),- )- .limit(1);- if (rows.length === 0) return 'visitor';- return rows[0].senderId === null ? 'creator' : 'visitor';- };-- /**- * Scope predicate without the recycle-bin filter β restore / purge internals- * only. Keeps the visitor exclusion of {@link ownership} so a creator-facing- * restore or purge can never reach an agent-share visitor row.- */- private trashScope = () =>- and(- buildWorkspaceWhere(- { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },- messages,- ),- this.notShareVisitor(),- );-- private pluginsOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);-- private translatesOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTranslates);-- private ttsOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTTS);-- private agentsToSessionsOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentsToSessions);-- // **************** Query *************** //-- /**- * The newest user message of each given topic, keyed by topic id. Used to- * pre-inject recent same-channel history for IM platforms that can't read- * chat history at runtime (e.g. WeChat). Only `role = 'user'` rows with- * non-empty text are considered.- */- queryLastUserMessageByTopics = async (topicIds: string[]): Promise<Map<string, string>> => {- if (topicIds.length === 0) return new Map();-- const rows = await this.db- .selectDistinctOn([messages.topicId], {- content: messages.content,- topicId: messages.topicId,- })- .from(messages)- .where(- and(- this.ownership(),- inArray(messages.topicId, topicIds),- eq(messages.role, 'user'),- isNotNull(messages.content),- ne(messages.content, ''),- ),- )- .orderBy(messages.topicId, desc(messages.createdAt));-- const result = new Map<string, string>();- for (const row of rows) {- const content = (row.content ?? '').trim();- if (row.topicId && content) result.set(row.topicId, content);- }- return result;- };-- /**- * Query messages by params (high-level API)- *- * This is the main query method that handles common query patterns.- * For custom queries, use `queryWithWhere` directly.- */- query = async (- {- agentId,- before,- current = 0,- includeFileWorks,- pageSize = 1000,- sessionId,- skipWorks,- topicId,- groupId,- threadId,- }: QueryMessageParams = {},- options: {- /**- * Opt IN to agent-share visitor messages. Visitor conversations persist- * under the CREATOR's `userId` (only `topics.senderId` marks them), so- * `this.ownership()` alone lets a creator read a visitor's full transcript- * by passing its `topicId` β bypassing `allowCreatorViewSessions=false`.- * Defaults to false so every creator-facing caller fails closed; only the- * share-scoped read path ({@link MessageModel.queryForVisitor}) sets it.- */- allowShareVisitor?: boolean;- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;- timing?: ModelTimingContext;- /** See {@link QueryMessagesOptions.workAccessScope}. */- workAccessScope?: WorkAccessScope;- } = {},- ) => {- const queryStartedAt = Date.now();- // Effective visitor gate: per-call `allowShareVisitor` OR the instance's- // `includeShareVisitor`. Combined so `queryForVisitor(...)` still works- // on a default-scoped instance (its explicit param overrides), AND a- // share-runtime instance stops needing the param at every call site.- const includeVisitor = options.allowShareVisitor || this.includeShareVisitor;- const timing = options.timing;-- // Topic-scope shortcut: when the caller pins a `topicId` and hasn't opted- // in to visitor rows, resolve the topic's `senderId` ONCE and either fail- // closed (visitor topic) or drop the per-row NOT EXISTS predicate that- // `queryWithWhere` / `queryMessageGroupNodes` would otherwise re-check for- // every message in the topic. Every row inside a topic shares its parent- // topic's visitor/creator identity, so a single indexed topic lookup is- // strictly stronger than the correlated subquery repeated per row.- let topicScopeVerified = false;- if (topicId && !includeVisitor) {- const scope = await this.resolveTopicVisitorScope(topicId);- if (scope === 'visitor') {- logTiming(timing, 'db.message.query:done', {- messageCount: 0,- stageMs: getDurationMs(queryStartedAt),- });- return [];- }- topicScopeVerified = true;- }- // `queryWithWhere` already ANDs `notShareVisitorMessage()` via- // `ownership()`, so the previous per-branch `shareVisitorCondition` in- // the `where` was pure duplication β dropped. When `topicScopeVerified`- // is true the predicate is redundant altogether (the topic has been- // classified once), and we pass that verdict downstream via- // `allowShareVisitor: effectiveIncludeVisitor` so `queryWithWhere` swaps- // its scope from `ownership()` to `workspaceScope()` and skips the- // per-row NOT EXISTS.- const effectiveIncludeVisitor = includeVisitor || topicScopeVerified;- logTiming(timing, 'db.message.query:start', {- current,- hasAgentId: !!agentId,- hasGroupId: !!groupId,- hasSessionId: !!sessionId,- hasThreadId: !!threadId,- hasTopicId: !!topicId,- pageSize,- });-- // Build agent condition (handles legacy sessionId lookup)- let agentCondition: SQL | undefined;- if (agentId) {- agentCondition = await runTimedStage(- timing,- 'db.message.query.buildAgentCondition',- () => this.buildAgentCondition(agentId),- { hasAgentId: true },- );- } else if (sessionId) {- agentCondition = this.matchSession(sessionId);- }-- // For thread queries, we need to fetch complete thread data (parent + thread messages)- if (threadId) {- const threadCondition = await runTimedStage(- timing,- 'db.message.query.buildThreadCondition',- () => this.buildThreadQueryCondition(threadId),- { hasThreadId: true },- );- // A topic thread may contain replies from delegated agents. When the topic is known,- // scope the complete thread to it instead of filtering those replies by the parent agent.- const threadScopeCondition = topicId ? this.matchTopic(topicId) : agentCondition;- const messageItems = await this.queryWithWhere({- allowShareVisitor: effectiveIncludeVisitor,- before,- current,- includeFileWorks,- pageSize,- postProcessUrl: options.postProcessUrl,- skipWorks,- timing,- topicId: topicId ?? undefined,- workAccessScope: options.workAccessScope,- where: and(threadScopeCondition, threadCondition),- });- logTiming(timing, 'db.message.query:done', {- messageCount: messageItems.length,- stageMs: getDurationMs(queryStartedAt),- });- return messageItems;- }-- // For Group Chat queries: filter by groupId only (not agentId)- // In Group Chat, all messages (user, supervisor, workers) should have groupId- // and may have different agentIds, so we only filter by groupId + topicId- if (groupId) {- const whereCondition = and(- eq(messages.groupId, groupId),- this.matchTopic(topicId),- this.matchThread(threadId),- );-- const messageItems = await this.queryWithWhere({- allowShareVisitor: effectiveIncludeVisitor,- before,- current,- includeFileWorks,- pageSize,- postProcessUrl: options.postProcessUrl,- skipWorks,- timing,- topicId: topicId ?? undefined,- workAccessScope: options.workAccessScope,- where: whereCondition,- });- logTiming(timing, 'db.message.query:done', {- messageCount: messageItems.length,- stageMs: getDurationMs(queryStartedAt),- });- return messageItems;- }-- // A concrete topic is the conversation boundary and may legitimately- // contain messages from multiple agents (for example callAgent replies).- // Inbox queries have no topic, so they still require agent/session scope.- const conversationCondition = topicId- ? this.matchTopic(topicId)- : and(agentCondition ?? this.matchSession(sessionId), this.matchTopic(topicId));-- // Standard query with conversation/topic/group filters- const whereCondition = and(- conversationCondition,- this.matchGroup(groupId),- this.matchThread(threadId),- );-- const messageItems = await this.queryWithWhere({- allowShareVisitor: effectiveIncludeVisitor,- before,- current,- includeFileWorks,- pageSize,- postProcessUrl: options.postProcessUrl,- skipWorks,- timing,- topicId: topicId ?? undefined,- where: whereCondition,- workAccessScope: options.workAccessScope,- });- logTiming(timing, 'db.message.query:done', {- messageCount: messageItems.length,- stageMs: getDurationMs(queryStartedAt),- });- return messageItems;- };-- // **************** Agent Share (visitor-scoped) *************** //-- /**- * Visitor-facing twin of {@link query} for agent-share reads.- *- * Share messages persist under the CREATOR's account (see `shareChat.ts`),- * so `query()`'s joined `sender` and the billing/model-snapshot fields- * describe the creator, not the visitor reading them. `redaction` carries the- * share's own `showModelInfo` / `showErrorDetails` switches; omitting it- * strips everything (fail closed).- */- queryForVisitor = async (- params: QueryMessageParams = {},- options: {- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;- redaction?: VisitorRedactionOptions;- timing?: ModelTimingContext;- /**- * The visitor's share scope for Work summaries. Omitting it skips Work- * assembly entirely (fail closed): the ordinary scope would join the- * CREATOR's Works, which must never reach a visitor surface.- */- workAccessScope?: WorkAccessScope;- } = {},- ): Promise<UIChatMessage[]> => {- // The only caller allowed past `query()`'s visitor guard: the topic was- // already resolved and authorized as this visitor's own share topic.- const messageItems = await this.query(- { ...params, skipWorks: params.skipWorks || !options.workAccessScope },- { ...options, allowShareVisitor: true },- );- return messageItems.map((message) => toVisitorMessage(message, options.redaction));- };-- /**- * Exact per-topic turn count for one role, used by `maxTurnsPerTopic`.- *- * MUST NOT reuse {@link MessageModel.count}: its `analyticsConditions()` ANDs- * in `notShareVisitorMessage()`, which excludes every message whose topic has- * a non-null `senderId` β i.e. every agent-share visitor topic. That- * predicate is correct for personal analytics (visitor usage is reported- * separately), but it would make `count()` return 0 forever for a share- * topic, silently disabling the turn cap.- *- * Safe without a visitor/ownership check here: the caller (shareChat router /- * `reserveShareVisitorTurn`) already resolved and authorized the topic, and- * `this.ownership()` matches because share messages carry the creator's- * `userId` (the model is constructed with `share.ownerId`).- */- countByTopic = async ({ role, topicId }: { role: string; topicId: string }): Promise<number> => {- const result = await this.db- .select({ count: count(messages.id) })- .from(messages)- .where(and(this.ownership(), eq(messages.topicId, topicId), eq(messages.role, role)));-- return result[0].count;- };-- /**- * Return a lightweight, ownership-scoped transcript for a topic.- *- * Unlike the conversation query, this intentionally does not infer missing- * session, group, or thread filters as `IS NULL`, and it does not replace raw- * message-group members with synthetic nodes. Consumers such as the CLI need- * the complete persisted transcript and exact database pagination.- */- queryTopicTranscript = async ({- limit,- offset,- topicId,- }: {- limit: number;- offset: number;- topicId: string;- }): Promise<TopicTranscriptResult> => {- // Creator-facing only (CLI / topic transcript router): agent-share visitor- // messages live under the creator's `userId`, so ownership alone would hand- // the creator a visitor's full transcript from a raw topic id.- const where = and(this.ownership(), eq(messages.topicId, topicId), notShareVisitorMessage());-- const [items, totalResult] = await Promise.all([- this.db- .select({- agentId: messages.agentId,- error: messages.error,- metadata: messages.metadata,- model: messages.model,- pluginError: messagePlugins.error,- provider: messages.provider,- reasoning: messages.reasoning,- toolCallId: messagePlugins.toolCallId,- usage: messages.usage,- content: messages.content,- createdAt: messages.createdAt,- id: messages.id,- messageGroupId: messages.messageGroupId,- parentId: messages.parentId,- role: messages.role,- threadId: messages.threadId,- tools: messages.tools,- })- .from(messages)- .leftJoin(messagePlugins, and(eq(messagePlugins.id, messages.id), this.pluginsOwnership()))- .where(where)- .orderBy(asc(messages.createdAt), asc(messages.id))- .limit(limit)- .offset(offset),- this.db- .select({ count: count(messages.id) })- .from(messages)- .where(where),- ]);-- return {- items: items.map(({ tools, usage, ...message }) => ({- ...message,- error: message.error as ChatMessageError | null,- metadata: message.metadata as MessageMetadata | null,- tools: Array.isArray(tools) ? (tools as ChatToolPayload[]) : null,- usage: usage ?? message.metadata?.usage ?? null,- })),- total: totalResult[0]?.count ?? 0,- };- };-- /**- * Lightweight parent/group links for the FULL message tree of a topic,- * INCLUDING messages hidden inside MessageGroups (compression / parallel).- *- * `query` replaces grouped messages with synthetic group nodes that expose- * neither their members' `parentId` nor (for compaction) the group's- * `parentMessageId`, so branch-ancestry can't be reconstructed from `query`- * output alone. This returns the raw `id β parentId` / `messageGroupId` links- * so callers (e.g. server-runtime regenerate pruning) can walk ancestry across- * a compacted range.- */- queryTopicMessageTree = async ({- threadId,- topicId,- }: {- threadId?: string | null;- topicId: string;- }): Promise<{ id: string; messageGroupId: string | null; parentId: string | null }[]> => {- return this.db- .select({- id: messages.id,- messageGroupId: messages.messageGroupId,- parentId: messages.parentId,- })- .from(messages)- .where(and(this.ownership(), this.matchTopic(topicId), this.matchThread(threadId)));- };-- /**- * Query messages with full relations (files, plugins, translations, etc.)- *- * This is the low-level query method that accepts a custom where condition.- * Use this for building custom query scenarios.- *- * Features:- * - Filters out messages that belong to MessageGroups (compression/parallel)- * - Includes MessageGroup nodes (compressedGroup/compareGroup) in the result- * - compressedGroup nodes include pinnedMessages array (favorite=true messages)- * - compareGroup nodes include children array (parallel messages)- *- * @param options - Query options including where condition and pagination- * @returns Messages with all related data, including MessageGroup nodes- */- queryWithWhere = async (options: QueryMessagesOptions = {}): Promise<UIChatMessage[]> => {- const {- where,- before,- current = 0,- includeFileWorks,- pageSize = 1000,- postProcessUrl,- skipWorks,- topicId,- timing,- allowShareVisitor,- workAccessScope,- groupNodeWindow,- } = options;- const totalStartedAt = Date.now();- const offset = current * pageSize;- // See {@link QueryMessagesOptions.allowShareVisitor}. Combined with the- // instance's `includeShareVisitor` so either widens the scope.- const scope =- allowShareVisitor || this.includeShareVisitor ? this.workspaceScope() : this.ownership();-- // Round-cursor paging: only rows strictly older than the `(createdAt, id)`- // tuple. The id tie-break mirrors the sort order below, so rows sharing a- // createdAt with the cursor are neither skipped nor duplicated.- const beforeCondition = before- ? or(- lt(messages.createdAt, before.createdAt),- and(eq(messages.createdAt, before.createdAt), lt(messages.id, before.id)),- )- : undefined;-- // 1. get basic messages with joins, excluding messages that belong to MessageGroups- const result = await runTimedStage(- timing,- 'db.message.queryWithWhere.baseSelect',- () =>- this.db- .select({- id: messages.id,- role: messages.role,- content: messages.content,- editorData: messages.editorData,- reasoning: messages.reasoning,- search: messages.search,- metadata: messages.metadata,- usage: messages.usage,- error: messages.error,-- model: messages.model,- provider: messages.provider,-- createdAt: messages.createdAt,- updatedAt: messages.updatedAt,-- sessionId: messages.sessionId,- topicId: messages.topicId,- parentId: messages.parentId,- threadId: messages.threadId,-- // Group chat fields- groupId: messages.groupId,- agentId: messages.agentId,- targetId: messages.targetId,-- sender: {- // `id` MUST be the first selected field: drizzle decides whether a- // left-joined nested selection is null from its first column, so- // leading with a nullable column (avatar) collapsed every- // avatar-less sender to `sender: null`.- id: users.id,- avatar: users.avatar,- fullName: users.fullName,- username: users.username,- },-- tools: messages.tools,- tool_call_id: messagePlugins.toolCallId,-- plugin: {- apiName: messagePlugins.apiName,- arguments: messagePlugins.arguments,- identifier: messagePlugins.identifier,- type: messagePlugins.type,- },- pluginError: messagePlugins.error,- pluginIntervention: messagePlugins.intervention,- pluginState: messagePlugins.state,-- translate: {- content: messageTranslates.content,- from: messageTranslates.from,- to: messageTranslates.to,- },-- ttsId: messageTTS.id,- ttsContentMd5: messageTTS.contentMd5,- ttsFile: messageTTS.fileId,- ttsVoice: messageTTS.voice,- })- .from(messages)- .where(- and(- scope,- // Filter out messages that belong to MessageGroups- isNull(messages.messageGroupId),- where,- beforeCondition,- ),- )- .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))- .leftJoin(messageTranslates, eq(messageTranslates.id, messages.id))- .leftJoin(messageTTS, eq(messageTTS.id, messages.id))- .leftJoin(users, eq(users.id, messages.userId))- // Page from the NEWEST messages, not the oldest. `desc` + limit/offset- // fetches the most recent `pageSize` rows, so a topic with more than- // `pageSize` mainline messages keeps its latest turns (including the- // final answer) instead of silently dropping them β the previous- // `asc + limit` truncated exactly the newest batch, which is the worst- // possible slice for a chat transcript. The page is reversed back to- // ascending immediately below, so every downstream consumer is- // unaffected; only *which* rows are fetched changed. See.- .orderBy(desc(messages.createdAt), desc(messages.id))- .limit(pageSize)- .offset(offset),- { current, pageSize },- );- logTiming(timing, 'db.message.queryWithWhere.baseSelect:rows', { rowCount: result.length });-- // Restore ascending (createdAt, id) order so downstream assembly β the- // MessageGroup time window, work-summary anchoring, and the final merge sort β- // behaves exactly as before the newest-first fetch above.- result.reverse();-- // When the newest page is truncated (it filled `pageSize`), its oldest rows- // may sit mid-round. The renderer roots a slice at a single parent, so a slice- // cut inside a round can strand sibling chains and drop them from the screen.- // Align the lower boundary to a round start β a mainline `user` message β so- // the slice is one contiguous chain. Never trim to empty: an oversized single- // round with no user message in view is kept whole (the proper fix for those- // is lazy step loading). Thread queries pass no `topicId` and are untouched.- //- // Scope: this serves the single "most recent page" load (`current === 0`)- // and the round-cursor `before` pages that walk older history β the only- // shapes the chat read path requests; `current`/`pageSize` offset paging is- // dead code here (the very premise of). The trim is deliberately NOT- // offset-exact: rows dropped from one page reappear at the TOP of the next- // `before` page (its cursor is the trimmed page's oldest kept row), so the- // round-cursor walk loses nothing by construction.- if (topicId && (current === 0 || before) && result.length >= pageSize) {- const firstRoundStart = result.findIndex((message) => message.role === 'user');- if (firstRoundStart > 0) result.splice(0, firstRoundStart);- }-- const messageIds = result.map((message) => message.id as string);-- const messageGroupNodesPromise = this.queryMessageGroupNodesForPage({- allowShareVisitor: allowShareVisitor || this.includeShareVisitor,- current,- hasBeforeCursor: !!before,- postProcessUrl,- result,- timing,- topicId,- window: groupNodeWindow,- });-- const taskMessageIds = result- .filter((message) => message.role === 'task')- .map((message) => {- return message.id as string;- });-- const [- messageGroupNodes,- { documentsMap, relatedFileList },- chunksList,- messageQueriesList,- threadData,- worksByMessageId,- ] = await Promise.all([- messageGroupNodesPromise,- this.queryMessageFileRelations(messageIds, postProcessUrl, timing),- this.queryMessageChunkRelations(messageIds, timing),- this.queryMessageQueryRelations(messageIds, timing),- this.queryMessageThreadRelations(taskMessageIds, timing),- skipWorks- ? ({} as Record<string, WorkSummaryItem[]>)- : this.queryMessageWorkSummaries(result, includeFileWorks, timing, workAccessScope),- ]);-- if (messageIds.length === 0 && messageGroupNodes.length === 0) {- logTiming(timing, 'db.message.queryWithWhere:done', {- messageGroupCount: 0,- rowCount: 0,- stageMs: getDurationMs(totalStartedAt),- });- return [];- }-- const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));- const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));- const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));- const fileList = relatedFileList.filter(- (i) =>- !(i.fileType || '').startsWith('image') &&- !(i.fileType || '').startsWith('video') &&- !(i.fileType || '').startsWith('audio'),- );-- const threadMap = this.createThreadMap(threadData);-- // 6. Transform regular messages- const transformedMessages = await runTimedStage(- timing,- 'db.message.queryWithWhere.transform',- () =>- result.map(- ({- model,- provider,- translate,- ttsId,- ttsFile,- ttsContentMd5,- ttsVoice,- sender,- ...item- }) => {- const messageQuery = messageQueriesList.find(- (relation) => relation.messageId === item.id,- );- return {- ...item,- // LEFT JOIN β users row is null only when the sender account was- // deleted (rare, since `messages.user_id` cascades on user delete).- // Collapse a null-id sender to `null` so the client can rely on- // `sender?.id` as the presence check.- sender: sender?.id ? sender : null,- chunksList: chunksList- .filter((relation) => relation.messageId === item.id)- .map((c) => ({- ...c,- similarity: c.similarity === null ? undefined : Number(c.similarity),- })),-- extra: {- model,- provider,- translate,- tts: ttsId- ? {- contentMd5: ttsContentMd5,- file: ttsFile,- voice: ttsVoice,- }- : undefined,- },- fileList: fileList- .filter((relation) => relation.messageId === item.id)-- .map<ChatFileItem>(({ id, url, size, fileType, name }) =>- // Nulled by the visibility guard: the viewer lost access to- // the referenced file. Emit a tombstone (id only) so the UI- // renders a no-access placeholder.- name === null- ? { fileType: '', id, inaccessible: true, name: '', size: 0, url: '' }- : {- content: documentsMap[id]?.content,- originalCharCount: documentsMap[id]?.originalCharCount,- fileType: fileType!,- id,- name,- size: size!,- url,- },- ),- imageList: imageList- .filter((relation) => relation.messageId === item.id)- .map(({ fileType, id, metadata, name, url }) =>- createChatImageItem({ fileType, id, metadata, name: name!, url }),- ),-- model,-- provider,- ragQuery: messageQuery?.rewriteQuery,- ragQueryId: messageQuery?.id,- ragRawQuery: messageQuery?.userQuery,- // Add taskDetail for task messages- taskDetail: item.role === 'task' ? threadMap.get(item.id as string) : undefined,- // Prefer the dedicated `usage` column, falling back to legacy- // `metadata.usage` for rows written before the migration.- usage: item.usage ?? (item.metadata as { usage?: ModelUsage } | null)?.usage,- videoList: videoList- .filter((relation) => relation.messageId === item.id)-- .map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),- // Work summaries for this message's root operation, resolved- // server-side (attached only to the round's anchor message).- works: worksByMessageId[item.id as string],- audioList: audioList- .filter((relation) => relation.messageId === item.id)- .map<ChatAudioItem>(materializeChatAudioItem),- } as unknown as UIChatMessage;- },- ),- {- chunkCount: chunksList.length,- fileCount: relatedFileList.length,- messageQueryCount: messageQueriesList.length,- rowCount: result.length,- },- );-- // 7. Merge regular messages with MessageGroup nodes and sort by createdAt- const allItems = [...transformedMessages, ...messageGroupNodes];- allItems.sort((a, b) => {- const aTime = new Date(a.createdAt).getTime();- const bTime = new Date(b.createdAt).getTime();- return aTime - bTime;- });-- logTiming(timing, 'db.message.queryWithWhere:done', {- messageGroupCount: messageGroupNodes.length,- resultCount: allItems.length,- rowCount: result.length,- stageMs: getDurationMs(totalStartedAt),- });-- return allItems;- };-- /**- * Cursor-paginated read of a topic's mainline conversation, aligned to round- * boundaries (a mainline `user` message starts a round). Built for callers that- * only DISPLAY history and never resend it to the model β server-runtime- * (gateway) and local hetero agents β where eagerly loading the whole transcript- * is wasteful on long topics. Legacy client mode keeps using `query` (full- * fetch) because it resends the entire session each turn.- *- * Initial load (`cursor` omitted) returns the newest `roundLimit` rounds, or- * fewer if `countBudget` is reached first, but the current round is always- * whole. Pass the returned `nextCursor` to load the previous rounds (scroll up).- * Unlike offset paging, cursors land on round boundaries, so consecutive pages- * are gap-free and never split a round.- */- queryTopicMessagesByCursor = async (- {- countBudget = DEFAULT_ROUND_COUNT_BUDGET,- cursor,- groupId,- includeFileWorks,- roundLimit = DEFAULT_ROUND_LIMIT,- skipWorks,- topicId,- }: QueryTopicByCursorParams,- options: {- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;- timing?: ModelTimingContext;- } = {},- ): Promise<TopicMessagesByCursorResult> => {- // Same visitor gate as `query`: a creator's read of an agent-share visitor- // topic fails closed, and a verified creator topic skips the per-row check.- if ((await this.resolveTopicVisitorScope(topicId)) === 'visitor') {- return { hasMore: false, messages: [], nextCursor: null };- }-- // Mainline = this topic (and its chat group, if any), not in a thread. Like- // the standard `query`, a concrete topic is the conversation boundary: it is- // NOT narrowed by agent/session, because a topic may legitimately hold rows- // from several agents (e.g. `callAgent` / delegated replies).- const mainlineWhere = and(- this.matchTopic(topicId),- this.matchGroup(groupId),- this.matchThread(undefined),- );-- const { lowerBound, hasMore } = await this.resolveRoundWindow({- countBudget,- cursor,- mainlineWhere,- roundLimit,- });-- // MessageGroup nodes (compression / comparison) are partitioned across pages- // by the same `[lowerBound, cursor)` window as mainline rows, so each group is- // emitted exactly once over a full backward walk. The oldest page (`!hasMore`)- // leaves the lower side open so groups dated before the first remaining- // mainline row β including a topic whose whole history was compressed β stay- // reachable instead of vanishing.- const groupNodeWindow: MessageGroupNodeWindow = {- before: cursor?.createdAt ?? null,- from: hasMore && lowerBound ? lowerBound.createdAt : null,- };-- // No lower bound means no mainline rows remain β either the topic has none- // (e.g. compression moved every message into a group) or nothing older than- // the cursor is left. The page is then group-only: fetch no mainline rows (an- // unbounded `where` would wrongly reload the entire topic) but still assemble- // the remaining group nodes.- //- // Otherwise bound the window on BOTH sides: at/after the resolved round start,- // and β when paging older β strictly before the cursor. Without the upper- // bound the window would also re-include every newer round already loaded.- const where = lowerBound- ? and(- mainlineWhere,- this.messageAtOrAfter(lowerBound),- cursor ? this.messageStrictlyBefore(cursor) : undefined,- )- : sql`false`;-- const messages = await this.queryWithWhere({- allowShareVisitor: true,- current: 0,- includeFileWorks,- pageSize: CURSOR_PAGE_CEILING,- postProcessUrl: options.postProcessUrl,- skipWorks,- timing: options.timing,- topicId,- where,- // Only assemble group nodes within this page's window (not the whole topic),- // so scroll-up pages don't repeat groups or eagerly load compressed history.- groupNodeWindow,- });-- // `lowerBound.createdAt` is already the lossless microsecond cursor string.- return { hasMore, messages, nextCursor: hasMore && lowerBound ? lowerBound : null };- };-- /**- * Resolve the round window for a cursor page: walk mainline rows newest-first- * and stop at the `roundLimit`-th round boundary (a `user` message) or the- * `countBudget` safety cap, whichever comes first. Returns the lower bound (the- * oldest included round's start) and whether older rounds remain.- */- private resolveRoundWindow = async ({- countBudget,- cursor,- mainlineWhere,- roundLimit,- }: {- countBudget: number;- cursor?: MessageRoundCursor | null;- mainlineWhere: SQL | undefined;- roundLimit: number;- }): Promise<{ hasMore: boolean; lowerBound: { createdAt: string; id: string } | null }> => {- const olderThanCursor = cursor ? this.messageStrictlyBefore(cursor) : undefined;-- const rows = (await this.db- .select({- // Microsecond-precision UTC string. `createdAt` is a timestamptz whose- // now() default can carry microseconds, but a JS Date keeps only- // milliseconds β a Date-derived cursor would round sub-millisecond- // boundaries and let rows leak between adjacent pages. Carry the lossless- // value in the cursor and compare it back with a ::timestamptz cast.- createdAtIso: sql<string>`to_char(${messages.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,- id: messages.id,- role: messages.role,- })- .from(messages)- .where(and(this.ownership(), isNull(messages.messageGroupId), mainlineWhere, olderThanCursor))- .orderBy(desc(messages.createdAt), desc(messages.id))- .limit(countBudget + 1)) as { createdAtIso: string; id: string; role: string }[];-- if (rows.length === 0) return { hasMore: false, lowerBound: null };-- let rounds = 0;- let boundaryIndex = -1;- for (let i = 0; i < rows.length; i += 1) {- if (rows[i].role === 'user') {- rounds += 1;- boundaryIndex = i;- if (rounds >= roundLimit) break;- }- // Safety cap: once a full budget has been walked and at least one whole- // round is captured, stop at the last boundary instead of scanning further.- if (i + 1 >= countBudget && rounds >= 1) break;- }-- // No `user` turn in the visible window β an oversized newest round, or a tail- // with no user turn. Fall back to the oldest fetched row; that slice is a- // partial round the renderer roots as an orphan chain. Lazy step loading is- // the proper fix (a later stage).- if (boundaryIndex === -1) boundaryIndex = rows.length - 1;-- const boundaryRow = rows[boundaryIndex];- const hasMore = boundaryIndex < rows.length - 1 || rows.length > countBudget;-- return { hasMore, lowerBound: { createdAt: boundaryRow.createdAtIso, id: boundaryRow.id } };- };-- /**- * `(createdAt, id)` strictly before the cursor β the "older than" half-open- * bound. Compares against the cursor's lossless microsecond string cast to- * `timestamptz`, so sub-millisecond boundaries stay exact.- */- private messageStrictlyBefore = (cursor: MessageRoundCursor) =>- or(- sql`${messages.createdAt} < ${cursor.createdAt}::timestamptz`,- and(- sql`${messages.createdAt} = ${cursor.createdAt}::timestamptz`,- lt(messages.id, cursor.id),- ),- );-- /** `(createdAt, id)` at or after the lower bound β the inclusive window start. */- private messageAtOrAfter = (bound: { createdAt: string; id: string }) =>- or(- sql`${messages.createdAt} > ${bound.createdAt}::timestamptz`,- and(sql`${messages.createdAt} = ${bound.createdAt}::timestamptz`, gte(messages.id, bound.id)),- );-- private queryMessageGroupNodesForPage = async ({- allowShareVisitor,- current,- hasBeforeCursor,- postProcessUrl,- result,- timing,- topicId,- window,- }: {- /**- * Effective visitor gate resolved by the caller (per-call- * `allowShareVisitor` OR the instance's `includeShareVisitor`). Threaded- * through so the underlying `messageGroups` where-clause fails closed on- * a creator's default read of a visitor topic β otherwise a bare- * workspace/topicId filter would still surface the group's synthetic- * `compressedGroup`/`compareGroup` nodes (with content summaries) even- * though the row query returned nothing.- */- allowShareVisitor?: boolean;- current: number;- /**- * The page was fetched with a round-cursor (`before`): scope group nodes to- * the page's time window instead of the whole topic β page 0 already- * returned every group node, so an unwindowed fetch here would only- * duplicate them.- */- hasBeforeCursor?: boolean;- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;- result: { createdAt: Date }[];- timing?: ModelTimingContext;- topicId?: string;- /** Explicit group window (cursor pagination); overrides the row-derived one. */- window?: MessageGroupNodeWindow;- }): Promise<UIChatMessage[]> => {- if (!topicId) return [];-- if (window) {- return runTimedStage(- timing,- 'db.message.queryWithWhere.messageGroups',- () =>- this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {- allowShareVisitor,- window,- }),- { current, hasMessages: result.length > 0, topicId },- );- }-- if (result.length === 0) {- if (current !== 0 || hasBeforeCursor) return [];-- return runTimedStage(- timing,- 'db.message.queryWithWhere.messageGroups',- () =>- this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {- allowShareVisitor,- }),- { current, hasMessages: false, topicId },- );- }-- if (current === 0 && !hasBeforeCursor) {- return runTimedStage(- timing,- 'db.message.queryWithWhere.messageGroups',- () =>- this.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {- allowShareVisitor,- }),- { current, hasMessages: true, topicId },- );- }-- const firstMessageTime = result[0].createdAt;- const lastMessageTime = result.at(-1)!.createdAt;-- return runTimedStage(- timing,- 'db.message.queryWithWhere.messageGroups',- () =>- this.queryMessageGroupNodes(- topicId,- {- endTime: lastMessageTime,- startTime: firstMessageTime,- },- postProcessUrl,- timing,- { allowShareVisitor },- ),- { current, hasMessages: true, topicId },- );- };-- private queryMessageFileRelations = async (- messageIds: string[],- postProcessUrl: QueryMessagesOptions['postProcessUrl'],- timing?: ModelTimingContext,- ): Promise<MessageFileRelations> => {- if (messageIds.length === 0) return { documentsMap: {}, relatedFileList: [] };-- const rawRelatedFileList = await runTimedStage(- timing,- 'db.message.queryWithWhere.relatedFiles.select',- () =>- this.db- .select({- fileType: files.fileType,- id: messagesFiles.fileId,- messageId: messagesFiles.messageId,- metadata: files.metadata,- name: files.name,- size: files.size,- url: files.url,- })- .from(messagesFiles)- // Guard the referenced file, not just the relation: in a shared- // conversation (chat group / workspace task) the message is visible- // to every member, but a file its owner switched back to private- // must degrade to a tombstone (id only) instead of leaking- // name/size/url. Same anti-leak join pattern as the agent knowledge- // reads in agent.ts.- .leftJoin(- files,- and(- eq(files.id, messagesFiles.fileId),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),- ),- )- .where(inArray(messagesFiles.messageId, messageIds)),- { messageCount: messageIds.length },- );- logTiming(timing, 'db.message.queryWithWhere.relatedFiles.select:rows', {- rowCount: rawRelatedFileList.length,- });-- const relatedFileList = await runTimedStage(- timing,- 'db.message.queryWithWhere.relatedFiles.postProcess',- () =>- Promise.all(- rawRelatedFileList.map(async (file) => {- // Tombstoned by the visibility guard above β nothing to presign.- if (file.name === null) return { ...file, url: '' };- return {- ...file,- url: postProcessUrl- ? await postProcessUrl(- file.url,- file as unknown as { fileType: string; id?: string | null },- )- : (file.url as string),- };- }),- ),- { fileCount: rawRelatedFileList.length },- );-- // Exclude tombstoned files β their parsed document content must not leak- // through the unguarded documents join below.- const fileIds = relatedFileList- .filter((file) => file.name !== null)- .map((file) => file.id)- .filter(Boolean);-- if (fileIds.length === 0) return { documentsMap: {}, relatedFileList };-- const documentsList = await runTimedStage(- timing,- 'db.message.queryWithWhere.documents.select',- () =>- this.db- .select(fileDocumentColumns)- .from(documents)- .where(and(inArray(documents.fileId, fileIds), notFileBackedPlaceholder()))- .orderBy(...fileDocumentsOrder),- { fileCount: fileIds.length },- );-- const documentsMap = toFileDocumentsMap(documentsList);-- return { documentsMap, relatedFileList };- };-- private queryMessageChunkRelations = async (- messageIds: string[],- timing?: ModelTimingContext,- ): Promise<MessageChunkRelation[]> => {- if (messageIds.length === 0) return [];-- const chunksList = await runTimedStage(- timing,- 'db.message.queryWithWhere.chunks.select',- () =>- this.db- .select({- fileId: files.id,- fileType: files.fileType,- fileUrl: files.url,- filename: files.name,- id: chunks.id,- messageId: messageQueryChunks.messageId,- similarity: messageQueryChunks.similarity,- text: chunks.text,- })- .from(messageQueryChunks)- .leftJoin(chunks, eq(chunks.id, messageQueryChunks.chunkId))- .leftJoin(fileChunks, eq(fileChunks.chunkId, chunks.id))- // Guard the referenced file like queryMessageFileRelations: in a- // shared conversation, RAG reference chunks of a file its owner- // switched back to private must not leak filename/url/text to other- // members. The inner join drops those chunk rows entirely.- .innerJoin(- files,- and(- eq(fileChunks.fileId, files.id),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),- ),- )- .where(inArray(messageQueryChunks.messageId, messageIds)),- { messageCount: messageIds.length },- );- logTiming(timing, 'db.message.queryWithWhere.chunks.select:rows', {- rowCount: chunksList.length,- });-- return chunksList;- };-- /**- * Resolve Work summaries for a page of messages and key them by anchor- * message id β the LAST message (rows are createdAt-asc, so last occurrence)- * carrying each `metadata.work.rootOperationId`. Works ride the message-list- * payload so the in-message Works chips and the sidebar summary read from one- * source instead of a dedicated work-summary fetch. Attaching only to the- * round's last message (not every row sharing the operation) keeps the- * payload flat β the client re-keys by `rootOperationId`, so which row- * physically carries it doesn't matter.- */- private queryMessageWorkSummaries = async (- rows: { id: unknown; metadata: unknown }[],- includeFileWorks?: boolean,- timing?: ModelTimingContext,- workAccessScope?: WorkAccessScope,- ): Promise<Record<string, WorkSummaryItem[]>> => {- const anchorByRootId = new Map<string, string>();- for (const row of rows) {- const rootOperationId = getMessageWorkRootId(row.metadata);- if (rootOperationId) anchorByRootId.set(rootOperationId, row.id as string);- }- if (anchorByRootId.size === 0) return {};-- const summaryMap = await runTimedStage(- timing,- 'db.message.queryWithWhere.workSummaries',- () =>- new WorkModel(- this.db,- this.userId,- this.workspaceId,- workAccessScope,- ).listSummariesByRootOperations({- includeFileWorks,- rootOperationIds: Array.from(anchorByRootId.keys()),- }),- { rootOperationCount: anchorByRootId.size },- );-- const worksByMessageId: Record<string, WorkSummaryItem[]> = {};- for (const [rootOperationId, messageId] of anchorByRootId) {- const works = summaryMap[rootOperationId];- if (works && works.length > 0) worksByMessageId[messageId] = works;- }- logTiming(timing, 'db.message.queryWithWhere.workSummaries:rows', {- messageCount: Object.keys(worksByMessageId).length,- });- return worksByMessageId;- };-- private queryMessageQueryRelations = async (- messageIds: string[],- timing?: ModelTimingContext,- ): Promise<MessageQueryRelation[]> => {- if (messageIds.length === 0) return [];-- const messageQueriesList = await runTimedStage(- timing,- 'db.message.queryWithWhere.messageQueries.select',- () =>- this.db- .select({- id: messageQueries.id,- messageId: messageQueries.messageId,- rewriteQuery: messageQueries.rewriteQuery,- userQuery: messageQueries.userQuery,- })- .from(messageQueries)- .where(inArray(messageQueries.messageId, messageIds)),- { messageCount: messageIds.length },- );- logTiming(timing, 'db.message.queryWithWhere.messageQueries.select:rows', {- rowCount: messageQueriesList.length,- });-- return messageQueriesList;- };-- private queryMessageThreadRelations = async (- taskMessageIds: string[],- timing?: ModelTimingContext,- ): Promise<MessageThreadRelation[]> => {- if (taskMessageIds.length === 0) return [];-- return runTimedStage(- timing,- 'db.message.queryWithWhere.taskThreads.select',- () =>- this.db- .select({- metadata: threads.metadata,- sourceMessageId: threads.sourceMessageId,- status: threads.status,- threadId: threads.id,- title: threads.title,- })- .from(threads)- .where(- and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),- inArray(threads.sourceMessageId, taskMessageIds),- ),- ),- { taskMessageCount: taskMessageIds.length },- );- };-- private createThreadMap = (threadData: MessageThreadRelation[]) =>- new Map<string, TaskDetail>(- threadData.map((thread) => {- const metadata = thread.metadata as Record<string, unknown> | null;- return [- thread.sourceMessageId!,- {- clientMode: metadata?.clientMode as boolean | undefined,- duration: metadata?.duration as number | undefined,- status: thread.status as ThreadStatus,- threadId: thread.threadId,- title: thread.title ?? undefined,- totalCost: metadata?.totalCost as number | undefined,- totalMessages: metadata?.totalMessages as number | undefined,- totalTokens: metadata?.totalTokens as number | undefined,- totalToolCalls: metadata?.totalToolCalls as number | undefined,- },- ];- }),- );-- /**- * Query messages by their IDs with full relations- *- * This is useful for getting full message data when you already have the IDs.- * It reuses the same transformation logic as queryWithWhere.- *- * @param messageIds - Array of message IDs to query- * @param options - Query options (postProcessUrl for file URL transformation)- * @returns Messages with all related data (files, plugins, translations, etc.)- */- queryByIds = async (- messageIds: string[],- options: {- /**- * Opt IN to agent-share visitor rows. Reserved for internal callers- * (`queryMessageGroupNodes`) that already resolved and authorized the- * parent topic via {@link resolveTopicVisitorScope}; every row shares- * that topic's visitor/creator identity, so the per-row NOT EXISTS- * predicate baked into `this.ownership()` is redundant once the topic- * itself has been classified. External callers must leave this false.- */- allowShareVisitor?: boolean;- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>;- } = {},- ): Promise<UIChatMessage[]> => {- if (messageIds.length === 0) return [];-- const { postProcessUrl } = options;- const scope =- options.allowShareVisitor || this.includeShareVisitor- ? this.workspaceScope()- : this.ownership();-- // 1. Query messages with joins- const result = await this.db- .select({- id: messages.id,- role: messages.role,- content: messages.content,- editorData: messages.editorData,- reasoning: messages.reasoning,- search: messages.search,- metadata: messages.metadata,- usage: messages.usage,- error: messages.error,-- model: messages.model,- provider: messages.provider,-- createdAt: messages.createdAt,- updatedAt: messages.updatedAt,-- sessionId: messages.sessionId,- topicId: messages.topicId,- parentId: messages.parentId,- threadId: messages.threadId,-- // Group chat fields- groupId: messages.groupId,- agentId: messages.agentId,- targetId: messages.targetId,-- sender: {- // `id` MUST be the first selected field β see queryWithWhere's sender- // selection for why (drizzle left-join nested-object nullification).- id: users.id,- avatar: users.avatar,- fullName: users.fullName,- username: users.username,- },-- tools: messages.tools,- tool_call_id: messagePlugins.toolCallId,-- plugin: {- apiName: messagePlugins.apiName,- arguments: messagePlugins.arguments,- identifier: messagePlugins.identifier,- type: messagePlugins.type,- },- pluginError: messagePlugins.error,- pluginIntervention: messagePlugins.intervention,- pluginState: messagePlugins.state,-- translate: {- content: messageTranslates.content,- from: messageTranslates.from,- to: messageTranslates.to,- },-- ttsId: messageTTS.id,- ttsContentMd5: messageTTS.contentMd5,- ttsFile: messageTTS.fileId,- ttsVoice: messageTTS.voice,- })- .from(messages)- .where(and(scope, inArray(messages.id, messageIds)))- .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))- .leftJoin(messageTranslates, eq(messageTranslates.id, messages.id))- .leftJoin(messageTTS, eq(messageTTS.id, messages.id))- .leftJoin(users, eq(users.id, messages.userId))- .orderBy(asc(messages.createdAt));-- if (result.length === 0) return [];-- // 2. Run parallel queries for better performance- const taskMessageIds = result.filter((m) => m.role === 'task').map((m) => m.id as string);-- const [rawRelatedFileList, chunksList, messageQueriesList, threadData] = await Promise.all([- // 2a. Get related files- this.db- .select({- fileType: files.fileType,- id: messagesFiles.fileId,- messageId: messagesFiles.messageId,- metadata: files.metadata,- name: files.name,- size: files.size,- url: files.url,- })- .from(messagesFiles)- // Same anti-leak guard as queryMessageFileRelations: tombstone files- // the viewer lost access to instead of leaking name/size/url.- .leftJoin(- files,- and(- eq(files.id, messagesFiles.fileId),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),- ),- )- .where(inArray(messagesFiles.messageId, messageIds)),-- // 2b. Get related file chunks (visibility-guarded like queryWithWhere)- this.queryMessageChunkRelations(messageIds),-- // 2c. Get related message queries (RAG)- this.db- .select({- id: messageQueries.id,- messageId: messageQueries.messageId,- rewriteQuery: messageQueries.rewriteQuery,- userQuery: messageQueries.userQuery,- })- .from(messageQueries)- .where(inArray(messageQueries.messageId, messageIds)),-- // 2d. Get thread info for task messages- taskMessageIds.length > 0- ? this.db- .select({- metadata: threads.metadata,- sourceMessageId: threads.sourceMessageId,- status: threads.status,- threadId: threads.id,- title: threads.title,- })- .from(threads)- .where(- and(- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- threads,- ),- inArray(threads.sourceMessageId, taskMessageIds),- ),- )- : Promise.resolve([]),- ]);-- // 3. Process file results- const relatedFileList = await Promise.all(- rawRelatedFileList.map(async (file) => {- // Tombstoned by the visibility guard above β nothing to presign.- if (file.name === null) return { ...file, url: '' };- return {- ...file,- url: postProcessUrl- ? await postProcessUrl(- file.url,- file as unknown as { fileType: string; id?: string | null },- )- : (file.url as string),- };- }),- );-- // Get associated document content. Exclude tombstoned files β their parsed- // document content must not leak through the unguarded documents join.- const fileIds = relatedFileList- .filter((file) => file.name !== null)- .map((file) => file.id)- .filter(Boolean);-- let documentsMap: FileDocumentsMap = {};-- if (fileIds.length > 0) {- const documentsList = await this.db- .select(fileDocumentColumns)- .from(documents)- .where(and(inArray(documents.fileId, fileIds), notFileBackedPlaceholder()))- .orderBy(...fileDocumentsOrder);-- documentsMap = toFileDocumentsMap(documentsList);- }-- const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));- const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));- const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));- const fileList = relatedFileList.filter(- (i) =>- !(i.fileType || '').startsWith('image') &&- !(i.fileType || '').startsWith('video') &&- !(i.fileType || '').startsWith('audio'),- );-- // 4. Build thread map- const threadMap = new Map(- threadData.map((t) => {- const metadata = t.metadata as Record<string, unknown> | null;- return [- t.sourceMessageId!,- {- clientMode: metadata?.clientMode as boolean | undefined,- duration: metadata?.duration as number | undefined,- status: t.status as ThreadStatus,- threadId: t.threadId,- title: t.title ?? undefined,- totalCost: metadata?.totalCost as number | undefined,- totalMessages: metadata?.totalMessages as number | undefined,- totalTokens: metadata?.totalTokens as number | undefined,- totalToolCalls: metadata?.totalToolCalls as number | undefined,- },- ];- }),- );-- // 6. Transform messages to UIChatMessage format- return result.map(- ({- model,- provider,- translate,- ttsId,- ttsFile,- ttsContentMd5,- ttsVoice,- sender,- ...item- }) => {- const messageQuery = messageQueriesList.find((relation) => relation.messageId === item.id);- return {- ...item,- // Same presence contract as queryWithWhere: collapse a null-id sender- // (deleted account) to `null` so clients can rely on `sender?.id`.- sender: sender?.id ? sender : null,- chunksList: chunksList- .filter((relation) => relation.messageId === item.id)- .map((c) => ({- ...c,- similarity: c.similarity === null ? undefined : Number(c.similarity),- })),-- extra: {- model,- provider,- translate,- tts: ttsId- ? {- contentMd5: ttsContentMd5,- file: ttsFile,- voice: ttsVoice,- }- : undefined,- },- fileList: fileList- .filter((relation) => relation.messageId === item.id)- .map<ChatFileItem>(({ id, url, size, fileType, name }) =>- // Nulled by the visibility guard: the viewer lost access to the- // referenced file. Emit a tombstone (id only) so the UI renders- // a no-access placeholder.- name === null- ? { fileType: '', id, inaccessible: true, name: '', size: 0, url: '' }- : {- content: documentsMap[id]?.content,- originalCharCount: documentsMap[id]?.originalCharCount,- fileType: fileType!,- id,- name,- size: size!,- url,- },- ),- imageList: imageList- .filter((relation) => relation.messageId === item.id)- .map(({ fileType, id, metadata, name, url }) =>- createChatImageItem({ fileType, id, metadata, name: name!, url }),- ),-- model,-- provider,- ragQuery: messageQuery?.rewriteQuery,- ragQueryId: messageQuery?.id,- ragRawQuery: messageQuery?.userQuery,- // Add taskDetail for task messages- taskDetail: item.role === 'task' ? threadMap.get(item.id as string) : undefined,- // Prefer the dedicated `usage` column, falling back to legacy- // `metadata.usage` for rows written before the migration.- usage: item.usage ?? (item.metadata as { usage?: ModelUsage } | null)?.usage,- videoList: videoList- .filter((relation) => relation.messageId === item.id)- .map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),- audioList: audioList- .filter((relation) => relation.messageId === item.id)- .map<ChatAudioItem>(materializeChatAudioItem),- } as unknown as UIChatMessage;- },- );- };-- /**- * Query MessageGroup nodes for a topic- * - compressedGroup: includes pinnedMessages and compressedMessages arrays- * - compareGroup: includes children array- *- * @param topicId - The topic ID to query groups for- * @param timeRange - Optional time range to filter groups (for pagination support)- */- private queryMessageGroupNodes = async (- topicId: string,- timeRange?: { endTime: Date; startTime: Date },- postProcessUrl?: (- path: string | null,- file: { fileType: string; id?: string | null },- ) => Promise<string>,- timing?: ModelTimingContext,- options: { allowShareVisitor?: boolean; window?: MessageGroupNodeWindow } = {},- ): Promise<UIChatMessage[]> => {- // Effective visitor gate β see `queryMessageGroupNodesForPage`. Absent- // this predicate, a creator's default `query({ topicId })` on a visitor- // topic returns no messages but still returns the group's synthetic- // `compressedGroup` node (with its `content` summary) or `compareGroup`- // node, leaking the visitor conversation shape.- const includeVisitor = options.allowShareVisitor || this.includeShareVisitor;-- // 1. Query MessageGroups for this topic, optionally filtered by time range- const whereConditions = [- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups),- eq(messageGroups.topicId, topicId),- ...(includeVisitor ? [] : [notShareVisitorTopicRef(messageGroups.topicId)]),- ];-- // Add time range filter if provided (for pagination)- if (timeRange) {- whereConditions.push(- gte(messageGroups.createdAt, timeRange.startTime),- lte(messageGroups.createdAt, timeRange.endTime),- );- }-- // Explicit half-open `[from, before)` window from cursor pagination, compared- // against lossless microsecond strings so page boundaries stay exact.- if (options.window?.from) {- whereConditions.push(sql`${messageGroups.createdAt} >= ${options.window.from}::timestamptz`);- }- if (options.window?.before) {- whereConditions.push(sql`${messageGroups.createdAt} < ${options.window.before}::timestamptz`);- }-- const groups = await runTimedStage(- timing,- 'db.message.messageGroups.groups.select',- () =>- this.db- .select()- .from(messageGroups)- .where(and(...whereConditions))- .orderBy(asc(messageGroups.createdAt)),- { hasTimeRange: !!timeRange, topicId },- );- logTiming(timing, 'db.message.messageGroups.groups.select:rows', { rowCount: groups.length });-- if (groups.length === 0) return [];-- const groupIds = groups.map((g) => g.id);-- // 2. Get all message IDs that belong to these groups (using messageGroupId relation)- const groupMessageRecords = await runTimedStage(- timing,- 'db.message.messageGroups.messages.select',- () =>- this.db- .select({- favorite: messages.favorite,- id: messages.id,- messageGroupId: messages.messageGroupId,- })- .from(messages)- .where(- and(- // The parent topic has already been classified by the caller- // (via `resolveTopicVisitorScope`) or the model was constructed- // as a share-runtime instance β either way, the per-row NOT- // EXISTS predicate baked into `ownership()` is redundant for- // messages that belong to a group inside a verified topic.- includeVisitor ? this.workspaceScope() : this.ownership(),- inArray(messages.messageGroupId, groupIds),- ),- )- .orderBy(asc(messages.createdAt)),- { groupCount: groupIds.length },- );- logTiming(timing, 'db.message.messageGroups.messages.select:rows', {- rowCount: groupMessageRecords.length,- });-- // 3. Query full message data using queryByIds (reuses all transformation logic)- const allMessageIds = groupMessageRecords.map((m) => m.id as string);- const fullMessages = await runTimedStage(- timing,- 'db.message.messageGroups.queryByIds',- () => this.queryByIds(allMessageIds, { allowShareVisitor: includeVisitor, postProcessUrl }),- { messageCount: allMessageIds.length },- );-- // Create a map for quick lookup- const messageMap = new Map(fullMessages.map((m) => [m.id, m]));- const favoriteMap = new Map(groupMessageRecords.map((m) => [m.id, m.favorite]));-- // 4. Build MessageGroup nodes- return groups.map((group) => {- // Get messages for this group- const groupMsgIds = groupMessageRecords- .filter((m) => m.messageGroupId === group.id)- .map((m) => m.id as string);-- const groupMsgs = groupMsgIds- .map((id) => messageMap.get(id))- .filter(Boolean) as UIChatMessage[];-- if (group.type === MessageGroupType.Compression) {- // compressedGroup: extract pinnedMessages (favorite=true)- const pinnedMessages = groupMsgIds- .filter((id) => favoriteMap.get(id) === true)- .map((id) => {- const m = messageMap.get(id);- return m- ? {- content: m.content,- createdAt: m.createdAt,- id: m.id,- model: m.model,- provider: m.provider,- role: m.role,- }- : null;- })- .filter(Boolean);-- // compressedMessages: parse messages through conversation-flow for proper grouping- // This transforms raw messages into displayMessages format (e.g., assistantGroup)- const { flatList } = parse(groupMsgs);- const compressedMessages = flatList;-- // Get the last message ID for parent-child linking in conversation-flow- const lastMessageId = groupMsgIds.at(-1);-- return {- compressedMessages,- content: group.content,- createdAt: group.createdAt,- id: group.id,- lastMessageId,- metadata: group.metadata,- pinnedMessages,- role: 'compressedGroup',- topicId: group.topicId,- updatedAt: group.updatedAt,- } as unknown as UIChatMessage;- } else {- // compareGroup (parallel): include children with basic info- const children = groupMsgs.map((m) => ({- content: m.content,- createdAt: m.createdAt,- id: m.id,- model: m.model,- provider: m.provider,- role: m.role,- }));-- return {- children,- createdAt: group.createdAt,- id: group.id,- role: 'compareGroup',- topicId: group.topicId,- updatedAt: group.updatedAt,- } as unknown as UIChatMessage;- }- });- };-- /**- * Build where condition for thread queries- *- * Returns a condition that matches both parent messages and thread messages.- */- private buildThreadQueryCondition = async (threadId: string): Promise<SQL | undefined> => {- // Fetch the thread info to get sourceMessageId and type- const thread = await this.db.query.threads.findFirst({- where: and(- eq(threads.id, threadId),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),- ),- });-- if (!thread?.sourceMessageId || !thread?.topicId) {- // Fallback to simple thread query if no source message- return eq(messages.threadId, threadId);- }-- // Get parent messages based on thread type- const parentMessages = await this.getThreadParentMessages({- sourceMessageId: thread.sourceMessageId,- threadType: thread.type as IThreadType,- topicId: thread.topicId,- });-- const parentMessageIds = parentMessages.map((m) => m.id);-- if (parentMessageIds.length === 0) {- return eq(messages.threadId, threadId);- }-- // Match either thread messages or parent messages- return or(eq(messages.threadId, threadId), inArray(messages.id, parentMessageIds));- };-- /**- * Build agent condition with legacy sessionId support- */- private buildAgentCondition = async (agentId: string): Promise<SQL | undefined> => {- // Get the associated sessionId for backward compatibility with legacy data- const agentSession = await this.db- .select({ sessionId: agentsToSessions.sessionId })- .from(agentsToSessions)- .where(and(eq(agentsToSessions.agentId, agentId), this.agentsToSessionsOwnership()))- .limit(1);-- const associatedSessionId = agentSession[0]?.sessionId;-- // Build condition to match both new (agentId) and legacy (sessionId) data- return associatedSessionId- ? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))- : eq(messages.agentId, agentId);- };-- findById = async (id: string) => {- return this.db.query.messages.findFirst({- where: and(eq(messages.id, id), this.ownership()),- });- };-- /**- * Ids among `ids` that resolve to an agent-share VISITOR message under this- * owner β the inverse of the `notShareVisitorMessage()` predicate every- * creator-facing read applies.- *- * Creator-facing write entry points use this to reject visitor targets- * (see `assertCreatorMessageTargets` in the server router helpers). Ids that- * match no row at all are NOT reported, so callers keep their existing no-op- * behaviour for stale/foreign ids and only fail on rows that really belong to- * a visitor's conversation.- */- findShareVisitorMessageIds = async (ids: string[]): Promise<string[]> => {- if (ids.length === 0) return [];-- const rows = await this.db- .select({ id: messages.id })- .from(messages)- // Explicitly scoped visitor-inclusive: this method's whole job is to- // return visitor ids so the router-level `assertCreatorMessageTargets`- // can reject them, so bypass the instance's visitor exclusion.- .where(and(inArray(messages.id, ids), this.workspaceScope(), not(notShareVisitorMessage())));-- return rows.map((row) => row.id);- };-- findByClientId = async (clientId: string) => {- return this.db.query.messages.findFirst({- where: and(eq(messages.clientId, clientId), this.ownership()),- });- };-- findLatestAssistantMessageByThread = async ({- agentId,- threadId,- topicId,- }: {- agentId: string;- threadId: string;- topicId: string;- }) =>- this.db.query.messages.findFirst({- orderBy: [desc(messages.createdAt), desc(messages.id)],- where: and(- this.ownership(),- eq(messages.agentId, agentId),- inArray(- messages.topicId,- this.db- .select({ id: topics.id })- .from(topics)- .where(- and(- eq(topics.id, topicId),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- ),- ),- ),- eq(messages.threadId, threadId),- eq(messages.role, 'assistant'),- ),- });-- /**- * Resolve the `role='verify'` delivery-checker card for an Agent Run (created- * with `metadata.verifyOperationId = operationId`). Used by auto-repair to- * persist the failure feedback onto the card it belongs to.- */- findVerifyMessageByOperationId = async (operationId: string) => {- return this.db.query.messages.findFirst({- where: and(- this.ownership(),- eq(messages.role, 'verify'),- sql`${messages.metadata}->>'verifyOperationId' = ${operationId}`,- ),- orderBy: [desc(messages.createdAt)],- });- };-- /**- * Resolve the newest assistant row an Agent Run produced, by the creation- * provenance `call_llm` stamps on every assistant row it creates or reuses- * (`metadata.operationId`). Scoped by `topicId` so the JSONB predicate runs- * inside the topic's own (indexed) rows rather than across the whole table.- *- * Used by the completion lifecycle to recover the run's real final reply- * when the runtime state no longer carries this run's messages β the- * topic-wide "latest assistant" would be an earlier turn's reply.- */- findLatestAssistantByOperationId = async ({- operationId,- topicId,- }: {- operationId: string;- topicId: string;- }) => {- return this.db.query.messages.findFirst({- where: and(- this.ownership(),- inArray(- messages.topicId,- this.db- .select({ id: topics.id })- .from(topics)- .where(- and(- eq(topics.id, topicId),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- ),- ),- ),- eq(messages.role, 'assistant'),- sql`${messages.metadata}->>'operationId' = ${operationId}`,- ),- orderBy: [desc(messages.createdAt)],- });- };-- /**- * Get parent messages for a thread- *- * @param params - Parameters for getting parent messages- * @param params.sourceMessageId - The ID of the source message that started the thread- * @param params.topicId - The topic ID the thread belongs to- * @param params.threadType - The type of thread (Continuation, Standalone, or Isolation)- * @returns Parent messages based on thread type:- * - Continuation: All messages from the topic up to and including the source message- * - Standalone: Only the source message itself- * - Isolation: No parent messages (completely isolated thread)- */- getThreadParentMessages = async (params: {- sourceMessageId: string;- threadType: IThreadType;- topicId: string;- }): Promise<DBMessageItem[]> => {- const { sourceMessageId, topicId, threadType } = params;-- // For Isolation type, return empty array (no parent messages)- if (threadType === ThreadType.Isolation) {- return [];- }-- // For Standalone type, only return the source message- if (threadType === ThreadType.Standalone) {- const sourceMessage = await this.db.query.messages.findFirst({- where: and(eq(messages.id, sourceMessageId), this.ownership()),- });-- return sourceMessage ? [sourceMessage as DBMessageItem] : [];- }-- // For Continuation type, get the source message first to know its createdAt- const sourceMessage = await this.db.query.messages.findFirst({- where: and(eq(messages.id, sourceMessageId), this.ownership()),- });-- if (!sourceMessage) return [];-- // Get all main conversation messages up to and including the source message- // Use `or` with explicit id match to handle timestamp precision issues- // (JavaScript Date has millisecond precision, but PostgreSQL timestamptz has microsecond precision)- const result = await this.db- .select()- .from(messages)- .where(- and(- this.ownership(),- eq(messages.topicId, topicId),- isNull(messages.threadId), // Only main conversation messages (not in any thread)- or(- lte(messages.createdAt, sourceMessage.createdAt),- eq(messages.id, sourceMessageId), // Ensure source message is always included- ),- ),- )- .orderBy(asc(messages.createdAt));-- return result as DBMessageItem[];- };-- findMessageQueriesById = async (messageId: string) => {- const result = await this.db- .select({- embeddings: embeddings.embeddings,- id: messageQueries.id,- query: messageQueries.rewriteQuery,- rewriteQuery: messageQueries.rewriteQuery,- userQuery: messageQueries.userQuery,- })- .from(messageQueries)- .where(and(eq(messageQueries.messageId, messageId)))- .leftJoin(embeddings, eq(embeddings.id, messageQueries.embeddingsId));-- if (result.length === 0) return undefined;-- return result[0];- };-- /**- * Full creator-facing message dump (`getAllMessages` / CLI export), so- * agent-share visitor messages must be excluded like every other- * creator-facing listing. The exclusion rides on- * {@link MessageModel.analyticsConditions}, which already ANDs- * `notShareVisitorMessage()` β see `../utils/shareVisitor`.- */- queryAll = async (params?: MessageAnalyticsFilters & { current?: number; pageSize?: number }) => {- const { current = 0, pageSize = 100, ...filters } = params ?? {};- const offset = current * pageSize;-- const result = await this.db- .select({- ...getTableColumns(messages),- agentName: agents.name,- agentTitle: agents.title,- })- .from(messages)- .leftJoin(agents, eq(messages.agentId, agents.id))- .where(genWhere(this.analyticsConditions(filters)))- .orderBy(desc(messages.createdAt))- .limit(pageSize)- .offset(offset);-- return result as (DBMessageItem & {- agentName: string | null;- agentTitle: string | null;- })[];- };-- // Plain select builder instead of `db.query...findMany`: the relational- // query API re-qualifies raw SQL fragments to the outer table alias, which- // breaks the `topics`-referencing NOT EXISTS inside `notShareVisitorMessage`.- queryBySessionId = async (sessionId?: string | null) => {- const result = await this.db- .select()- .from(messages)- // Visitor messages have no sessionId, so the null-session (inbox) branch- // would otherwise sweep them in.- .where(and(this.ownership(), this.matchSession(sessionId), notShareVisitorMessage()))- .orderBy(asc(messages.createdAt));-- return result as DBMessageItem[];- };-- queryByKeyword = async (keyword: string) => {- if (!keyword.trim()) return [];-- const bm25Query = sanitizeBm25Query(keyword);- const candidateResult = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled- ? await this.ftsSearchCandidateSource.ftsSearchCandidates({- entity: 'messages',- filters: {},- pagination: {},- query: { fields: ['content'], text: keyword },- })- : undefined;- const candidateIds = candidateResult?.candidates.map(({ id }) => id);- const result = await this.db- .select()- .from(messages)- .where(- and(- this.ownership(),- notShareVisitorMessage(),- searchableMessage(),- candidateIds- ? inJsonStringArray(messages.id, candidateIds)- : sql`${messages.content} @@@ ${bm25Query}`,- ),- )- .orderBy(desc(messages.createdAt));-- return result as DBMessageItem[];- };-- /**- * Ownership-scoped analytics filter conditions, shared by count /- * countGroupByTopic / topicMessageStats. The first entry is always the- * `userId Γ workspace` ownership predicate; later entries are optional.- * Agent-share visitor messages carry the creator's `userId`, so personal- * analytics must exclude them (visitor usage is reported separately by the- * share usage center) β see `notShareVisitorMessage` in `../utils/shareVisitor`.- *- * MUST NOT be applied to {@link countByTopic} β see that method's JSDoc for- * why exact per-topic turn counting needs the visitor topic's own messages.- */- private analyticsConditions = (params?: MessageAnalyticsFilters) => [- this.ownership(),- notShareVisitorMessage(),- params?.agentId ? eq(messages.agentId, params.agentId) : undefined,- params?.topicId ? eq(messages.topicId, params.topicId) : undefined,- params?.role ? eq(messages.role, params.role) : undefined,- params?.range- ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())- : undefined,- params?.endDate- ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())- : undefined,- params?.startDate- ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())- : undefined,- ];-- count = async (params?: MessageAnalyticsFilters): Promise<number> => {- const result = await this.db- .select({- count: count(messages.id),- })- .from(messages)- .where(genWhere(this.analyticsConditions(params)));-- return result[0].count;- };-- /**- * Approximate variant of {@link count} for dashboard totals. An exact- * COUNT over `messages` heap-fetches every row the user owns (tens of- * seconds for accounts with 100k+ messages), which no stats card needs.- *- * Strategy: ask the planner for a row estimate first (EXPLAIN, a few ms).- * Accounts the estimate marks as clearly heavy get the estimate, rounded- * to 3 significant digits so the number reads as the approximation it is.- * Everyone else β the vast majority β gets an exact count capped at- * `cap + 1` rows, which is cheap at that size. A user the planner- * underestimates still can't get a value below what the capped scan saw.- * Parallel workers are disabled for the EXPLAIN because parallel plans- * report per-worker row estimates, not totals.- */- countApproximate = async (- params?: MessageAnalyticsFilters,- { cap = 10_000 }: { cap?: number } = {},- ): Promise<number> => {- const where = genWhere(this.analyticsConditions(params));-- const roundEstimate = (estimate: number) => {- const magnitude = 10 ** Math.max(0, Math.floor(Math.log10(estimate)) - 2);- return Math.round(estimate / magnitude) * magnitude;- };-- let estimate: number | undefined;- try {- const estimateQuery = this.db.select({ id: messages.id }).from(messages).where(where);- const result = await this.db.transaction(async (trx) => {- await trx.execute(sql`SET LOCAL max_parallel_workers_per_gather = 0`);- return trx.execute(sql`EXPLAIN (FORMAT JSON) ${estimateQuery.getSQL()}`);- });- const rawPlan = result.rows[0]?.['QUERY PLAN'];- const parsed = typeof rawPlan === 'string' ? JSON.parse(rawPlan) : rawPlan;- const parsedRows = Number((parsed as any)?.[0]?.['Plan']?.['Plan Rows']);- if (Number.isFinite(parsedRows)) estimate = parsedRows;- } catch (error) {- // Best-effort β fall through to the capped exact count, but surface the- // degradation: past-cap accounts will all read as `cap + 1` until fixed.- console.error('countApproximate: planner estimate failed, using capped count only:', error);- }-- if (estimate !== undefined && estimate > cap * 2) return roundEstimate(estimate);-- const cappedRows = this.db- .select({ id: messages.id })- .from(messages)- .where(where)- .limit(cap + 1)- .as('capped');- const capped = await this.db.select({ count: count() }).from(cappedRows);- const exact = capped[0].count;- if (exact <= cap) return exact;-- return Math.max(estimate === undefined ? 0 : roundEstimate(estimate), exact);- };-- /**- * Count matching messages grouped by topic, sorted by count desc.- * Topics without a `topicId` are excluded. Pushes the GROUP BY to the DB- * so callers don't have to paginate raw rows and count client-side.- */- countGroupByTopic = async (- params?: MessageAnalyticsFilters,- ): Promise<TopicMessageCountItem[]> => {- const rows = await this.db- .select({- count: count(messages.id),- topicId: messages.topicId,- })- .from(messages)- .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))- .groupBy(messages.topicId)- .orderBy(desc(sql`count`), asc(messages.topicId));-- return rows.map((r) => ({ count: r.count, topicId: r.topicId! }));- };-- /**- * Distribution of message counts per topic (topics / mean / median /- * p90 / p99 / min / max / one-shot ratio + histogram). The per-topic- * counts are aggregated in the DB; only the final summary is returned.- */- topicMessageStats = async (params?: MessageAnalyticsFilters): Promise<TopicMessageStats> => {- const rows = await this.db- .select({- count: count(messages.id),- topicId: messages.topicId,- })- .from(messages)- .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))- .groupBy(messages.topicId);-- return computeTopicMessageStats(rows.map((r) => r.count));- };-- hasTopicMessages = async (topicId: string): Promise<boolean> => {- const rows = await this.db- .select({ id: messages.id })- .from(messages)- .where(and(eq(messages.topicId, topicId), this.ownership()))- .limit(1);-- return rows.length > 0;- };-- findFirstAssistantInTopic = async (topicId: string): Promise<DBMessageItem | undefined> => {- const rows = (await this.db- .select()- .from(messages)- .where(and(eq(messages.topicId, topicId), eq(messages.role, 'assistant'), this.ownership()))- .orderBy(asc(messages.createdAt))- .limit(1)) as DBMessageItem[];-- return rows[0];- };-- countWords = async (params?: {- endDate?: string;- range?: [string, string];- startDate?: string;- }): Promise<number> => {- const result = await this.db- .select({- count: sql<string>`sum(length(${messages.content}))`.as('total_length'),- })- .from(messages)- .where(- genWhere([- this.ownership(),- notShareVisitorMessage(),- params?.range- ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())- : undefined,- params?.endDate- ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())- : undefined,- params?.startDate- ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())- : undefined,- ]),- );-- return Number(result[0].count);- };-- rankModels = async (limit: number = 10): Promise<ModelRankItem[]> => {- return this.db- .select({- count: count(messages.id).as('count'),- id: messages.model,- })- .from(messages)- .where(- and(- this.ownership(),- notShareVisitorMessage(),- isNotNull(messages.model),- notCopiedTranscript(),- ),- )- .having(({ count }) => gt(count, 0))- .groupBy(messages.model)- .orderBy(desc(sql`count`), asc(messages.model))- .limit(limit);- };-- getHeatmaps = async (): Promise<HeatmapsProps['data']> => {- const startDate = today().subtract(1, 'year').startOf('day');- const endDate = today().endOf('day');-- const result = await this.db- .select({- count: count(messages.id),- date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),- })- .from(messages)- .where(- genWhere([- this.ownership(),- notShareVisitorMessage(),- genRangeWhere(- [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],- messages.createdAt,- (date) => date.toDate(),- ),- ]),- )- .groupBy(sql`heatmaps_date`)- .orderBy(desc(sql`heatmaps_date`));-- const heatmapData: HeatmapsProps['data'] = [];- let currentDate = startDate.clone();-- const dateCountMap = new Map<string, number>();- for (const item of result) {- if (item?.date) {- const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- dateCountMap.set(dateStr, item.count);- }- }-- while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {- const formattedDate = currentDate.format('YYYY-MM-DD');- const count = dateCountMap.get(formattedDate) || 0;-- const levelCount = count > 0 ? Math.ceil(count / 5) : 0;- const level = levelCount > 4 ? 4 : levelCount;-- heatmapData.push({- count,- date: formattedDate,- level,- });-- currentDate = currentDate.add(1, 'day');- }-- return heatmapData;- };-- /**- * Daily token-usage heatmap for the last year.- *- * Sums `usage.totalTokens` of assistant messages bucketed by the day each- * message was created β so tokens land on the day they were actually consumed- * (a long-running topic spreads across days instead of piling onto its- * creation date). Reads prefer the dedicated `usage` column and fall back to- * legacy `metadata.usage`, aggregating directly in SQL rather than pulling- * rows into JS. `level` is scaled relative to the busiest day so the heatmap- * stays readable regardless of absolute token volume.- */- getTokenHeatmaps = async (): Promise<HeatmapsProps['data']> => {- const startDate = today().subtract(1, 'year').startOf('day');- const endDate = today().endOf('day');-- const result = await this.db- .select({- date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),- tokens:- sql<number>`COALESCE(SUM((COALESCE(${messages.usage}, ${messages.metadata}->'usage')->>'totalTokens')::numeric), 0)`.mapWith(- Number,- ),- })- .from(messages)- .where(- genWhere([- this.ownership(),- notShareVisitorMessage(),- eq(messages.role, 'assistant'),- notCopiedTranscript(),- genRangeWhere(- [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],- messages.createdAt,- (date) => date.toDate(),- ),- ]),- )- .groupBy(sql`heatmaps_date`)- .orderBy(desc(sql`heatmaps_date`));-- const dateTokenMap = new Map<string, number>();- let maxTokens = 0;- for (const item of result) {- if (item?.date) {- const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- const tokens = item.tokens || 0;- dateTokenMap.set(dateStr, tokens);- if (tokens > maxTokens) maxTokens = tokens;- }- }-- const heatmapData: HeatmapsProps['data'] = [];- let currentDate = startDate.clone();-- while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {- const formattedDate = currentDate.format('YYYY-MM-DD');- const tokens = dateTokenMap.get(formattedDate) || 0;-- // Scale to 1-4 relative to the busiest day; 0 tokens stays at level 0.- const level =- tokens > 0 && maxTokens > 0- ? Math.min(4, Math.max(1, Math.ceil((tokens / maxTokens) * 4)))- : 0;-- heatmapData.push({- count: tokens,- date: formattedDate,- level,- });-- currentDate = currentDate.add(1, 'day');- }-- return heatmapData;- };-- hasMoreThanN = async (n: number): Promise<boolean> => {- const result = await this.db- .select({ id: messages.id })- .from(messages)- .where(and(this.ownership()))- .limit(n + 1);-- return result.length > n;- };-- /**- * Count messages up to a limit, useful for avoiding full table scans- */- countUpTo = async (n: number): Promise<number> => {- const result = await this.db- .select({ id: messages.id })- .from(messages)- .where(and(this.ownership()))- .limit(n);-- return result.length;- };-- // **************** Create *************** //-- private splitCreateMessageParams = ({- fileChunks,- files,- model: fromModel,- plugin,- pluginError,- pluginIntervention,- pluginState,- provider: fromProvider,- ragQueryId,- updatedAt,- createdAt,- ...message- }: CreateMessageParams): SplitCreateMessageParams => ({- insert: {- createdAt,- fromModel,- fromProvider,- message,- updatedAt,- },- relations: {- fileChunks,- files,- plugin,- pluginError,- pluginIntervention,- pluginState,- ragQueryId,- },- });-- private buildMessageInsertValue = (- { createdAt, fromModel, fromProvider, message, updatedAt }: CreateMessageInsertParams,- id: string,- ) => {- // Ensure group message does not populate sessionId- const normalizedMessage = message.groupId ? { ...message, sessionId: null } : message;- const { usage: legacyUsage, ...metadata } =- (normalizedMessage.metadata as Record<string, any> | undefined) || {};-- return buildWorkspacePayload(- { userId: this.userId, workspaceId: this.workspaceId },- {- ...normalizedMessage,- // Sanitize content to strip null bytes that PostgreSQL rejects- content: sanitizeNullBytes(normalizedMessage.content),- // TODO: remove this when the client is updated- createdAt: createdAt ? new Date(createdAt) : undefined,- id,- metadata: normalizedMessage.metadata ? metadata : undefined,- model: fromModel,- provider: fromProvider,- updatedAt: updatedAt ? new Date(updatedAt) : undefined,- // Promote token usage into the dedicated `usage` column, preferring a- // top-level `usage` over the legacy `metadata.usage`.- usage: normalizedMessage.usage ?? (legacyUsage as ModelUsage | undefined),- },- );- };-- private insertMessageRelationsInTransaction = async (- trx: Transaction,- {- fileChunks,- files,- plugin,- pluginError,- pluginIntervention,- pluginState,- ragQueryId,- }: CreateMessageRelationParams,- message: CreateMessageInsertParams['message'],- id: string,- timing?: ModelTimingContext,- timingPrefix: string = 'db.message.create',- ): Promise<void> => {- // Insert the plugin data if the message is a tool- if (message.role === 'tool') {- await runTimedStage(timing, `${timingPrefix}.plugin.insert`, () =>- trx.insert(messagePlugins).values({- apiName: clampToolIdentifier(plugin?.apiName),- arguments: sanitizeNullBytes(plugin?.arguments),- // A tool that fails on its first write only has pluginError to explain- // itself; without it the model reads an empty tool result.- error: sanitizeNullBytes(pluginError),- id,- identifier: clampToolIdentifier(plugin?.identifier),- intervention: pluginIntervention,- state: sanitizeNullBytes(pluginState),- toolCallId: message.tool_call_id,- type: plugin?.type,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- }),- );- }-- if (files && files.length > 0) {- await runTimedStage(- timing,- `${timingPrefix}.files.insert`,- () =>- trx.insert(messagesFiles).values(- files.map((file) => ({- fileId: file,- messageId: id,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- ),- { fileCount: files.length },- );- }-- if (fileChunks && fileChunks.length > 0 && ragQueryId) {- await runTimedStage(- timing,- `${timingPrefix}.fileChunks.insert`,- () =>- trx.insert(messageQueryChunks).values(- fileChunks.map((chunk) => ({- chunkId: chunk.id,- messageId: id,- queryId: ragQueryId,- similarity: chunk.similarity?.toString(),- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- ),- { chunkCount: fileChunks.length },- );- }- };-- private createInTransaction = async (- trx: Transaction,- params: CreateMessageParams,- id: string,- timing?: ModelTimingContext,- timingPrefix: string = 'db.message.create',- ): Promise<DBMessageItem> => {- const { insert, relations } = this.splitCreateMessageParams(params);-- const [item] = (await runTimedStage(- timing,- `${timingPrefix}.messages.insert`,- () => trx.insert(messages).values(this.buildMessageInsertValue(insert, id)).returning(),- {- hasGroupId: !!insert.message.groupId,- hasTopicId: !!insert.message.topicId,- role: insert.message.role,- },- )) as DBMessageItem[];-- await this.insertMessageRelationsInTransaction(- trx,- relations,- insert.message,- id,- timing,- timingPrefix,- );-- return item;- };-- create = async (- params: CreateMessageParams,- id: string = this.genId(),- timing?: ModelTimingContext,- ): Promise<DBMessageItem> => {- return runTimedStage(- timing,- 'db.message.create.transaction',- () =>- this.db.transaction(async (trx) => {- const item = await this.createInTransaction(trx, params, id, timing);-- return item;- }),- {- fileChunkCount: params.fileChunks?.length ?? 0,- fileCount: params.files?.length ?? 0,- hasTopicId: !!params.topicId,- role: params.role,- },- );- };-- createUserAndAssistantMessages = async (- { userMessage, assistantMessage }: CreateUserAndAssistantMessagesParams,- { ids, timing }: CreateUserAndAssistantMessagesOptions = {},- ): Promise<{ assistantMessage: DBMessageItem; userMessage: DBMessageItem }> => {- const userMessageId = ids?.userMessageId ?? this.genId();- const assistantMessageId = ids?.assistantMessageId ?? this.genId();- const createdAt = Date.now();- const defaultUserCreatedAt = createdAt;- const defaultAssistantCreatedAt = createdAt + 1;- const userMessageWithTimestamp = {- ...userMessage,- createdAt: userMessage.createdAt ?? defaultUserCreatedAt,- updatedAt:- userMessage.updatedAt ?? (userMessage.createdAt ? undefined : defaultUserCreatedAt),- };- const assistantMessageWithParent = {- ...assistantMessage,- createdAt: assistantMessage.createdAt ?? defaultAssistantCreatedAt,- parentId: userMessageId,- updatedAt:- assistantMessage.updatedAt ??- (assistantMessage.createdAt ? undefined : defaultAssistantCreatedAt),- };- const topicIds = [- ...new Set([userMessage.topicId, assistantMessage.topicId].filter(Boolean) as string[]),- ];-- return runTimedStage(- timing,- 'db.message.createUserAndAssistant.transaction',- () =>- this.db.transaction(async (trx) => {- const userPayload = this.splitCreateMessageParams(userMessageWithTimestamp);- const assistantPayload = this.splitCreateMessageParams(assistantMessageWithParent);- const insertedMessages = (await runTimedStage(- timing,- 'db.message.createUserAndAssistant.messages.insert',- () =>- trx- .insert(messages)- .values([- this.buildMessageInsertValue(userPayload.insert, userMessageId),- this.buildMessageInsertValue(assistantPayload.insert, assistantMessageId),- ])- .returning(),- { hasTopicId: topicIds.length > 0, messageCount: 2 },- )) as DBMessageItem[];- const messageMap = new Map(insertedMessages.map((message) => [message.id, message]));-- await this.insertMessageRelationsInTransaction(- trx,- userPayload.relations,- userPayload.insert.message,- userMessageId,- timing,- 'db.message.createUserAndAssistant.user',- );- await this.insertMessageRelationsInTransaction(- trx,- assistantPayload.relations,- assistantPayload.insert.message,- assistantMessageId,- timing,- 'db.message.createUserAndAssistant.assistant',- );-- const userMessageItem = messageMap.get(userMessageId);- const assistantMessageItem = messageMap.get(assistantMessageId);-- if (!userMessageItem || !assistantMessageItem) {- throw new Error('Failed to create user and assistant messages');- }-- return { assistantMessage: assistantMessageItem, userMessage: userMessageItem };- }),- {- assistantFileCount: assistantMessage.files?.length ?? 0,- hasTopicId: topicIds.length > 0,- userFileCount: userMessage.files?.length ?? 0,- },- );- };-- batchCreate = async (newMessages: DBMessageItem[]) => {- const messagesToInsert = newMessages.map((m) =>- buildWorkspacePayload(- { userId: this.userId, workspaceId: this.workspaceId },- // TODO: need a better way to handle this- { ...m, role: m.role as any },- ),- );-- return this.db.transaction(async (trx) => {- const result = await trx.insert(messages).values(messagesToInsert);-- return result;- });- };-- createMessageQuery = async (params: NewMessageQueryParams) => {- const result = await this.db- .insert(messageQueries)- .values({ ...params, userId: this.userId, workspaceId: this.workspaceId ?? null })- .returning();-- return result[0];- };- // **************** Update *************** //-- update = async (- id: string,- { imageList, metadata, usage, ...message }: Partial<UpdateMessageParams>,- timing?: ModelTimingContext,- ): Promise<{ success: boolean }> => {- // Accept legacy callers that still send `metadata.usage`, but persist usage- // exclusively in the dedicated top-level column.- const { usage: legacyUsage, ...metadataPatch } = (metadata as Record<string, any>) || {};- const usageToWrite = usage ?? (legacyUsage as ModelUsage | undefined);- const shouldUpdateMetadata = !!metadata || !!usageToWrite;- // A patch that matches no row is a lost write, not a no-op: the caller asked- // to persist content onto `id` and it went nowhere. Batched writers key their- // retry ledger off this flag, so reporting success here silently drops data.- let matchedRow = false;- try {- await runTimedStage(- timing,- 'db.message.update.transaction',- () =>- this.db.transaction(async (trx) => {- // 1. insert message files- if (imageList && imageList.length > 0) {- await runTimedStage(- timing,- 'db.message.update.imageFiles.insert',- () =>- trx.insert(messagesFiles).values(- imageList.map((file) => ({- fileId: file.id,- messageId: id,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- ),- { imageCount: imageList.length },- );- }-- // 2. Merge non-usage metadata. A usage-bearing update also removes- // any legacy `metadata.usage` left on the existing row.- let mergedMetadata: Record<string, any> | undefined;- if (shouldUpdateMetadata) {- const [existingMessage] = await runTimedStage(- timing,- 'db.message.update.metadata.select',- () =>- trx- .select({ metadata: messages.metadata })- .from(messages)- .where(and(eq(messages.id, id), this.ownership())),- );- mergedMetadata = merge(existingMessage?.metadata || {}, metadataPatch);- if (usageToWrite && mergedMetadata) delete mergedMetadata.usage;- }- const metadataToWrite = mergedMetadata;-- const [updated] = await runTimedStage(- timing,- 'db.message.update.messages.update',- () =>- trx- .update(messages)- .set({- ...message,- ...(metadataToWrite && { metadata: metadataToWrite }),- ...(usageToWrite && { usage: usageToWrite }),- })- .where(and(eq(messages.id, id), this.ownership()))- .returning({ topicId: messages.topicId }),- { hasMetadata: !!metadataPatch, valueKeys: Object.keys(message) },- );-- matchedRow = !!updated;-- if (- updated?.topicId && // When this write carries token usage (assistant finalize / hetero- // step), recompute the topic's denormalized usage rollup from its- // messages. Gated on the *incoming* payload so streaming- // content-only updates don't trigger needless recomputes.- usageToWrite- ) {- await runTimedStage(- timing,- 'db.message.update.topic.recomputeUsage',- () => recomputeTopicUsage(trx, this.userId, updated.topicId!, this.workspaceId),- { topicCount: 1 },- );- }- }),- {- hasImageList: !!imageList?.length,- hasMetadata: shouldUpdateMetadata,- valueKeys: Object.keys(message),- },- );-- if (!matchedRow) {- console.error(`Update message error: no message matched id ${id}`);- return { success: false };- }-- return { success: true };- } catch (error) {- console.error('Update message error:', error);- return { success: false };- }- };-- updateMetadata = async (id: string, metadata: Record<string, any>) => {- const item = await this.db.query.messages.findFirst({- where: and(eq(messages.id, id), this.ownership()),- });-- if (!item) return;-- const { usage: usageToWrite, ...metadataPatch } = metadata as Record<string, any>;- const mergedMetadata = merge(item.metadata || {}, metadataPatch);- if (usageToWrite) delete mergedMetadata.usage;-- return this.db- .update(messages)- .set({- metadata: mergedMetadata,- ...(usageToWrite && { usage: usageToWrite }),- })- .where(and(eq(messages.id, id), this.ownership()));- };-- updatePluginState = async (id: string, state: Record<string, any>): Promise<void> => {- const updated = await this.db- .update(messagePlugins)- .set({- // Plugin-state patches own complete top-level keys. Merge them in SQL so- // concurrent writers of different keys cannot overwrite each other.- state: sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(state)}::jsonb`,- })- .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))- .returning({ id: messagePlugins.id });-- if (updated.length === 0) throw new Error('Plugin not found');- };-- updateMessagePlugin = async (id: string, value: Partial<MessagePluginItem>) => {- const item = await this.db.query.messagePlugins.findFirst({- where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),- });- if (!item) throw new Error('Plugin not found');-- return this.db- .update(messagePlugins)- .set({- ...value,- apiName: clampToolIdentifier(value.apiName),- identifier: clampToolIdentifier(value.identifier),- })- .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()));- };-- /**- * Resolve an approval batch at one row-locking boundary. Every target is- * checked before any write, so Web, Mobile, Stop, and notification actions- * cannot each win a subset of the same assistant turn. Source adapters claim- * only; content/state remain in their private resolution until the runtime- * passes publishResult after afterToolCall. Stop may publish its fixed receipt.- */- resolveHumanApproval = async (- resolutions: HumanApprovalResolution[],- options: { publishResult?: boolean } = {},- ): Promise<'applied' | 'idempotent'> => {- if (resolutions.length === 0) return 'idempotent';-- const ids = resolutions.map(({ id }) => id);- if (new Set(ids).size !== ids.length) {- throw new Error('Human approval batch contains duplicate tool messages');- }-- return this.db.transaction(async (trx) => {- // Match deferred completion's lock order (message before plugin).- const lockedMessages = await trx- .select({ id: messages.id, content: messages.content })- .from(messages)- .where(and(inArray(messages.id, ids), this.ownership()))- .orderBy(messages.id)- .for('update');- const messagesById = new Map(lockedMessages.map((row) => [row.id, row]));- const lockedRows = await trx- .select({- id: messagePlugins.id,- intervention: messagePlugins.intervention,- state: messagePlugins.state,- })- .from(messagePlugins)- .where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()))- .for('update');- const lockedById = new Map(lockedRows.map((row) => [row.id, row]));-- const rowStates = resolutions.map((resolution) => {- const row = lockedById.get(resolution.id);- if (!row) throw new Error(`Plugin not found: ${resolution.id}`);- if (row.intervention?.status === 'pending') return 'pending' as const;-- const sameRequest =- Boolean(resolution.intervention.resolutionRequestId) &&- row.intervention?.resolutionRequestId === resolution.intervention.resolutionRequestId;- const sameDecision = Object.entries(resolution.intervention).every(- ([key, value]) =>- JSON.stringify(row.intervention?.[key as keyof typeof row.intervention]) ===- JSON.stringify(value),- );- if (sameRequest && sameDecision) return 'idempotent' as const;- throw new HumanApprovalAlreadyResolvedError(resolution.id);- });- const pendingCount = rowStates.filter((state) => state === 'pending').length;- if (pendingCount === 0 && !options.publishResult) return 'idempotent';- if (pendingCount !== 0 && pendingCount !== resolutions.length) {- throw new Error('Human approval batch contains a partial idempotent claim');- }-- let published = false;- for (const resolution of resolutions) {- // An already claimed source answer can publish exactly once. A replay- // retains the first final content, including a hook denial.- if (- pendingCount === 0 &&- (messagesById.get(resolution.id)?.content ||- (resolution.content === undefined &&- resolution.pluginState === undefined &&- resolution.pluginError === undefined))- )- continue;- published = true;- const row = lockedById.get(resolution.id)!;- if (options.publishResult && resolution.content !== undefined) {- const [updatedMessage] = await trx- .update(messages)- .set({ content: resolution.content })- .where(and(eq(messages.id, resolution.id), this.ownership()))- .returning({ id: messages.id });- if (!updatedMessage) throw new Error(`Message not found: ${resolution.id}`);- }-- const [updatedPlugin] = await trx- .update(messagePlugins)- .set({- // Status/result is a claim patch, not a replacement. Preserve the- // authoritative operation/batch/item identity stamped when the- // parked tool row was created so subsequent source reads, Stop,- // and rollback still address the same sealed batch.- intervention: merge(row.intervention || {}, resolution.intervention),- ...(options.publishResult &&- resolution.pluginError !== undefined && { error: resolution.pluginError }),- ...(options.publishResult &&- resolution.pluginState !== undefined && {- state: resolution.replacePluginState- ? resolution.pluginState- : merge(row.state || {}, resolution.pluginState || {}),- }),- })- .where(and(eq(messagePlugins.id, resolution.id), this.pluginsOwnership()))- .returning({ id: messagePlugins.id });- if (!updatedPlugin) throw new Error(`Plugin not found: ${resolution.id}`);- }-- return published ? 'applied' : 'idempotent';- });- };-- /** Restore the exact pre-claim snapshot when continuation startup fails. */- restoreHumanApproval = async (resolutions: HumanApprovalResolution[]): Promise<void> => {- if (resolutions.length === 0) return;-- await this.db.transaction(async (trx) => {- const ids = resolutions.map(({ id }) => id);- await trx- .select({ id: messages.id })- .from(messages)- .where(and(inArray(messages.id, ids), this.ownership()))- .orderBy(messages.id)- .for('update');- const lockedRows = await trx- .select({ id: messagePlugins.id, intervention: messagePlugins.intervention })- .from(messagePlugins)- .where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()))- .for('update');- const lockedById = new Map(lockedRows.map((row) => [row.id, row]));-- for (const resolution of resolutions) {- const locked = lockedById.get(resolution.id);- if (!locked) throw new Error(`Plugin not found: ${resolution.id}`);- if (- resolution.claimedResolutionRequestId &&- locked.intervention?.resolutionRequestId !== resolution.claimedResolutionRequestId- ) {- continue;- }- if (resolution.content !== undefined) {- const [updatedMessage] = await trx- .update(messages)- .set({ content: resolution.content })- .where(and(eq(messages.id, resolution.id), this.ownership()))- .returning({ id: messages.id });- if (!updatedMessage) throw new Error(`Message not found: ${resolution.id}`);- }- await trx- .update(messagePlugins)- .set({- intervention: resolution.intervention,- ...(resolution.pluginError !== undefined && { error: resolution.pluginError }),- ...(resolution.pluginState !== undefined && { state: resolution.pluginState }),- })- .where(and(eq(messagePlugins.id, resolution.id), this.pluginsOwnership()));- }- });- };-- /**- * Fetch the `message_plugins` row associated with a tool message. Tool-call- * metadata (identifier / apiName / arguments / type / toolCallId /- * intervention) lives on this row, not on the `messages` row returned by- * {@link findById}.- *- * Returns `undefined` when the message has no plugin row. Normalizes the- * DB row (nullable columns) into the optional-field shape of- * {@link MessagePluginItem} so callers don't need to juggle `null` vs- * `undefined`.- */- findMessagePlugin = async (messageId: string): Promise<MessagePluginItem | undefined> => {- const row = await this.db.query.messagePlugins.findFirst({- where: and(eq(messagePlugins.id, messageId), this.pluginsOwnership()),- });- if (!row) return undefined;- return {- apiName: row.apiName ?? undefined,- arguments: row.arguments ?? undefined,- clientId: row.clientId ?? undefined,- error: row.error ?? undefined,- id: row.id,- identifier: row.identifier ?? undefined,- intervention: row.intervention ?? undefined,- state: row.state ?? undefined,- toolCallId: row.toolCallId ?? undefined,- type: row.type ?? 'default',- userId: row.userId,- };- };-- /**- * List tool/plugin rows for a topic in stable first-seen order.- *- * This is used by onboarding analytics to reconstruct successful assistant- * creation results before the topic is moved into inbox.- */- listMessagePluginsByTopic = async (- topicId: string,- ): Promise<Array<MessagePluginItem & { metadata?: MessageMetadata }>> => {- const rows = await this.db- .select({- apiName: messagePlugins.apiName,- arguments: messagePlugins.arguments,- clientId: messagePlugins.clientId,- error: messagePlugins.error,- id: messagePlugins.id,- identifier: messagePlugins.identifier,- intervention: messagePlugins.intervention,- metadata: messages.metadata,- state: messagePlugins.state,- toolCallId: messagePlugins.toolCallId,- type: messagePlugins.type,- userId: messagePlugins.userId,- })- .from(messagePlugins)- .innerJoin(messages, eq(messagePlugins.id, messages.id))- .where(and(eq(messages.topicId, topicId), this.ownership(), this.pluginsOwnership()))- .orderBy(asc(messages.createdAt), asc(messages.id));-- return rows.map((row) => ({- apiName: row.apiName ?? undefined,- arguments: row.arguments ?? undefined,- clientId: row.clientId ?? undefined,- error: row.error ?? undefined,- id: row.id,- identifier: row.identifier ?? undefined,- intervention: row.intervention ?? undefined,- metadata: row.metadata ?? undefined,- state: row.state ?? undefined,- toolCallId: row.toolCallId ?? undefined,- type: row.type ?? 'default',- userId: row.userId,- }));- };-- /**- * The `state` of the most recent call to one tool API in a topic that- * produced any β a failed or aborted call leaves no state. Lets a tool read- * back what an earlier call in the same conversation produced, e.g. the group- * a builder conversation last created with `createGroup`.- *- * Scoped like a message query for the same branch: without `threadId` only- * the main conversation counts; with it, the thread plus the parent messages- * its type inherits β never a sibling thread.- */- findLatestPluginStateInTopic = async (params: {- apiName: string;- identifier: string;- threadId?: string | null;- topicId: string;- }): Promise<Record<string, any> | undefined> => {- const threadCondition = params.threadId- ? await this.buildThreadQueryCondition(params.threadId)- : isNull(messages.threadId);-- const [row] = await this.db- .select({ state: messagePlugins.state })- .from(messagePlugins)- .innerJoin(messages, eq(messagePlugins.id, messages.id))- .where(- and(- eq(messages.topicId, params.topicId),- threadCondition,- eq(messagePlugins.identifier, params.identifier),- eq(messagePlugins.apiName, params.apiName),- isNotNull(messagePlugins.state),- this.ownership(),- this.pluginsOwnership(),- ),- )- .orderBy(desc(messages.createdAt), desc(messages.id))- .limit(1);-- return row?.state ?? undefined;- };-- /**- * List the tool/plugin rows produced by ONE agent operation, for the- * per-operation file-edit scan.- *- * An operation has no direct foreign key on `message_plugins`, so its rows are- * bracketed two ways, OR-ed together:- * 1. Time window β same `topicId` + `threadId`, with the owning message's- * `createdAt` inside `[startedAt, completedAt]` (`completedAt` falls back to- * now for an op still finalizing). The primary path for in-process runs.- * 2. Heterogeneous match β the message carries- * `metadata.heterogeneousToolStateOperationId === operationId` directly,- * which a CLI-backed run stamps regardless of when the row lands. Mirrors- * the jsonb predicate in {@link findVerifyMessageByOperationId}.- *- * TRADE-OFF (v1): the time window is racy β two operations running- * concurrently in the SAME topic+thread can bleed each other's tool calls into- * the window. Accepted for now; the heterogeneous path is exact where it- * applies. Rows carry `createdAt` so the caller can globally order tool calls- * merged across an operation tree before folding them.- */- listMessagePluginsForOperation = async (params: {- completedAt?: Date | null;- operationId: string;- startedAt: Date;- threadId?: string | null;- topicId: string;- }): Promise<Array<MessagePluginItem & { content?: string; createdAt: Date }>> => {- const completedAt = params.completedAt ?? new Date();-- const withinWindow = and(- eq(messages.topicId, params.topicId),- params.threadId ? eq(messages.threadId, params.threadId) : isNull(messages.threadId),- gte(messages.createdAt, params.startedAt),- lte(messages.createdAt, completedAt),- );-- // The two branches are resolved SEPARATELY β never OR-ed into one WHERE (an- // `... AND (withinWindow OR heteroMatch)` is unindexable and seq-scans every- // plugin row the user owns). They are also SHAPED differently on purpose:- //- // - Time window: one index-friendly range scan joined to its plugin rows.- // - Heterogeneous match: resolved id-FIRST, not as a plugin JOIN. The- // `metadata->>'heterogeneousToolStateOperationId'` predicate carries a 0.5%- // default selectivity estimate, so joining it to `message_plugins` makes the- // planner scan / nested-loop the user's ENTIRE plugin history (100k+ rows,- // 100s+ per call for heavy users β it returns ~0 rows but pays the full scan- // every time, since most ops never stamp the key). Looking up the few- // matching message ids in a JOIN-free query first, then fetching those rows- // by primary key, leaves the planner no join to mis-order: the lookup is- // single-table (index-served once the metadata expression is indexed; a- // bounded scan otherwise) and the fetch is a pure PK access. Kept- // topic-agnostic to preserve the prior behaviour exactly β a late CLI row- // can land outside the op's window (and, rarely, its topic).- const projection = {- apiName: messagePlugins.apiName,- arguments: messagePlugins.arguments,- clientId: messagePlugins.clientId,- // The tool message's text body. Heterogeneous CLI adapters (claude-code- // Bash) persist the command's stdout here rather than in a structured- // `state` field, and the completion-time github Work scan reads the gh- // CLI's printed entity URL from it.- content: messages.content,- createdAt: messages.createdAt,- error: messagePlugins.error,- id: messagePlugins.id,- identifier: messagePlugins.identifier,- intervention: messagePlugins.intervention,- state: messagePlugins.state,- toolCallId: messagePlugins.toolCallId,- type: messagePlugins.type,- userId: messagePlugins.userId,- };-- const scan = (condition: SQL | undefined) =>- this.db- .select(projection)- .from(messagePlugins)- .innerJoin(messages, eq(messagePlugins.id, messages.id))- .where(and(this.ownership(), this.pluginsOwnership(), condition));-- const fetchHeterogeneous = async () => {- const idRows = await this.db- .select({ id: messages.id })- .from(messages)- .where(- and(- this.ownership(),- sql`${messages.metadata}->>'heterogeneousToolStateOperationId' = ${params.operationId}`,- ),- );- const ids = idRows.map((row) => row.id);- if (ids.length === 0) return [];- return scan(inArray(messagePlugins.id, ids));- };-- const [windowRows, heterogeneousRows] = await Promise.all([- scan(withinWindow),- fetchHeterogeneous(),- ]);-- const byId = new Map<string, (typeof windowRows)[number]>();- for (const row of windowRows) byId.set(row.id, row);- for (const row of heterogeneousRows) if (!byId.has(row.id)) byId.set(row.id, row);-- const rows = [...byId.values()].sort(- (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id),- );-- return rows.map((row) => ({- apiName: row.apiName ?? undefined,- arguments: row.arguments ?? undefined,- clientId: row.clientId ?? undefined,- content: row.content ?? undefined,- createdAt: row.createdAt,- error: row.error ?? undefined,- id: row.id,- identifier: row.identifier ?? undefined,- intervention: row.intervention ?? undefined,- state: row.state ?? undefined,- toolCallId: row.toolCallId ?? undefined,- type: row.type ?? 'default',- userId: row.userId,- }));- };-- /**- * Load specific tool-call rows by their message ids, ownership-scoped and- * pinned to one topic. Serves the LOCAL hetero run work scan- * (`work.registerShellWorksForRun`): a desktop-local CLI run has no- * `agent_operations` row, so the client reports the exact tool message ids it- * persisted instead of the server reconstructing an operation window. The- * topic pin means a caller can never scan rows outside the conversation it- * claims to complete.- */- listMessagePluginsByIds = async (params: {- ids: string[];- topicId: string;- }): Promise<Array<MessagePluginItem & { content?: string; createdAt: Date }>> => {- if (params.ids.length === 0) return [];-- const rows = await this.db- .select({- apiName: messagePlugins.apiName,- arguments: messagePlugins.arguments,- clientId: messagePlugins.clientId,- // The tool message's text body β claude-code Bash persists the- // command's stdout here (see listMessagePluginsForOperation).- content: messages.content,- createdAt: messages.createdAt,- error: messagePlugins.error,- id: messagePlugins.id,- identifier: messagePlugins.identifier,- intervention: messagePlugins.intervention,- state: messagePlugins.state,- toolCallId: messagePlugins.toolCallId,- type: messagePlugins.type,- userId: messagePlugins.userId,- })- .from(messagePlugins)- .innerJoin(messages, eq(messagePlugins.id, messages.id))- .where(- and(- inArray(messagePlugins.id, params.ids),- eq(messages.topicId, params.topicId),- this.ownership(),- this.pluginsOwnership(),- // A desktop-local hetero run never happens inside an agent-share- // visitor topic, so excluding them costs nothing and stops a creator- // from surfacing a visitor's tool calls as their own Work cards.- notShareVisitorMessage(),- ),- );-- const sorted = [...rows].sort(- (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id),- );-- return sorted.map((row) => ({- apiName: row.apiName ?? undefined,- arguments: row.arguments ?? undefined,- clientId: row.clientId ?? undefined,- content: row.content ?? undefined,- createdAt: row.createdAt,- error: row.error ?? undefined,- id: row.id,- identifier: row.identifier ?? undefined,- intervention: row.intervention ?? undefined,- state: row.state ?? undefined,- toolCallId: row.toolCallId ?? undefined,- type: row.type ?? 'default',- userId: row.userId,- }));- };-- /**- * Resolve the tool result message id for a toolCallId β the stable identifier- * the model emitted for the call. Lets server-side services push async state- * onto a tool card when all they hold is the call id recorded at creation- * time (e.g. the goal loop updating the `createGoal` card via- * `task.context.origin.toolCallId`).- */- findToolMessageIdByToolCallId = async (- toolCallId: string,- /**- * Restrict the match to calls made by one assistant message.- *- * `tool_call_id` is provider-supplied and only unique in practice β the- * column carries a plain index, not a unique constraint. Callers that act- * on the row (rather than just reading it) should scope the match, or a- * reused id from another turn resolves to an unrelated historical result.- */- parentId?: string,- ): Promise<string | null> => {- const rows = parentId- ? await this.db- .select({ id: messagePlugins.id })- .from(messagePlugins)- .innerJoin(messages, eq(messages.id, messagePlugins.id))- .where(- and(- eq(messagePlugins.toolCallId, toolCallId),- eq(messages.parentId, parentId),- this.pluginsOwnership(),- ),- )- .limit(1)- : await this.db- .select({ id: messagePlugins.id })- .from(messagePlugins)- .where(and(eq(messagePlugins.toolCallId, toolCallId), this.pluginsOwnership()))- .limit(1);-- return rows[0]?.id ?? null;- };-- /**- * Update tool message with content, metadata, pluginState, and pluginError in a single transaction- * This prevents race conditions when updating multiple fields- */- updateToolMessage = async (- id: string,- params: {- content?: string;- heterogeneousToolState?: HeterogeneousToolStateSnapshot;- metadata?: Record<string, any>;- pluginError?: any;- pluginState?: Record<string, any>;- /** Replace rather than merge when withholding a complete tool result. */- replacePluginState?: boolean;- /** Finalize a deferred placeholder once; later callbacks cannot replace its result. */- onlyIfEmpty?: boolean;- },- ): Promise<{ applied: boolean; snapshotSeq?: number; success: boolean }> => {- const {- content,- heterogeneousToolState,- metadata,- pluginState,- pluginError,- replacePluginState,- } = params;-- // `undefined` while no branch has looked for the row yet; see `update` above- // for why a write that matches nothing must not report success.- let matchedRow: boolean | undefined;- let applied = true;- let snapshotSeq: number | undefined;-- try {- await this.db.transaction(async (trx) => {- if (params.onlyIfEmpty) {- const [message] = await trx- .select({ content: messages.content })- .from(messages)- .where(and(eq(messages.id, id), this.ownership()))- .for('update');- matchedRow = !!message;- if (!message) return;- if (message.content) {- applied = false;- return;- }- }-- let existingMetadata: Record<string, any> | undefined;-- if (metadata !== undefined || heterogeneousToolState !== undefined) {- const baseQuery = trx- .select({ metadata: messages.metadata })- .from(messages)- .where(and(eq(messages.id, id), this.ownership()))- .limit(1);- const [existingMessage] = heterogeneousToolState- ? await baseQuery.for('update')- : await baseQuery;-- matchedRow = !!existingMessage;- if (!existingMessage) return;-- existingMetadata = (existingMessage.metadata ?? {}) as Record<string, any>;-- if (heterogeneousToolState) {- const currentOperationId = existingMetadata.heterogeneousToolStateOperationId;- const rawCurrentSeq = existingMetadata.heterogeneousToolStateSeq;- const currentSeq =- currentOperationId === heterogeneousToolState.operationId &&- typeof rawCurrentSeq === 'number' &&- Number.isFinite(rawCurrentSeq)- ? rawCurrentSeq- : 0;-- if (heterogeneousToolState.snapshotSeq <= currentSeq) {- applied = false;- snapshotSeq = currentSeq;- return;- }-- snapshotSeq = heterogeneousToolState.snapshotSeq;- }- }-- // Update messages table (content, metadata)- if (- content !== undefined ||- metadata !== undefined ||- heterogeneousToolState !== undefined- ) {- const messageUpdateData: Record<string, any> = {};-- if (content !== undefined) {- messageUpdateData.content = sanitizeNullBytes(content);- }-- if (metadata !== undefined || heterogeneousToolState !== undefined) {- const mergedMetadata = merge(existingMetadata || {}, metadata || {});- messageUpdateData.metadata = heterogeneousToolState- ? merge(mergedMetadata, {- heterogeneousToolStateOperationId: heterogeneousToolState.operationId,- heterogeneousToolStateSeq: heterogeneousToolState.snapshotSeq,- })- : mergedMetadata;- }-- if (Object.keys(messageUpdateData).length > 0) {- const [updated] = await trx- .update(messages)- .set(messageUpdateData)- .where(and(eq(messages.id, id), this.ownership()))- .returning({ id: messages.id });-- matchedRow = !!updated;- }- }-- // Update messagePlugins table (pluginState, pluginError)- if (pluginState !== undefined || pluginError !== undefined) {- const pluginUpdateData: Record<string, any> = {};-- if (pluginState !== undefined) {- const sanitizedState = sanitizeNullBytes(pluginState);- // Snapshot writes replace the whole runtime state. Ordinary patches- // own complete top-level keys and merge inside the UPDATE so an- // answer write cannot race away an intervention-terminal write.- pluginUpdateData.state =- heterogeneousToolState || replacePluginState- ? sanitizedState- : sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(sanitizedState)}::jsonb`;- }-- if (pluginError !== undefined) {- pluginUpdateData.error = sanitizeNullBytes(pluginError);- }-- const [updatedPlugin] = await trx- .update(messagePlugins)- .set(pluginUpdateData)- .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))- .returning({ id: messagePlugins.id });-- // A plugin-only patch never touches `messages`, so the plugin row is- // the only evidence the tool message exists.- if (matchedRow === undefined) matchedRow = !!updatedPlugin;-- if (!updatedPlugin && heterogeneousToolState) {- throw new Error(`No tool plugin matched id ${id}`);- }- }- });-- if (matchedRow === false) {- console.error(`Update tool message error: no tool message matched id ${id}`);- return { applied: false, success: false };- }-- return { applied, snapshotSeq, success: true };- } catch (error) {- console.error('Update tool message error:', error);- return { applied: false, success: false };- }- };-- /**- * Update tool arguments by toolCallId - updates both tool message plugin.arguments- * and parent assistant message tools[].arguments in a single transaction- *- * This method uses toolCallId (the stable identifier from AI response) instead of- * tool message ID, which allows updating arguments even when the tool message- * hasn't been persisted yet (e.g., during intervention pending state).- *- * @param toolCallId - The tool call ID (stable identifier from AI response)- * @param args - The new arguments string (already stringified JSON)- */- updateToolArguments = async (toolCallId: string, args: string): Promise<{ success: boolean }> => {- try {- await this.db.transaction(async (trx) => {- // 1. Find tool plugin and tool message with parentId in one query- const [toolResult] = await trx- .select({- parentId: messages.parentId,- toolPluginId: messagePlugins.id,- })- .from(messagePlugins)- .innerJoin(messages, eq(messages.id, messagePlugins.id))- .where(and(eq(messagePlugins.toolCallId, toolCallId), this.ownership()))- .limit(1);-- if (!toolResult?.parentId) {- throw new Error(`No tool message found with toolCallId: ${toolCallId}`);- }-- // 2. Get parent assistant message's tools- const [parentMessage] = await trx- .select({ id: messages.id, tools: messages.tools })- .from(messages)- .where(and(eq(messages.id, toolResult.parentId), this.ownership()))- .limit(1);-- if (!parentMessage?.tools) {- throw new Error(`No parent assistant message found for toolCallId: ${toolCallId}`);- }-- const parentTools = parentMessage.tools as ChatToolPayload[];-- // 3. Update the parent assistant message's tools[].arguments- const updatedTools = parentTools.map((tool) => {- if (tool.id === toolCallId) {- return { ...tool, arguments: args };- }- return tool;- });-- // Execute both updates in parallel- await Promise.all([- // Update tool plugin arguments- trx- .update(messagePlugins)- .set({ arguments: args })- .where(and(eq(messagePlugins.id, toolResult.toolPluginId), this.pluginsOwnership())),- // Update parent assistant message's tools- trx- .update(messages)- .set({ tools: updatedTools })- .where(and(eq(messages.id, parentMessage.id), this.ownership())),- ]);- });-- return { success: true };- } catch (error) {- console.error('Update tool arguments error:', error);- return { success: false };- }- };-- /**- * Id of the latest main-thread (`threadId IS NULL`) "spine" message in a- * topic: the most recent message that is NOT a tool and NOT a signal-tagged- * reactive turn (Monitor stdout callbacks etc.). This is the chain anchor for- * the heterogeneous-agent write side: the next normal- * turn parents off it, producing a `user β asst β asst β¦` spine with tools as- * inline children.- *- * Read straight from the DB and ordered by `createdAt`, it is independent of- * the in-memory current-assistant pointer β which can regress to the run's- * seed placeholder on a cold / non-sticky serverless replica. Anchoring here- * instead keeps consecutive cold-replica steps chained linearly rather than- * forking onto a stale node (the remote "ζιΎ" bug). No `createdAt` floor is- * needed: a topic runs at most one operation at a time, so the latest spine- * message IS this run's continuation point.- *- * Excludes `role:'tool'` (inline children) and TOOLLESS signal-tagged- * assistants (`metadata->'signal'` with no tools), which are tool-child- * callbacks β anchoring a normal turn onto a callback would orphan it under- * the read side's tool-only signal collection. A signal turn that DID emit- * tools is back on the main chain and stays a spine candidate.- */- getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> =>- this.getLatestSpineMessageId({ topicId, threadId: null });-- /**- * Whether `descendantId` belongs to the branch rooted at `ancestorId`.- *- * Used when reconciling a client-selected conversation tail with the latest- * server row: a newer row may be a sibling from a historical callback fork,- * not an advancement of the branch the user is viewing.- */- isMessageDescendantOf = async ({- ancestorId,- descendantId,- topicId,- }: {- ancestorId: string;- descendantId: string;- topicId: string;- }): Promise<boolean> => {- const result = await this.db.execute(sql`- WITH RECURSIVE ancestors(id, parent_id) AS (- SELECT id, parent_id- FROM messages- WHERE id = ${descendantId}- AND topic_id = ${topicId}- AND ${this.ownership()}- UNION- SELECT parent.id, parent.parent_id- FROM messages parent- JOIN ancestors child ON parent.id = child.parent_id- WHERE parent.topic_id = ${topicId}- )- SELECT 1 AS hit FROM ancestors WHERE id = ${ancestorId} LIMIT 1- `);-- return result.rows.length > 0;- };-- /**- * Thread-aware variant of {@link getLastMainThreadSpineMessageId}: the id of- * the latest "spine" message (the most recent message that is NOT a tool and- * NOT a signal-tagged reactive turn) in a topic, scoped to the main thread- * (`threadId IS NULL`) or to a specific thread.- *- * Like the main-thread query it EXCLUDES `role:'tool'` and TOOLLESS- * signal-tagged assistants: tools are inline children of their assistant turn,- * so the conversation head a new turn parents off is the assistant, never the- * tool result that landed under it. A tools-bearing signal turn is main-chain- * and remains a spine candidate.- *- * Used by `sendMessageInServer` to make `parentId` server-authoritative and- * close the concurrent-append race: the client computes `parentId` from a- * local snapshot whose spine tail may already have advanced (e.g. another- * assistant turn was written while the user was composing), so trusting it- * would fork the new turn off a stale node. Ordering by `createdAt` is safe- * because a topic runs at most one operation at a time.- */- getLatestSpineMessageId = async ({- topicId,- threadId,- }: {- threadId?: string | null;- topicId: string;- }): Promise<string | undefined> => {- const [row] = await this.db- .select({ id: messages.id })- .from(messages)- .where(- and(- eq(messages.topicId, topicId),- not(eq(messages.role, 'tool')),- threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),- // Exclude signal-tagged assistants β BUT only the toolless ones. The- // writer tags a turn `signal` at stream_start before it knows the turn- // will call tools; a signal turn that DOES emit a tool_use is really- // back on the main chain (see `reduceToolsChunk`'s spine promotion),- // so it must stay a spine candidate or a cold replica re-forks the- // wire off the pre-signal turn. Match the read side, which likewise- // treats a tools-bearing message as non-signal (`getMessageSignal`).- //- // Key existence (`jsonb_exists`) is used instead of `metadata -> 'signal'- // IS NULL`, which crashes the serverless Postgres engine as a WHERE- // predicate (rt_fetch out-of-bounds, SQLSTATE XX000 β the `->` operator- // only survives in SELECT/ORDER BY). Toolless is expressed with plain- // jsonb equality (`= '[]'` / IS NULL) rather than `jsonb_array_length`,- // which is unproven on this engine as a qual.- sql`NOT (- COALESCE(jsonb_exists(${messages.metadata}, 'signal'), false)- AND (${messages.tools} IS NULL OR ${messages.tools} = '[]'::jsonb)- )`,- this.ownership(),- ),- )- .orderBy(desc(messages.createdAt))- .limit(1);-- return row?.id;- };-- /**- * Fallback anchor for {@link getLatestSpineMessageId}: the latest non-tool- * message in a topic/thread, WITHOUT the toolless-signal exclusion.- *- * A topic whose main thread holds nothing but toolless signal turns has no- * spine candidate, so the spine lookup returns undefined and the caller would- * persist the new turn with `parentId: undefined` β a second root that forks- * the conversation tree. The renderer walks that forest depth-first, so an- * earlier root's long-running subtree gets emitted before a later root and the- * newest reply surfaces ABOVE older messages.- *- * `role:'tool'` stays excluded: tool results are inline children of their- * assistant turn, and anchoring a normal turn onto one orphans it under the- * read side's tool-only signal collection.- */- getLatestNonToolMessageId = async ({- topicId,- threadId,- }: {- threadId?: string | null;- topicId: string;- }): Promise<string | undefined> => {- const [row] = await this.db- .select({ id: messages.id })- .from(messages)- .where(- and(- eq(messages.topicId, topicId),- not(eq(messages.role, 'tool')),- threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),- this.ownership(),- ),- )- .orderBy(desc(messages.createdAt))- .limit(1);-- return row?.id;- };-- updateTranslate = async (id: string, translate: Partial<ChatTranslate>) => {- const result = await this.db.query.messageTranslates.findFirst({- where: and(eq(messageTranslates.id, id), this.translatesOwnership()),- });-- // If the message does not exist in the translate table, insert it- if (!result) {- return this.db.insert(messageTranslates).values({- ...translate,- id,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- });- }-- // or just update the existing one- return this.db- .update(messageTranslates)- .set(translate)- .where(and(eq(messageTranslates.id, id), this.translatesOwnership()));- };-- updateTTS = async (id: string, tts: Partial<ChatTTS>) => {- const { contentMd5, file, voice } = tts;- // Older clients sent an empty payload when starting TTS, so keep this backward-compatible.- if ([contentMd5, file, voice].every((value) => value === undefined)) return;-- const result = await this.db.query.messageTTS.findFirst({- where: and(eq(messageTTS.id, id), this.ttsOwnership()),- });-- // If the message does not exist in the TTS table, insert it- if (!result) {- return this.db.insert(messageTTS).values({- contentMd5,- fileId: file,- id,- userId: this.userId,- voice,- workspaceId: this.workspaceId ?? null,- });- }-- // or just update the existing one- return this.db- .update(messageTTS)- .set({ contentMd5, fileId: file, voice })- .where(and(eq(messageTTS.id, id), this.ttsOwnership()));- };-- async updateMessageRAG(id: string, { ragQueryId, fileChunks }: UpdateMessageRAGParams) {- return this.db.insert(messageQueryChunks).values(- fileChunks.map((chunk) => ({- chunkId: chunk.id,- messageId: id,- queryId: ragQueryId,- similarity: chunk.similarity?.toString(),- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- );- }-- // **************** Delete *************** //-- /**- * Preserve the selected branch by identity across a deletion. Branch metadata- * stores a positional index, while deleting or reparenting children can change- * that index space. If the selected branch itself is deleted, remove the stale- * index so conversation-flow can infer the remaining active branch instead of- * mistaking `index === branchCount` for an optimistic branch creation.- */- private captureActiveBranchSnapshots = async (- tx: Transaction,- parentIds: string[],- ): Promise<ActiveBranchSnapshot[]> => {- const uniqueParentIds = [...new Set(parentIds)];- if (uniqueParentIds.length === 0) return [];-- const parentRows = await tx- .select({ id: messages.id, metadata: messages.metadata })- .from(messages)- .where(and(this.ownership(), inArray(messages.id, uniqueParentIds)));- const branchIdsByParent = await this.queryDirectBranchIds(tx, uniqueParentIds);- const snapshots: ActiveBranchSnapshot[] = [];-- for (const parent of parentRows) {- if (!isPlainRecord(parent.metadata)) continue;-- const activeBranchIndex = parent.metadata.activeBranchIndex;- if (typeof activeBranchIndex !== 'number' || activeBranchIndex < 0) continue;-- const branchIds = branchIdsByParent.get(parent.id) ?? [];- snapshots.push({- activeBranchId: branchIds[activeBranchIndex],- activeBranchIndex,- metadata: parent.metadata,- parentId: parent.id,- wasOptimistic: activeBranchIndex === branchIds.length,- });- }-- return snapshots;- };-- private queryDirectBranchIds = async (tx: Transaction, parentIds: string[]) => {- const branchRows = await tx- .select({ id: messages.id, parentId: messages.parentId })- .from(messages)- .where(- and(- this.ownership(),- inArray(messages.parentId, parentIds),- not(eq(messages.role, 'tool')),- ),- )- .orderBy(asc(messages.createdAt), asc(messages.id));- const branchIdsByParent = new Map<string, string[]>();-- for (const branch of branchRows) {- if (!branch.parentId) continue;- const branchIds = branchIdsByParent.get(branch.parentId) ?? [];- branchIds.push(branch.id);- branchIdsByParent.set(branch.parentId, branchIds);- }-- return branchIdsByParent;- };-- private reconcileActiveBranchSnapshots = async (- tx: Transaction,- snapshots: ActiveBranchSnapshot[],- ) => {- if (snapshots.length === 0) return;-- const branchIdsByParent = await this.queryDirectBranchIds(- tx,- snapshots.map((snapshot) => snapshot.parentId),- );-- for (const snapshot of snapshots) {- const branchIds = branchIdsByParent.get(snapshot.parentId) ?? [];- const survivingBranchIndex = snapshot.activeBranchId- ? branchIds.indexOf(snapshot.activeBranchId)- : -1;- const activeBranchIndex = snapshot.wasOptimistic- ? branchIds.length- : survivingBranchIndex >= 0- ? survivingBranchIndex- : undefined;-- if (activeBranchIndex === snapshot.activeBranchIndex) continue;-- const metadata = { ...snapshot.metadata };- delete metadata.activeBranchIndex;- if (activeBranchIndex !== undefined) metadata.activeBranchIndex = activeBranchIndex;-- await tx- .update(messages)- .set({ metadata })- .where(and(eq(messages.id, snapshot.parentId), this.ownership()));- }- };-- /**- * Delete one message (plus the tool messages it owns).- *- * Agent-share visitor messages live under the creator's `userId`, so plain- * ownership matches them: by default this refuses to touch them, which keeps- * the creator-facing `message.removeMessage` from destroying a visitor's- * conversation even when the creator obtained a raw visitor message id (e.g.- * through data export). The agent runtime β which also runs visitor turns- * under the creator's identity and must clean up its own placeholders β opts- * back in with `includeShareVisitor`.- */- deleteMessage = async (id: string, options?: ShareVisitorWriteOptions) => {- // Effective visitor gate: per-call `true` OR the instance flag widens the- // scope. Uses `workspaceScope()` (raw) so an instance-default caller can- // still opt in per-call without `ownership()` re-adding the exclusion.- const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;- const scope = includeVisitor ? this.workspaceScope() : this.ownership();-- return this.db.transaction(async (tx) => {- // 1. Query the complete information of the message to be deleted- const message = await tx- .select()- .from(messages)- .where(and(eq(messages.id, id), scope))- .limit(1);-- // If the message to be deleted is not found, return directly- if (message.length === 0) return;-- const activeBranchSnapshots = await this.captureActiveBranchSnapshots(- tx,- message[0].parentId ? [message[0].parentId] : [],- );-- // 2. Update child messages' parentId to the current message's parentId- // This preserves the tree structure when deleting a node- await tx- .update(messages)- .set({ parentId: message[0].parentId })- .where(and(eq(messages.parentId, id), scope));-- // 3. Check if the message contains tools- const toolCallIds = (message[0].tools as ChatToolPayload[])- ?.map((tool) => tool.id)- .filter(Boolean);-- let relatedMessageIds: string[] = [];-- if (toolCallIds?.length > 0) {- // 4. If the message contains tools, query all associated message ids- const res = await tx- .select({ id: messagePlugins.id })- .from(messagePlugins)- .where(inArray(messagePlugins.toolCallId, toolCallIds));-- relatedMessageIds = res.map((row) => row.id);- }-- // 5. Merge the list of message ids to be deleted- const messageIdsToDelete = [id, ...relatedMessageIds];-- // 6. Delete all related messages- await tx.delete(messages).where(and(scope, inArray(messages.id, messageIdsToDelete)));-- await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);-- // 7. Keep the topic's usage rollup in sync (pure derived β a removed- // assistant message must drop out of the topic totals).- if (message[0].topicId) {- await recomputeTopicUsage(tx, this.userId, message[0].topicId, this.workspaceId);- }- });- };-- /**- * Batch twin of {@link MessageModel.deleteMessage} β same agent-share visitor- * rule: visitor messages are skipped unless the caller explicitly opts in.- */- deleteMessages = async (ids: string[], options?: ShareVisitorWriteOptions) => {- if (ids.length === 0) return;-- const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;- const scope = includeVisitor ? this.workspaceScope() : this.ownership();-- return this.db.transaction(async (tx) => {- // 1. Query all messages to be deleted with their parentId- const toDelete = await tx- .select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId })- .from(messages)- .where(and(scope, inArray(messages.id, ids)));-- if (toDelete.length === 0) return;-- // 2. Build id -> parentId map and deleteSet- const parentMap = new Map<string, string | null>();- const deleteSet = new Set<string>();- for (const msg of toDelete) {- parentMap.set(msg.id, msg.parentId);- deleteSet.add(msg.id);- }-- // 3. Find the final ancestor for each deleted message (first ancestor not in deleteSet)- const finalAncestorMap = new Map<string, string | null>();-- const findFinalAncestor = (id: string): string | null => {- if (finalAncestorMap.has(id)) return finalAncestorMap.get(id)!;-- const parentId = parentMap.get(id);- if (parentId === null || parentId === undefined) {- finalAncestorMap.set(id, null);- return null;- }-- if (!deleteSet.has(parentId)) {- // Parent is not being deleted, it's the final ancestor- finalAncestorMap.set(id, parentId);- return parentId;- }-- // Parent is also being deleted, recursively find its ancestor- const ancestor = findFinalAncestor(parentId);- finalAncestorMap.set(id, ancestor);- return ancestor;- };-- for (const id of deleteSet) {- findFinalAncestor(id);- }-- const activeBranchSnapshots = await this.captureActiveBranchSnapshots(- tx,- [...new Set(finalAncestorMap.values())].filter((id): id is string => id !== null),- );-- // 4. Query child messages whose parentId points to messages being deleted- const children = await tx- .select({ id: messages.id, parentId: messages.parentId })- .from(messages)- .where(and(scope, inArray(messages.parentId, ids), not(inArray(messages.id, ids))));-- // 5. Update each child's parentId to the final ancestor- for (const child of children) {- const newParentId = finalAncestorMap.get(child.parentId!) ?? null;- await tx- .update(messages)- .set({ parentId: newParentId })- .where(and(eq(messages.id, child.id), scope));- }-- // 6. Delete the messages. Deletes the ids that survived the step-1- // filter, not the raw input, so a mixed batch drops only the visitor rows.- await tx.delete(messages).where(and(scope, inArray(messages.id, [...deleteSet])));-- await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);-- // 7. Recompute the usage rollup for every affected topic (pure derived).- const affectedTopicIds = [- ...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),- ];- for (const topicId of affectedTopicIds) {- await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);- }- });- };-- /**- * Add files to a message by inserting records into messagesFiles table- * This associates existing files with a message for display in fileList/imageList/videoList- */- addFiles = async (messageId: string, fileIds: string[]): Promise<{ success: boolean }> => {- if (fileIds.length === 0) return { success: true };-- // The insert below has no ownership predicate of its own, so verify the- // target message is actually visible to this user/workspace first β- // otherwise a caller could attach files to another tenant's message.- const message = await this.findById(messageId);- if (!message) return { success: false };-- try {- await this.db.insert(messagesFiles).values(- fileIds.map((fileId) => ({- fileId,- messageId,- userId: this.userId,- workspaceId: this.workspaceId ?? null,- })),- );- return { success: true };- } catch (error) {- console.error('Add files to message error:', error);- return { success: false };- }- };-- deleteMessageTranslate = async (id: string) =>- this.db- .delete(messageTranslates)- .where(and(eq(messageTranslates.id, id), this.translatesOwnership()));-- deleteMessageTTS = async (id: string) =>- this.db.delete(messageTTS).where(and(eq(messageTTS.id, id), this.ttsOwnership()));-- deleteMessageQuery = async (id: string) =>- this.db- .delete(messageQueries)- .where(- and(- eq(messageQueries.id, id),- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messageQueries,- ),- ),- );-- // **************** Recycle bin *************** //-- /**- * Move messages to the recycle bin. Mirrors {@link deleteMessages} step for- * step β tool companions are pulled in, live children are re-parented onto- * the nearest surviving ancestor, the active-branch pointer is reconciled and- * the topic usage rollup recomputed β but the rows are stamped instead of- * dropped. Returns one entry per stamped row with the tree data a restore- * needs to splice it back (`parentId` + the child ids that were re-parented- * away from it), and whether the row was an explicitly requested root or a- * tool companion pulled in with it.- */- softDeleteMessages = async (- ids: string[],- options: SoftDeleteOptions,- ): Promise<SoftDeletedMessage[]> => {- if (ids.length === 0) return [];-- return this.db.transaction(async (tx) => {- const requested = await tx- .select({- content: messages.content,- id: messages.id,- parentId: messages.parentId,- projectId: topics.projectId,- role: messages.role,- tools: messages.tools,- topicId: messages.topicId,- })- .from(messages)- .leftJoin(- topics,- and(- eq(messages.topicId, topics.id),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- ),- )- .where(and(this.ownership(), inArray(messages.id, ids)));- if (requested.length === 0) return [];-- // Tool companions: the tool-result rows of a trashed assistant turn go- // with it (same rule as the hard delete).- const toolCallIds = requested- .flatMap((row) => ((row.tools as ChatToolPayload[]) ?? []).map((tool) => tool.id))- .filter(Boolean);- const requestedIds = new Set(requested.map((row) => row.id));- // toolCallId β the requested row that issued it, so each companion is- // attributed to its own assistant turn rather than to the batch.- const toolCallOwner = new Map<string, string>();- for (const row of requested) {- for (const tool of (row.tools as ChatToolPayload[]) ?? []) {- if (tool.id) toolCallOwner.set(tool.id, row.id);- }- }- const companionOwner = new Map<string, string>();- let companions: typeof requested = [];- if (toolCallIds.length > 0) {- const companionRows = await tx- .select({ id: messagePlugins.id, toolCallId: messagePlugins.toolCallId })- .from(messagePlugins)- .where(inArray(messagePlugins.toolCallId, toolCallIds));- for (const row of companionRows) {- const owner = row.toolCallId ? toolCallOwner.get(row.toolCallId) : undefined;- if (owner && !requestedIds.has(row.id)) companionOwner.set(row.id, owner);- }- const companionIds = [...companionOwner.keys()];- if (companionIds.length > 0) {- companions = await tx- .select({- content: messages.content,- id: messages.id,- parentId: messages.parentId,- projectId: topics.projectId,- role: messages.role,- tools: messages.tools,- topicId: messages.topicId,- })- .from(messages)- .leftJoin(- topics,- and(- eq(messages.topicId, topics.id),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- ),- )- .where(and(this.ownership(), inArray(messages.id, companionIds)));- }- }-- const toDelete = [...requested, ...companions];- const deleteIds = toDelete.map((row) => row.id);- const deleteSet = new Set(deleteIds);- const parentMap = new Map(toDelete.map((row) => [row.id, row.parentId] as const));-- const finalAncestorMap = new Map<string, string | null>();- const findFinalAncestor = (id: string): string | null => {- if (finalAncestorMap.has(id)) return finalAncestorMap.get(id)!;- const parentId = parentMap.get(id);- if (parentId === null || parentId === undefined) {- finalAncestorMap.set(id, null);- return null;- }- if (!deleteSet.has(parentId)) {- finalAncestorMap.set(id, parentId);- return parentId;- }- const ancestor = findFinalAncestor(parentId);- finalAncestorMap.set(id, ancestor);- return ancestor;- };- for (const id of deleteSet) findFinalAncestor(id);-- const activeBranchSnapshots = await this.captureActiveBranchSnapshots(- tx,- [...new Set(finalAncestorMap.values())].filter((id): id is string => id !== null),- );-- // Live children re-parented onto the nearest surviving ancestor β- // remembered per message so a restore can hand them back.- const children = await tx- .select({ id: messages.id, parentId: messages.parentId })- .from(messages)- .where(- and(- this.ownership(),- inArray(messages.parentId, deleteIds),- not(inArray(messages.id, deleteIds)),- ),- );- const childIdsByParent = new Map<string, string[]>();- for (const child of children) {- const list = childIdsByParent.get(child.parentId!) ?? [];- list.push(child.id);- childIdsByParent.set(child.parentId!, list);- await tx- .update(messages)- .set({ parentId: finalAncestorMap.get(child.parentId!) ?? null })- .where(and(eq(messages.id, child.id), this.ownership()));- }-- await tx- .update(messages)- .set(trashStamp(options.deletedAt))- .where(and(this.ownership(), inArray(messages.id, deleteIds)));-- await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);-- const affectedTopicIds = [- ...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),- ];- for (const topicId of affectedTopicIds) {- await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);- }-- return toDelete.map((row) => ({- childIds: childIdsByParent.get(row.id) ?? [],- content: row.content,- id: row.id,- isCompanion: !requestedIds.has(row.id),- ownerId: companionOwner.get(row.id) ?? null,- parentId: row.parentId,- projectId: row.projectId,- role: row.role,- topicId: row.topicId,- }));- });- };-- /**- * Bring trashed messages back and splice them into their branch: the stamp- * is cleared and the children recorded at trash time are re-parented onto- * the message again (best effort β a child that has since moved or gone is- * left alone). The active-branch pointer of the parent keeps pointing at- * whatever branch is active today.- */- restoreMessages = async (- entries: { childIds?: string[]; id: string; parentId?: string | null }[],- ): Promise<string[]> => {- if (entries.length === 0) return [];- return this.db.transaction(async (tx) => {- const ids = entries.map((entry) => entry.id);- const rows = await tx- .select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId })- .from(messages)- .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));- if (rows.length === 0) return [];-- const parentIds = rows.map((row) => row.parentId).filter((id): id is string => !!id);- const activeBranchSnapshots = await this.captureActiveBranchSnapshots(tx, parentIds);-- // Report what the write restored, not what the read saw: a purge that- // commits in between leaves nothing to update, and the caller must not- // count that row as restored.- const updated = await tx- .update(messages)- .set(restoreStamp())- .where(- and(- this.trashScope(),- inArray(- messages.id,- rows.map((row) => row.id),- ),- isTrashed(messages.isDeleted),- ),- )- .returning({ id: messages.id });- const restoredIds = new Set(updated.map((row) => row.id));-- for (const entry of entries) {- if (!restoredIds.has(entry.id) || !entry.childIds?.length) continue;- await tx- .update(messages)- .set({ parentId: entry.id })- .where(and(inArray(messages.id, entry.childIds), this.trashScope()));- }-- // While the row was in the bin its children hung off its parent, and the- // user may have picked one of them as the active branch there. They now- // move back under the restored row, so carry that choice up to it β- // otherwise reconciliation cannot find the child among the parent's- // branches, drops the selection and the view can jump to a sibling.- const restoredAncestorOf = new Map<string, string>();- for (const entry of entries) {- if (!restoredIds.has(entry.id)) continue;- for (const childId of entry.childIds ?? []) restoredAncestorOf.set(childId, entry.id);- }- for (const snapshot of activeBranchSnapshots) {- const ancestor = snapshot.activeBranchId && restoredAncestorOf.get(snapshot.activeBranchId);- if (ancestor) snapshot.activeBranchId = ancestor;- }-- await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);-- const affectedTopicIds = [...new Set(rows.map((m) => m.topicId).filter(Boolean) as string[])];- for (const topicId of affectedTopicIds) {- await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);- }- return [...restoredIds];- });- };-- findTrashedByIds = async (ids: string[]) => {- if (ids.length === 0) return [];- return this.db- .select({- agentId: messages.agentId,- id: messages.id,- parentId: messages.parentId,- sessionId: messages.sessionId,- topicId: messages.topicId,- })- .from(messages)- .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));- };-- /**- * Cascade helper for trashing an agent: stamps the live messages that hang- * off the given agents or their legacy session shells WITHOUT a topic. Rows- * inside a topic are hidden by that topic's own stamp; topic-less rows have- * no parent to hide them (`workspaceScope()` treats them as live), so they- * are stamped directly and registered as the agent's children. Their branch- * stays intact, so a plain restore of the same ids brings them back.- */- softDeleteTopicless = async (- parents: { agentIds?: string[]; sessionIds?: string[] },- options: SoftDeleteOptions,- ) => {- const conditions: SQL[] = [];- if (parents.agentIds?.length) conditions.push(inArray(messages.agentId, parents.agentIds));- if (parents.sessionIds?.length)- conditions.push(inArray(messages.sessionId, parents.sessionIds));- if (conditions.length === 0) return [];-- return this.db- .update(messages)- .set(trashStamp(options.deletedAt))- .where(and(isNull(messages.topicId), or(...conditions), this.ownership()))- .returning({ content: messages.content, id: messages.id, role: messages.role });- };-- /**- * Hard delete for the purge sweep. Children were already re-parented at trash- * time and usage already excludes stamped rows, so this is a plain delete- * keyed on `scope()`.- */- purgeMessages = async (ids: string[]) => {- if (ids.length === 0) return;- // Only rows still stamped: a restore that commits between the purge's- // registry read and this delete must win.- return this.db- .delete(messages)- .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));- };-- /**- * Creator-facing "clear this session/topic/group" sweep.- *- * Agent-share visitor messages live under the creator's `userId` but are- * hidden from every creator-facing listing (see `notShareVisitorMessage` in- * `../utils/shareVisitor`), so an id-less sweep must not destroy them β- * same rule as {@link deleteAllMessages}. Runtime cleanup opts back in via- * `includeShareVisitor`.- */- deleteMessagesBySession = async (- sessionId?: string | null,- topicId?: string | null,- groupId?: string | null,- options?: ShareVisitorWriteOptions,- ) => {- const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;- const scope = includeVisitor ? this.workspaceScope() : this.ownership();-- return this.db- .delete(messages)- .where(- and(- scope,- this.matchSession(sessionId),- this.matchTopic(topicId),- this.matchGroup(groupId),- ),- );- };-- /**- * Creator-facing "clear all my messages".- *- * Agent-share visitor messages are stored under the creator's `userId` but- * are hidden from every creator-facing listing (see `notShareVisitorMessage`- * in `../utils/shareVisitor`), so an id-less sweep must not destroy them β- * "clear all" can only mean the rows the creator can actually see. Id-targeted- * deletes ({@link MessageModel.deleteMessage}, {@link MessageModel.deleteMessages})- * apply the same guard by default β a creator can obtain visitor ids out of- * band (data export), so "the caller named the id" is not proof the row is- * theirs to delete. Runtime cleanup opts back in via `includeShareVisitor`.- */- deleteAllMessages = async () => {- return this.db.delete(messages).where(and(this.ownership(), notShareVisitorMessage()));- };-- /**- * Deletes multiple messages based on the agentId.- * This will delete messages that have either:- * 1. Direct agentId match (new data)- * 2. SessionId match via agentsToSessions lookup (legacy data)- *- * This is the creator's "clear this agent's messages" action, so visitor- * messages are excluded (see {@link deleteAllMessages}). Deleting the agent- * itself is a different path: `messages.agent_id` / `topics.agent_id` cascade- * at the DB level, so visitor rows do go away with the agent.- */- batchDeleteByAgentId = async (agentId: string) => {- // Get the associated sessionId for backward compatibility with legacy data- const agentSession = await this.db- .select({ sessionId: agentsToSessions.sessionId })- .from(agentsToSessions)- .where(and(eq(agentsToSessions.agentId, agentId), this.agentsToSessionsOwnership()))- .limit(1);-- const associatedSessionId = agentSession[0]?.sessionId;-- // Build condition to match both new (agentId) and legacy (sessionId) data- const agentCondition = associatedSessionId- ? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))- : eq(messages.agentId, agentId);-- return this.db- .delete(messages)- .where(and(this.ownership(), agentCondition, notShareVisitorMessage()));- };-- // **************** Helper *************** //-- // 18-char hash (was 14): widen the message id space β the coordinator-driven- // hetero subagent flow allocates many ids per run, and a few extra chars keep- // collision odds negligible at that volume.- private genId = () => idGenerator('messages', 18);-- private matchSession = (sessionId?: string | null) => {- if (sessionId === INBOX_SESSION_ID) return isNull(messages.sessionId);-- return sessionId ? eq(messages.sessionId, sessionId) : isNull(messages.sessionId);- };-- private matchTopic = (topicId?: string | null) =>- topicId ? eq(messages.topicId, topicId) : isNull(messages.topicId);-- private matchGroup = (groupId?: string | null) =>- groupId ? eq(messages.groupId, groupId) : isNull(messages.groupId);-- private matchThread = (threadId?: string | null) => {- if (!!threadId) return eq(messages.threadId, threadId);- return isNull(messages.threadId);- };-- /**- * Check which user IDs from the given list have at least one message.- */- static checkUsersHaveMessages = async (- db: LobeChatDatabase,- userIds: string[],- ): Promise<Set<string>> => {- if (userIds.length === 0) return new Set();- const result = await db- .select({ userId: messages.userId })- .from(messages)- .where(inArray(messages.userId, userIds))- .groupBy(messages.userId);- return new Set(result.map((r) => r.userId));- };-}diff --git a/packages/database/src/models/message/analytics.ts b/packages/database/src/models/message/analytics.tsnew file mode 100644index 00000000000..606a9e23d3c--- /dev/null+++ b/packages/database/src/models/message/analytics.ts@@ -0,0 +1,463 @@+import type { DBMessageItem, ModelRankItem } from '@lobechat/types';+import type { HeatmapsProps } from '@lobehub/charts';+import dayjs from 'dayjs';+import { and, asc, count, desc, eq, getTableColumns, gt, isNotNull, sql } from 'drizzle-orm';++import { today } from '@/utils/time';++import { agents, messages } from '../../schemas';+import { notCopiedTranscript } from '../../utils/copiedTranscript';+import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../../utils/genWhere';+import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { MessageScope } from './scope';+import type { MessageAnalyticsFilters, TopicMessageCountItem, TopicMessageStats } from './types';++/**+ * Linear-interpolation percentile over an ascending-sorted array, matching+ * PostgreSQL's `percentile_cont`. Returns 0 for an empty input.+ */+const percentileCont = (sorted: number[], q: number): number => {+ const n = sorted.length;+ if (n === 0) return 0;+ if (n === 1) return sorted[0];+ const rank = q * (n - 1);+ const lo = Math.floor(rank);+ const hi = Math.ceil(rank);+ if (lo === hi) return sorted[lo];+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (rank - lo);+};++/** Reduce a list of per-topic message counts into a {@link TopicMessageStats}. */+const computeTopicMessageStats = (counts: number[]): TopicMessageStats => {+ const topics = counts.length;+ if (topics === 0) {+ return {+ histogram: [],+ max: 0,+ mean: 0,+ median: 0,+ min: 0,+ oneshot: 0,+ oneshotRatio: 0,+ p90: 0,+ p99: 0,+ topics: 0,+ totalMessages: 0,+ };+ }++ const sorted = [...counts].sort((a, b) => a - b);+ const totalMessages = sorted.reduce((acc, c) => acc + c, 0);+ const oneshot = sorted.filter((c) => c === 1).length;++ const bucket = new Map<number, number>();+ for (const c of sorted) bucket.set(c, (bucket.get(c) ?? 0) + 1);+ const histogram = [...bucket.entries()]+ .sort(([a], [b]) => a - b)+ .map(([userCount, topicCount]) => ({ topics: topicCount, userCount }));++ return {+ histogram,+ max: sorted[topics - 1],+ mean: totalMessages / topics,+ median: percentileCont(sorted, 0.5),+ min: sorted[0],+ oneshot,+ oneshotRatio: oneshot / topics,+ p90: percentileCont(sorted, 0.9),+ p99: percentileCont(sorted, 0.99),+ topics,+ totalMessages,+ };+};++export class MessageAnalyticsQueries extends MessageScope {+ /**+ * Full creator-facing message dump (`getAllMessages` / CLI export), so+ * agent-share visitor messages must be excluded like every other+ * creator-facing listing. The exclusion rides on+ * {@link MessageModel.analyticsConditions}, which already ANDs+ * `notShareVisitorMessage()` β see `../utils/shareVisitor`.+ */+ queryAll = async (params?: MessageAnalyticsFilters & { current?: number; pageSize?: number }) => {+ const { current = 0, pageSize = 100, ...filters } = params ?? {};+ const offset = current * pageSize;++ const result = await this.db+ .select({+ ...getTableColumns(messages),+ agentName: agents.name,+ agentTitle: agents.title,+ })+ .from(messages)+ .leftJoin(agents, eq(messages.agentId, agents.id))+ .where(genWhere(this.analyticsConditions(filters)))+ .orderBy(desc(messages.createdAt))+ .limit(pageSize)+ .offset(offset);++ return result as (DBMessageItem & {+ agentName: string | null;+ agentTitle: string | null;+ })[];+ };++ /**+ * Ownership-scoped analytics filter conditions, shared by count /+ * countGroupByTopic / topicMessageStats. The first entry is always the+ * `userId Γ workspace` ownership predicate; later entries are optional.+ * Agent-share visitor messages carry the creator's `userId`, so personal+ * analytics must exclude them (visitor usage is reported separately by the+ * share usage center) β see `notShareVisitorMessage` in `../utils/shareVisitor`.+ *+ * MUST NOT be applied to {@link countByTopic} β see that method's JSDoc for+ * why exact per-topic turn counting needs the visitor topic's own messages.+ */+ private analyticsConditions = (params?: MessageAnalyticsFilters) => [+ this.ownership(),+ notShareVisitorMessage(),+ params?.agentId ? eq(messages.agentId, params.agentId) : undefined,+ params?.topicId ? eq(messages.topicId, params.topicId) : undefined,+ params?.role ? eq(messages.role, params.role) : undefined,+ params?.range+ ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())+ : undefined,+ params?.endDate+ ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())+ : undefined,+ params?.startDate+ ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())+ : undefined,+ ];++ count = async (params?: MessageAnalyticsFilters): Promise<number> => {+ const result = await this.db+ .select({+ count: count(messages.id),+ })+ .from(messages)+ .where(genWhere(this.analyticsConditions(params)));++ return result[0].count;+ };++ /**+ * Approximate variant of {@link count} for dashboard totals. An exact+ * COUNT over `messages` heap-fetches every row the user owns (tens of+ * seconds for accounts with 100k+ messages), which no stats card needs.+ *+ * Strategy: ask the planner for a row estimate first (EXPLAIN, a few ms).+ * Accounts the estimate marks as clearly heavy get the estimate, rounded+ * to 3 significant digits so the number reads as the approximation it is.+ * Everyone else β the vast majority β gets an exact count capped at+ * `cap + 1` rows, which is cheap at that size. A user the planner+ * underestimates still can't get a value below what the capped scan saw.+ * Parallel workers are disabled for the EXPLAIN because parallel plans+ * report per-worker row estimates, not totals.+ */+ countApproximate = async (+ params?: MessageAnalyticsFilters,+ { cap = 10_000 }: { cap?: number } = {},+ ): Promise<number> => {+ const where = genWhere(this.analyticsConditions(params));++ const roundEstimate = (estimate: number) => {+ const magnitude = 10 ** Math.max(0, Math.floor(Math.log10(estimate)) - 2);+ return Math.round(estimate / magnitude) * magnitude;+ };++ let estimate: number | undefined;+ try {+ const estimateQuery = this.db.select({ id: messages.id }).from(messages).where(where);+ const result = await this.db.transaction(async (trx) => {+ await trx.execute(sql`SET LOCAL max_parallel_workers_per_gather = 0`);+ return trx.execute(sql`EXPLAIN (FORMAT JSON) ${estimateQuery.getSQL()}`);+ });+ const rawPlan = result.rows[0]?.['QUERY PLAN'];+ const parsed = typeof rawPlan === 'string' ? JSON.parse(rawPlan) : rawPlan;+ const parsedRows = Number((parsed as any)?.[0]?.['Plan']?.['Plan Rows']);+ if (Number.isFinite(parsedRows)) estimate = parsedRows;+ } catch (error) {+ // Best-effort β fall through to the capped exact count, but surface the+ // degradation: past-cap accounts will all read as `cap + 1` until fixed.+ console.error('countApproximate: planner estimate failed, using capped count only:', error);+ }++ if (estimate !== undefined && estimate > cap * 2) return roundEstimate(estimate);++ const cappedRows = this.db+ .select({ id: messages.id })+ .from(messages)+ .where(where)+ .limit(cap + 1)+ .as('capped');+ const capped = await this.db.select({ count: count() }).from(cappedRows);+ const exact = capped[0].count;+ if (exact <= cap) return exact;++ return Math.max(estimate === undefined ? 0 : roundEstimate(estimate), exact);+ };++ /**+ * Count matching messages grouped by topic, sorted by count desc.+ * Topics without a `topicId` are excluded. Pushes the GROUP BY to the DB+ * so callers don't have to paginate raw rows and count client-side.+ */+ countGroupByTopic = async (+ params?: MessageAnalyticsFilters,+ ): Promise<TopicMessageCountItem[]> => {+ const rows = await this.db+ .select({+ count: count(messages.id),+ topicId: messages.topicId,+ })+ .from(messages)+ .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))+ .groupBy(messages.topicId)+ .orderBy(desc(sql`count`), asc(messages.topicId));++ return rows.map((r) => ({ count: r.count, topicId: r.topicId! }));+ };++ /**+ * Distribution of message counts per topic (topics / mean / median /+ * p90 / p99 / min / max / one-shot ratio + histogram). The per-topic+ * counts are aggregated in the DB; only the final summary is returned.+ */+ topicMessageStats = async (params?: MessageAnalyticsFilters): Promise<TopicMessageStats> => {+ const rows = await this.db+ .select({+ count: count(messages.id),+ topicId: messages.topicId,+ })+ .from(messages)+ .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))+ .groupBy(messages.topicId);++ return computeTopicMessageStats(rows.map((r) => r.count));+ };++ hasTopicMessages = async (topicId: string): Promise<boolean> => {+ const rows = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(and(eq(messages.topicId, topicId), this.ownership()))+ .limit(1);++ return rows.length > 0;+ };++ findFirstAssistantInTopic = async (topicId: string): Promise<DBMessageItem | undefined> => {+ const rows = (await this.db+ .select()+ .from(messages)+ .where(and(eq(messages.topicId, topicId), eq(messages.role, 'assistant'), this.ownership()))+ .orderBy(asc(messages.createdAt))+ .limit(1)) as DBMessageItem[];++ return rows[0];+ };++ countWords = async (params?: {+ endDate?: string;+ range?: [string, string];+ startDate?: string;+ }): Promise<number> => {+ const result = await this.db+ .select({+ count: sql<string>`sum(length(${messages.content}))`.as('total_length'),+ })+ .from(messages)+ .where(+ genWhere([+ this.ownership(),+ notShareVisitorMessage(),+ params?.range+ ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())+ : undefined,+ params?.endDate+ ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())+ : undefined,+ params?.startDate+ ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())+ : undefined,+ ]),+ );++ return Number(result[0].count);+ };++ rankModels = async (limit: number = 10): Promise<ModelRankItem[]> => {+ return this.db+ .select({+ count: count(messages.id).as('count'),+ id: messages.model,+ })+ .from(messages)+ .where(+ and(+ this.ownership(),+ notShareVisitorMessage(),+ isNotNull(messages.model),+ notCopiedTranscript(),+ ),+ )+ .having(({ count }) => gt(count, 0))+ .groupBy(messages.model)+ .orderBy(desc(sql`count`), asc(messages.model))+ .limit(limit);+ };++ getHeatmaps = async (): Promise<HeatmapsProps['data']> => {+ const startDate = today().subtract(1, 'year').startOf('day');+ const endDate = today().endOf('day');++ const result = await this.db+ .select({+ count: count(messages.id),+ date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),+ })+ .from(messages)+ .where(+ genWhere([+ this.ownership(),+ notShareVisitorMessage(),+ genRangeWhere(+ [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],+ messages.createdAt,+ (date) => date.toDate(),+ ),+ ]),+ )+ .groupBy(sql`heatmaps_date`)+ .orderBy(desc(sql`heatmaps_date`));++ const heatmapData: HeatmapsProps['data'] = [];+ let currentDate = startDate.clone();++ const dateCountMap = new Map<string, number>();+ for (const item of result) {+ if (item?.date) {+ const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');+ dateCountMap.set(dateStr, item.count);+ }+ }++ while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {+ const formattedDate = currentDate.format('YYYY-MM-DD');+ const count = dateCountMap.get(formattedDate) || 0;++ const levelCount = count > 0 ? Math.ceil(count / 5) : 0;+ const level = levelCount > 4 ? 4 : levelCount;++ heatmapData.push({+ count,+ date: formattedDate,+ level,+ });++ currentDate = currentDate.add(1, 'day');+ }++ return heatmapData;+ };++ /**+ * Daily token-usage heatmap for the last year.+ *+ * Sums `usage.totalTokens` of assistant messages bucketed by the day each+ * message was created β so tokens land on the day they were actually consumed+ * (a long-running topic spreads across days instead of piling onto its+ * creation date). Reads prefer the dedicated `usage` column and fall back to+ * legacy `metadata.usage`, aggregating directly in SQL rather than pulling+ * rows into JS. `level` is scaled relative to the busiest day so the heatmap+ * stays readable regardless of absolute token volume.+ */+ getTokenHeatmaps = async (): Promise<HeatmapsProps['data']> => {+ const startDate = today().subtract(1, 'year').startOf('day');+ const endDate = today().endOf('day');++ const result = await this.db+ .select({+ date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),+ tokens:+ sql<number>`COALESCE(SUM((COALESCE(${messages.usage}, ${messages.metadata}->'usage')->>'totalTokens')::numeric), 0)`.mapWith(+ Number,+ ),+ })+ .from(messages)+ .where(+ genWhere([+ this.ownership(),+ notShareVisitorMessage(),+ eq(messages.role, 'assistant'),+ notCopiedTranscript(),+ genRangeWhere(+ [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],+ messages.createdAt,+ (date) => date.toDate(),+ ),+ ]),+ )+ .groupBy(sql`heatmaps_date`)+ .orderBy(desc(sql`heatmaps_date`));++ const dateTokenMap = new Map<string, number>();+ let maxTokens = 0;+ for (const item of result) {+ if (item?.date) {+ const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');+ const tokens = item.tokens || 0;+ dateTokenMap.set(dateStr, tokens);+ if (tokens > maxTokens) maxTokens = tokens;+ }+ }++ const heatmapData: HeatmapsProps['data'] = [];+ let currentDate = startDate.clone();++ while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {+ const formattedDate = currentDate.format('YYYY-MM-DD');+ const tokens = dateTokenMap.get(formattedDate) || 0;++ // Scale to 1-4 relative to the busiest day; 0 tokens stays at level 0.+ const level =+ tokens > 0 && maxTokens > 0+ ? Math.min(4, Math.max(1, Math.ceil((tokens / maxTokens) * 4)))+ : 0;++ heatmapData.push({+ count: tokens,+ date: formattedDate,+ level,+ });++ currentDate = currentDate.add(1, 'day');+ }++ return heatmapData;+ };++ hasMoreThanN = async (n: number): Promise<boolean> => {+ const result = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(and(this.ownership()))+ .limit(n + 1);++ return result.length > n;+ };++ /**+ * Count messages up to a limit, useful for avoiding full table scans+ */+ countUpTo = async (n: number): Promise<number> => {+ const result = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(and(this.ownership()))+ .limit(n);++ return result.length;+ };+}diff --git a/packages/database/src/models/message/annotation.ts b/packages/database/src/models/message/annotation.tsnew file mode 100644index 00000000000..e154a4e69b1--- /dev/null+++ b/packages/database/src/models/message/annotation.ts@@ -0,0 +1,136 @@+import type { ChatTranslate, ChatTTS, UpdateMessageRAGParams } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import {+ messageQueries,+ messageQueryChunks,+ messagesFiles,+ messageTranslates,+ messageTTS,+} from '../../schemas';+import { buildWorkspaceWhere } from '../../utils/workspace';+import type { MessageLookupQueries } from './lookup';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';++export class MessageAnnotationMutations extends MessageScope {+ private readonly lookups: MessageLookupQueries;++ constructor(args: MessageScopeArgs, deps: { lookups: MessageLookupQueries }) {+ super(...args);+ this.lookups = deps.lookups;+ }++ updateTranslate = async (id: string, translate: Partial<ChatTranslate>) => {+ const result = await this.db.query.messageTranslates.findFirst({+ where: and(eq(messageTranslates.id, id), this.translatesOwnership()),+ });++ // If the message does not exist in the translate table, insert it+ if (!result) {+ return this.db.insert(messageTranslates).values({+ ...translate,+ id,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ });+ }++ // or just update the existing one+ return this.db+ .update(messageTranslates)+ .set(translate)+ .where(and(eq(messageTranslates.id, id), this.translatesOwnership()));+ };++ updateTTS = async (id: string, tts: Partial<ChatTTS>) => {+ const { contentMd5, file, voice } = tts;+ // Older clients sent an empty payload when starting TTS, so keep this backward-compatible.+ if ([contentMd5, file, voice].every((value) => value === undefined)) return;++ const result = await this.db.query.messageTTS.findFirst({+ where: and(eq(messageTTS.id, id), this.ttsOwnership()),+ });++ // If the message does not exist in the TTS table, insert it+ if (!result) {+ return this.db.insert(messageTTS).values({+ contentMd5,+ fileId: file,+ id,+ userId: this.userId,+ voice,+ workspaceId: this.workspaceId ?? null,+ });+ }++ // or just update the existing one+ return this.db+ .update(messageTTS)+ .set({ contentMd5, fileId: file, voice })+ .where(and(eq(messageTTS.id, id), this.ttsOwnership()));+ };++ async updateMessageRAG(id: string, { ragQueryId, fileChunks }: UpdateMessageRAGParams) {+ return this.db.insert(messageQueryChunks).values(+ fileChunks.map((chunk) => ({+ chunkId: chunk.id,+ messageId: id,+ queryId: ragQueryId,+ similarity: chunk.similarity?.toString(),+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ );+ }++ /**+ * Add files to a message by inserting records into messagesFiles table+ * This associates existing files with a message for display in fileList/imageList/videoList+ */+ addFiles = async (messageId: string, fileIds: string[]): Promise<{ success: boolean }> => {+ if (fileIds.length === 0) return { success: true };++ // The insert below has no ownership predicate of its own, so verify the+ // target message is actually visible to this user/workspace first β+ // otherwise a caller could attach files to another tenant's message.+ const message = await this.lookups.findById(messageId);+ if (!message) return { success: false };++ try {+ await this.db.insert(messagesFiles).values(+ fileIds.map((fileId) => ({+ fileId,+ messageId,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ );+ return { success: true };+ } catch (error) {+ console.error('Add files to message error:', error);+ return { success: false };+ }+ };++ deleteMessageTranslate = async (id: string) =>+ this.db+ .delete(messageTranslates)+ .where(and(eq(messageTranslates.id, id), this.translatesOwnership()));++ deleteMessageTTS = async (id: string) =>+ this.db.delete(messageTTS).where(and(eq(messageTTS.id, id), this.ttsOwnership()));++ deleteMessageQuery = async (id: string) =>+ this.db+ .delete(messageQueries)+ .where(+ and(+ eq(messageQueries.id, id),+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messageQueries,+ ),+ ),+ );+}diff --git a/packages/database/src/models/message/attachments.ts b/packages/database/src/models/message/attachments.tsnew file mode 100644index 00000000000..dd806a41687--- /dev/null+++ b/packages/database/src/models/message/attachments.ts@@ -0,0 +1,119 @@+import type { ChatAudioItem, ChatImageItem } from '@lobechat/types';+import { readAudioDurationMs } from '@lobechat/utils';+import { isPlainRecord } from '@lobechat/utils/object';+import { asc } from 'drizzle-orm';++import { documents } from '../../schemas';+import { documentOriginalCharCount } from '../../utils/originalCharCount';++/**+ * Max concurrent `postProcessUrl` calls (file URL presign/transform) while+ * hydrating the attachments of a message page.+ */+export const FILE_URL_POST_PROCESS_CONCURRENCY = 10;++export const fileDocumentColumns = {+ content: documents.content,+ fileId: documents.fileId,+ originalCharCount: documentOriginalCharCount().mapWith(Number),+};++/**+ * A file can own more than one document (`parseDocument` writes a page-editor copy next to the parse+ * cache). Every reader picks the oldest, matching `DocumentModel.findByFileId`, so a preview and the+ * `readAttachment` pages that continue it come from the same text.+ */+export const fileDocumentsOrder = [asc(documents.createdAt), asc(documents.id)];++export type FileDocumentsMap = Record<string, { content: string; originalCharCount?: number }>;++export const toFileDocumentsMap = (+ rows: { content: string | null; fileId: string | null; originalCharCount: number | null }[],+): FileDocumentsMap =>+ rows.reduce<FileDocumentsMap>((acc, doc) => {+ // Rows arrive oldest first (see `fileDocumentsOrder`); keep the first so the prompt shows the+ // same document `DocumentModel.findByFileId` β and therefore `readAttachment` β pages through.+ if (doc.fileId && !(doc.fileId in acc)) {+ acc[doc.fileId] = {+ content: doc.content as string,+ originalCharCount: doc.originalCharCount ?? undefined,+ };+ }+ return acc;+ }, {});++export const createChatImageItem = ({+ fileType,+ id,+ metadata,+ name,+ url,+}: {+ fileType?: string | null;+ id: string;+ metadata: unknown;+ name: string;+ url: string;+}): ChatImageItem => {+ const imageMetadata = isPlainRecord(metadata) ? metadata : {};+ const toPositiveNumber = (value: unknown) =>+ typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;+ const height = toPositiveNumber(imageMetadata.height);+ const ratio = toPositiveNumber(imageMetadata.ratio);+ const width = toPositiveNumber(imageMetadata.width);++ return {+ alt: name,+ ...(height && { height }),+ id,+ ...(fileType && { mimeType: fileType }),+ ...(ratio && { ratio }),+ url,+ ...(width && { width }),+ };+};++/**+ * Read the operation-final Work root id stamped on a message's metadata by the+ * Work registry (`metadata.work.rootOperationId`). Mirrors the client-side+ * `getOperationFinalRootId` without importing from the app layer.+ */+export const getMessageWorkRootId = (metadata: unknown): string | undefined => {+ const rootOperationId = (metadata as { work?: { rootOperationId?: unknown } } | null)?.work+ ?.rootOperationId;+ return typeof rootOperationId === 'string' && rootOperationId ? rootOperationId : undefined;+};++export interface MessageRelatedFile {+ fileType: string | null;+ id: string;+ messageId: string;+ metadata: unknown;+ name: string | null;+ size: number | null;+ url: string;+}++export const materializeChatAudioItem = ({+ fileType,+ id,+ metadata,+ name,+ url,+}: MessageRelatedFile): ChatAudioItem => {+ const value = isPlainRecord(metadata) ? metadata : {};+ const durationMs = readAudioDurationMs(metadata);++ return {+ alt: name!,+ ...(typeof value.codec === 'string' ? { codec: value.codec } : {}),+ ...(durationMs === undefined ? {} : { durationMs }),+ id,+ ...(typeof value.mimeType === 'string'+ ? { mimeType: value.mimeType }+ : fileType+ ? { mimeType: fileType }+ : {}),+ url,+ };+};diff --git a/packages/database/src/models/message/branchSnapshots.ts b/packages/database/src/models/message/branchSnapshots.tsnew file mode 100644index 00000000000..49e56a7b86c--- /dev/null+++ b/packages/database/src/models/message/branchSnapshots.ts@@ -0,0 +1,112 @@+import { isPlainRecord } from '@lobechat/utils/object';+import { and, asc, eq, inArray, not } from 'drizzle-orm';++import { messages } from '../../schemas';+import type { Transaction } from '../../type';+import { MessageScope } from './scope';++interface ActiveBranchSnapshot {+ activeBranchId?: string;+ activeBranchIndex: number;+ metadata: Record<PropertyKey, unknown>;+ parentId: string;+ wasOptimistic: boolean;+}++export class MessageBranchSnapshots extends MessageScope {+ /**+ * Preserve the selected branch by identity across a deletion. Branch metadata+ * stores a positional index, while deleting or reparenting children can change+ * that index space. If the selected branch itself is deleted, remove the stale+ * index so conversation-flow can infer the remaining active branch instead of+ * mistaking `index === branchCount` for an optimistic branch creation.+ */+ captureActiveBranchSnapshots = async (+ tx: Transaction,+ parentIds: string[],+ ): Promise<ActiveBranchSnapshot[]> => {+ const uniqueParentIds = [...new Set(parentIds)];+ if (uniqueParentIds.length === 0) return [];++ const parentRows = await tx+ .select({ id: messages.id, metadata: messages.metadata })+ .from(messages)+ .where(and(this.ownership(), inArray(messages.id, uniqueParentIds)));+ const branchIdsByParent = await this.queryDirectBranchIds(tx, uniqueParentIds);+ const snapshots: ActiveBranchSnapshot[] = [];++ for (const parent of parentRows) {+ if (!isPlainRecord(parent.metadata)) continue;++ const activeBranchIndex = parent.metadata.activeBranchIndex;+ if (typeof activeBranchIndex !== 'number' || activeBranchIndex < 0) continue;++ const branchIds = branchIdsByParent.get(parent.id) ?? [];+ snapshots.push({+ activeBranchId: branchIds[activeBranchIndex],+ activeBranchIndex,+ metadata: parent.metadata,+ parentId: parent.id,+ wasOptimistic: activeBranchIndex === branchIds.length,+ });+ }++ return snapshots;+ };++ private queryDirectBranchIds = async (tx: Transaction, parentIds: string[]) => {+ const branchRows = await tx+ .select({ id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(+ and(+ this.ownership(),+ inArray(messages.parentId, parentIds),+ not(eq(messages.role, 'tool')),+ ),+ )+ .orderBy(asc(messages.createdAt), asc(messages.id));+ const branchIdsByParent = new Map<string, string[]>();++ for (const branch of branchRows) {+ if (!branch.parentId) continue;+ const branchIds = branchIdsByParent.get(branch.parentId) ?? [];+ branchIds.push(branch.id);+ branchIdsByParent.set(branch.parentId, branchIds);+ }++ return branchIdsByParent;+ };++ reconcileActiveBranchSnapshots = async (tx: Transaction, snapshots: ActiveBranchSnapshot[]) => {+ if (snapshots.length === 0) return;++ const branchIdsByParent = await this.queryDirectBranchIds(+ tx,+ snapshots.map((snapshot) => snapshot.parentId),+ );++ for (const snapshot of snapshots) {+ const branchIds = branchIdsByParent.get(snapshot.parentId) ?? [];+ const survivingBranchIndex = snapshot.activeBranchId+ ? branchIds.indexOf(snapshot.activeBranchId)+ : -1;+ const activeBranchIndex = snapshot.wasOptimistic+ ? branchIds.length+ : survivingBranchIndex >= 0+ ? survivingBranchIndex+ : undefined;++ if (activeBranchIndex === snapshot.activeBranchIndex) continue;++ const metadata = { ...snapshot.metadata };+ delete metadata.activeBranchIndex;+ if (activeBranchIndex !== undefined) metadata.activeBranchIndex = activeBranchIndex;++ await tx+ .update(messages)+ .set({ metadata })+ .where(and(eq(messages.id, snapshot.parentId), this.ownership()));+ }+ };+}diff --git a/packages/database/src/models/message/delete.ts b/packages/database/src/models/message/delete.tsnew file mode 100644index 00000000000..2ba93440a23--- /dev/null+++ b/packages/database/src/models/message/delete.ts@@ -0,0 +1,261 @@+import type { ChatToolPayload } from '@lobechat/types';+import { and, eq, inArray, not, or } from 'drizzle-orm';++import { agentsToSessions, messagePlugins, messages } from '../../schemas';+import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { recomputeTopicUsage } from '../topicUsage';+import type { MessageBranchSnapshots } from './branchSnapshots';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';+import type { ShareVisitorWriteOptions } from './types';++export class MessageDeleteMutations extends MessageScope {+ private readonly snapshots: MessageBranchSnapshots;++ constructor(args: MessageScopeArgs, deps: { snapshots: MessageBranchSnapshots }) {+ super(...args);+ this.snapshots = deps.snapshots;+ }++ /**+ * Delete one message (plus the tool messages it owns).+ *+ * Agent-share visitor messages live under the creator's `userId`, so plain+ * ownership matches them: by default this refuses to touch them, which keeps+ * the creator-facing `message.removeMessage` from destroying a visitor's+ * conversation even when the creator obtained a raw visitor message id (e.g.+ * through data export). The agent runtime β which also runs visitor turns+ * under the creator's identity and must clean up its own placeholders β opts+ * back in with `includeShareVisitor`.+ */+ deleteMessage = async (id: string, options?: ShareVisitorWriteOptions) => {+ // Effective visitor gate: per-call `true` OR the instance flag widens the+ // scope. Uses `workspaceScope()` (raw) so an instance-default caller can+ // still opt in per-call without `ownership()` re-adding the exclusion.+ const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;+ const scope = includeVisitor ? this.workspaceScope() : this.ownership();++ return this.db.transaction(async (tx) => {+ // 1. Query the complete information of the message to be deleted+ const message = await tx+ .select()+ .from(messages)+ .where(and(eq(messages.id, id), scope))+ .limit(1);++ // If the message to be deleted is not found, return directly+ if (message.length === 0) return;++ const activeBranchSnapshots = await this.snapshots.captureActiveBranchSnapshots(+ tx,+ message[0].parentId ? [message[0].parentId] : [],+ );++ // 2. Update child messages' parentId to the current message's parentId+ // This preserves the tree structure when deleting a node+ await tx+ .update(messages)+ .set({ parentId: message[0].parentId })+ .where(and(eq(messages.parentId, id), scope));++ // 3. Check if the message contains tools+ const toolCallIds = (message[0].tools as ChatToolPayload[])+ ?.map((tool) => tool.id)+ .filter(Boolean);++ let relatedMessageIds: string[] = [];++ if (toolCallIds?.length > 0) {+ // 4. If the message contains tools, query all associated message ids+ const res = await tx+ .select({ id: messagePlugins.id })+ .from(messagePlugins)+ .where(inArray(messagePlugins.toolCallId, toolCallIds));++ relatedMessageIds = res.map((row) => row.id);+ }++ // 5. Merge the list of message ids to be deleted+ const messageIdsToDelete = [id, ...relatedMessageIds];++ // 6. Delete all related messages+ await tx.delete(messages).where(and(scope, inArray(messages.id, messageIdsToDelete)));++ await this.snapshots.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);++ // 7. Keep the topic's usage rollup in sync (pure derived β a removed+ // assistant message must drop out of the topic totals).+ if (message[0].topicId) {+ await recomputeTopicUsage(tx, this.userId, message[0].topicId, this.workspaceId);+ }+ });+ };++ /**+ * Batch twin of {@link MessageModel.deleteMessage} β same agent-share visitor+ * rule: visitor messages are skipped unless the caller explicitly opts in.+ */+ deleteMessages = async (ids: string[], options?: ShareVisitorWriteOptions) => {+ if (ids.length === 0) return;++ const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;+ const scope = includeVisitor ? this.workspaceScope() : this.ownership();++ return this.db.transaction(async (tx) => {+ // 1. Query all messages to be deleted with their parentId+ const toDelete = await tx+ .select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId })+ .from(messages)+ .where(and(scope, inArray(messages.id, ids)));++ if (toDelete.length === 0) return;++ // 2. Build id -> parentId map and deleteSet+ const parentMap = new Map<string, string | null>();+ const deleteSet = new Set<string>();+ for (const msg of toDelete) {+ parentMap.set(msg.id, msg.parentId);+ deleteSet.add(msg.id);+ }++ // 3. Find the final ancestor for each deleted message (first ancestor not in deleteSet)+ const finalAncestorMap = new Map<string, string | null>();++ const findFinalAncestor = (id: string): string | null => {+ if (finalAncestorMap.has(id)) return finalAncestorMap.get(id)!;++ const parentId = parentMap.get(id);+ if (parentId === null || parentId === undefined) {+ finalAncestorMap.set(id, null);+ return null;+ }++ if (!deleteSet.has(parentId)) {+ // Parent is not being deleted, it's the final ancestor+ finalAncestorMap.set(id, parentId);+ return parentId;+ }++ // Parent is also being deleted, recursively find its ancestor+ const ancestor = findFinalAncestor(parentId);+ finalAncestorMap.set(id, ancestor);+ return ancestor;+ };++ for (const id of deleteSet) {+ findFinalAncestor(id);+ }++ const activeBranchSnapshots = await this.snapshots.captureActiveBranchSnapshots(+ tx,+ [...new Set(finalAncestorMap.values())].filter((id): id is string => id !== null),+ );++ // 4. Query child messages whose parentId points to messages being deleted+ const children = await tx+ .select({ id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(and(scope, inArray(messages.parentId, ids), not(inArray(messages.id, ids))));++ // 5. Update each child's parentId to the final ancestor+ for (const child of children) {+ const newParentId = finalAncestorMap.get(child.parentId!) ?? null;+ await tx+ .update(messages)+ .set({ parentId: newParentId })+ .where(and(eq(messages.id, child.id), scope));+ }++ // 6. Delete the messages. Deletes the ids that survived the step-1+ // filter, not the raw input, so a mixed batch drops only the visitor rows.+ await tx.delete(messages).where(and(scope, inArray(messages.id, [...deleteSet])));++ await this.snapshots.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);++ // 7. Recompute the usage rollup for every affected topic (pure derived).+ const affectedTopicIds = [+ ...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),+ ];+ for (const topicId of affectedTopicIds) {+ await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);+ }+ });+ };++ /**+ * Creator-facing "clear this session/topic/group" sweep.+ *+ * Agent-share visitor messages live under the creator's `userId` but are+ * hidden from every creator-facing listing (see `notShareVisitorMessage` in+ * `../utils/shareVisitor`), so an id-less sweep must not destroy them β+ * same rule as {@link deleteAllMessages}. Runtime cleanup opts back in via+ * `includeShareVisitor`.+ */+ deleteMessagesBySession = async (+ sessionId?: string | null,+ topicId?: string | null,+ groupId?: string | null,+ options?: ShareVisitorWriteOptions,+ ) => {+ const includeVisitor = options?.includeShareVisitor || this.includeShareVisitor;+ const scope = includeVisitor ? this.workspaceScope() : this.ownership();++ return this.db+ .delete(messages)+ .where(+ and(+ scope,+ this.matchSession(sessionId),+ this.matchTopic(topicId),+ this.matchGroup(groupId),+ ),+ );+ };++ /**+ * Creator-facing "clear all my messages".+ *+ * Agent-share visitor messages are stored under the creator's `userId` but+ * are hidden from every creator-facing listing (see `notShareVisitorMessage`+ * in `../utils/shareVisitor`), so an id-less sweep must not destroy them β+ * "clear all" can only mean the rows the creator can actually see. Id-targeted+ * deletes ({@link MessageModel.deleteMessage}, {@link MessageModel.deleteMessages})+ * apply the same guard by default β a creator can obtain visitor ids out of+ * band (data export), so "the caller named the id" is not proof the row is+ * theirs to delete. Runtime cleanup opts back in via `includeShareVisitor`.+ */+ deleteAllMessages = async () => {+ return this.db.delete(messages).where(and(this.ownership(), notShareVisitorMessage()));+ };++ /**+ * Deletes multiple messages based on the agentId.+ * This will delete messages that have either:+ * 1. Direct agentId match (new data)+ * 2. SessionId match via agentsToSessions lookup (legacy data)+ *+ * This is the creator's "clear this agent's messages" action, so visitor+ * messages are excluded (see {@link deleteAllMessages}). Deleting the agent+ * itself is a different path: `messages.agent_id` / `topics.agent_id` cascade+ * at the DB level, so visitor rows do go away with the agent.+ */+ batchDeleteByAgentId = async (agentId: string) => {+ // Get the associated sessionId for backward compatibility with legacy data+ const agentSession = await this.db+ .select({ sessionId: agentsToSessions.sessionId })+ .from(agentsToSessions)+ .where(and(eq(agentsToSessions.agentId, agentId), this.agentsToSessionsOwnership()))+ .limit(1);++ const associatedSessionId = agentSession[0]?.sessionId;++ // Build condition to match both new (agentId) and legacy (sessionId) data+ const agentCondition = associatedSessionId+ ? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))+ : eq(messages.agentId, agentId);++ return this.db+ .delete(messages)+ .where(and(this.ownership(), agentCondition, notShareVisitorMessage()));+ };+}diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.tsnew file mode 100644index 00000000000..b954ff23f23--- /dev/null+++ b/packages/database/src/models/message/index.ts@@ -0,0 +1,240 @@+import type { UpdateMessageRAGParams } from '@lobechat/types';+import { inArray } from 'drizzle-orm';++import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';+import { MessageApprovalRepo } from '../../repositories/messageApproval';+import { messages } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { MessageAnalyticsQueries } from './analytics';+import { MessageAnnotationMutations } from './annotation';+import { MessageBranchSnapshots } from './branchSnapshots';+import { MessageDeleteMutations } from './delete';+import { MessageLookupQueries } from './lookup';+import { MessagePluginStore } from './plugin';+import { MessageConversationQueries } from './query';+import { MessageByIdsQueries } from './queryByIds';+import { MessagePageQueries } from './queryWithWhere';+import { MessageRelationQueries } from './relations';+import type { MessageScopeArgs } from './scope';+import { MessageSpineQueries } from './spine';+import { MessageToolMutations } from './tool';+import { MessageTrashMutations } from './trash';+import type { MessageModelOptions } from './types';+import { MessageWriteMutations } from './write';++/**+ * Message persistence model. The class composes one instance per sub-domain+ * (reads, analytics, writes, plugins, deletion, β¦) built on a shared+ * `MessageScope` and exposes their public methods as bound properties,+ * so callers can keep destructuring them.+ */+export class MessageModel {+ findById: MessageLookupQueries['findById'];+ findShareVisitorMessageIds: MessageLookupQueries['findShareVisitorMessageIds'];+ findByClientId: MessageLookupQueries['findByClientId'];+ findLatestAssistantMessageByThread: MessageLookupQueries['findLatestAssistantMessageByThread'];+ findVerifyMessageByOperationId: MessageLookupQueries['findVerifyMessageByOperationId'];+ findLatestAssistantByOperationId: MessageLookupQueries['findLatestAssistantByOperationId'];+ getThreadParentMessages: MessageLookupQueries['getThreadParentMessages'];+ findMessageQueriesById: MessageLookupQueries['findMessageQueriesById'];+ queryBySessionId: MessageLookupQueries['queryBySessionId'];+ queryByKeyword: MessageLookupQueries['queryByKeyword'];++ queryByIds: MessageByIdsQueries['queryByIds'];++ queryWithWhere: MessagePageQueries['queryWithWhere'];++ queryLastUserMessageByTopics: MessageConversationQueries['queryLastUserMessageByTopics'];+ query: MessageConversationQueries['query'];+ queryForVisitor: MessageConversationQueries['queryForVisitor'];+ countByTopic: MessageConversationQueries['countByTopic'];+ queryTopicTranscript: MessageConversationQueries['queryTopicTranscript'];+ queryTopicMessageTree: MessageConversationQueries['queryTopicMessageTree'];+ queryTopicMessagesByCursor: MessageConversationQueries['queryTopicMessagesByCursor'];++ queryAll: MessageAnalyticsQueries['queryAll'];+ count: MessageAnalyticsQueries['count'];+ countApproximate: MessageAnalyticsQueries['countApproximate'];+ countGroupByTopic: MessageAnalyticsQueries['countGroupByTopic'];+ topicMessageStats: MessageAnalyticsQueries['topicMessageStats'];+ hasTopicMessages: MessageAnalyticsQueries['hasTopicMessages'];+ findFirstAssistantInTopic: MessageAnalyticsQueries['findFirstAssistantInTopic'];+ countWords: MessageAnalyticsQueries['countWords'];+ rankModels: MessageAnalyticsQueries['rankModels'];+ getHeatmaps: MessageAnalyticsQueries['getHeatmaps'];+ getTokenHeatmaps: MessageAnalyticsQueries['getTokenHeatmaps'];+ hasMoreThanN: MessageAnalyticsQueries['hasMoreThanN'];+ countUpTo: MessageAnalyticsQueries['countUpTo'];++ create: MessageWriteMutations['create'];+ createUserAndAssistantMessages: MessageWriteMutations['createUserAndAssistantMessages'];+ batchCreate: MessageWriteMutations['batchCreate'];+ createMessageQuery: MessageWriteMutations['createMessageQuery'];+ update: MessageWriteMutations['update'];+ updateMetadata: MessageWriteMutations['updateMetadata'];++ updatePluginState: MessagePluginStore['updatePluginState'];+ updateMessagePlugin: MessagePluginStore['updateMessagePlugin'];+ resolveHumanApproval: MessageApprovalRepo['resolve'];+ restoreHumanApproval: MessageApprovalRepo['restore'];+ findMessagePlugin: MessagePluginStore['findMessagePlugin'];+ listMessagePluginsByTopic: MessagePluginStore['listMessagePluginsByTopic'];+ findLatestPluginStateInTopic: MessagePluginStore['findLatestPluginStateInTopic'];+ listMessagePluginsForOperation: MessagePluginStore['listMessagePluginsForOperation'];+ listMessagePluginsByIds: MessagePluginStore['listMessagePluginsByIds'];+ findToolMessageIdByToolCallId: MessagePluginStore['findToolMessageIdByToolCallId'];++ updateToolMessage: MessageToolMutations['updateToolMessage'];+ updateToolArguments: MessageToolMutations['updateToolArguments'];++ getLastMainThreadSpineMessageId: MessageSpineQueries['getLastMainThreadSpineMessageId'];+ isMessageDescendantOf: MessageSpineQueries['isMessageDescendantOf'];+ getLatestSpineMessageId: MessageSpineQueries['getLatestSpineMessageId'];+ getLatestNonToolMessageId: MessageSpineQueries['getLatestNonToolMessageId'];++ updateTranslate: MessageAnnotationMutations['updateTranslate'];+ updateTTS: MessageAnnotationMutations['updateTTS'];+ addFiles: MessageAnnotationMutations['addFiles'];+ deleteMessageTranslate: MessageAnnotationMutations['deleteMessageTranslate'];+ deleteMessageTTS: MessageAnnotationMutations['deleteMessageTTS'];+ deleteMessageQuery: MessageAnnotationMutations['deleteMessageQuery'];++ deleteMessage: MessageDeleteMutations['deleteMessage'];+ deleteMessages: MessageDeleteMutations['deleteMessages'];+ deleteMessagesBySession: MessageDeleteMutations['deleteMessagesBySession'];+ deleteAllMessages: MessageDeleteMutations['deleteAllMessages'];+ batchDeleteByAgentId: MessageDeleteMutations['batchDeleteByAgentId'];++ softDeleteMessages: MessageTrashMutations['softDeleteMessages'];+ restoreMessages: MessageTrashMutations['restoreMessages'];+ findTrashedByIds: MessageTrashMutations['findTrashedByIds'];+ softDeleteTopicless: MessageTrashMutations['softDeleteTopicless'];+ purgeMessages: MessageTrashMutations['purgeMessages'];++ private readonly annotations: MessageAnnotationMutations;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ ftsSearchCandidateSource?: FtsSearchCandidateSource,+ options: MessageModelOptions = {},+ ) {+ const args: MessageScopeArgs = [db, userId, workspaceId, ftsSearchCandidateSource, options];++ const lookups = new MessageLookupQueries(...args);+ const relations = new MessageRelationQueries(...args);+ const byIds = new MessageByIdsQueries(args, { relations });+ const page = new MessagePageQueries(args, { relations, byIds });+ const conversation = new MessageConversationQueries(args, { lookups, page });+ const analytics = new MessageAnalyticsQueries(...args);+ const writes = new MessageWriteMutations(...args);+ const plugins = new MessagePluginStore(args, { lookups });+ const tools = new MessageToolMutations(...args);+ const spine = new MessageSpineQueries(...args);+ const annotations = new MessageAnnotationMutations(args, { lookups });+ const snapshots = new MessageBranchSnapshots(...args);+ const deletion = new MessageDeleteMutations(args, { snapshots });+ const trash = new MessageTrashMutations(args, { snapshots });++ this.annotations = annotations;++ this.findById = lookups.findById;+ this.findShareVisitorMessageIds = lookups.findShareVisitorMessageIds;+ this.findByClientId = lookups.findByClientId;+ this.findLatestAssistantMessageByThread = lookups.findLatestAssistantMessageByThread;+ this.findVerifyMessageByOperationId = lookups.findVerifyMessageByOperationId;+ this.findLatestAssistantByOperationId = lookups.findLatestAssistantByOperationId;+ this.getThreadParentMessages = lookups.getThreadParentMessages;+ this.findMessageQueriesById = lookups.findMessageQueriesById;+ this.queryBySessionId = lookups.queryBySessionId;+ this.queryByKeyword = lookups.queryByKeyword;+ this.queryByIds = byIds.queryByIds;+ this.queryWithWhere = page.queryWithWhere;+ this.queryLastUserMessageByTopics = conversation.queryLastUserMessageByTopics;+ this.query = conversation.query;+ this.queryForVisitor = conversation.queryForVisitor;+ this.countByTopic = conversation.countByTopic;+ this.queryTopicTranscript = conversation.queryTopicTranscript;+ this.queryTopicMessageTree = conversation.queryTopicMessageTree;+ this.queryTopicMessagesByCursor = conversation.queryTopicMessagesByCursor;+ this.queryAll = analytics.queryAll;+ this.count = analytics.count;+ this.countApproximate = analytics.countApproximate;+ this.countGroupByTopic = analytics.countGroupByTopic;+ this.topicMessageStats = analytics.topicMessageStats;+ this.hasTopicMessages = analytics.hasTopicMessages;+ this.findFirstAssistantInTopic = analytics.findFirstAssistantInTopic;+ this.countWords = analytics.countWords;+ this.rankModels = analytics.rankModels;+ this.getHeatmaps = analytics.getHeatmaps;+ this.getTokenHeatmaps = analytics.getTokenHeatmaps;+ this.hasMoreThanN = analytics.hasMoreThanN;+ this.countUpTo = analytics.countUpTo;+ this.create = writes.create;+ this.createUserAndAssistantMessages = writes.createUserAndAssistantMessages;+ this.batchCreate = writes.batchCreate;+ this.createMessageQuery = writes.createMessageQuery;+ this.update = writes.update;+ this.updateMetadata = writes.updateMetadata;+ this.updatePluginState = plugins.updatePluginState;+ this.updateMessagePlugin = plugins.updateMessagePlugin;+ // The approval claim locks and writes message roots and plugin rows in one+ // transaction; that unit of work is owned by the repository.+ const approvals = new MessageApprovalRepo(db, userId, workspaceId, options);+ this.resolveHumanApproval = approvals.resolve;+ this.restoreHumanApproval = approvals.restore;+ this.findMessagePlugin = plugins.findMessagePlugin;+ this.listMessagePluginsByTopic = plugins.listMessagePluginsByTopic;+ this.findLatestPluginStateInTopic = plugins.findLatestPluginStateInTopic;+ this.listMessagePluginsForOperation = plugins.listMessagePluginsForOperation;+ this.listMessagePluginsByIds = plugins.listMessagePluginsByIds;+ this.findToolMessageIdByToolCallId = plugins.findToolMessageIdByToolCallId;+ this.updateToolMessage = tools.updateToolMessage;+ this.updateToolArguments = tools.updateToolArguments;+ this.getLastMainThreadSpineMessageId = spine.getLastMainThreadSpineMessageId;+ this.isMessageDescendantOf = spine.isMessageDescendantOf;+ this.getLatestSpineMessageId = spine.getLatestSpineMessageId;+ this.getLatestNonToolMessageId = spine.getLatestNonToolMessageId;+ this.updateTranslate = annotations.updateTranslate;+ this.updateTTS = annotations.updateTTS;+ this.addFiles = annotations.addFiles;+ this.deleteMessageTranslate = annotations.deleteMessageTranslate;+ this.deleteMessageTTS = annotations.deleteMessageTTS;+ this.deleteMessageQuery = annotations.deleteMessageQuery;+ this.deleteMessage = deletion.deleteMessage;+ this.deleteMessages = deletion.deleteMessages;+ this.deleteMessagesBySession = deletion.deleteMessagesBySession;+ this.deleteAllMessages = deletion.deleteAllMessages;+ this.batchDeleteByAgentId = deletion.batchDeleteByAgentId;+ this.softDeleteMessages = trash.softDeleteMessages;+ this.restoreMessages = trash.restoreMessages;+ this.findTrashedByIds = trash.findTrashedByIds;+ this.softDeleteTopicless = trash.softDeleteTopicless;+ this.purgeMessages = trash.purgeMessages;+ }++ async updateMessageRAG(id: string, params: UpdateMessageRAGParams) {+ return this.annotations.updateMessageRAG(id, params);+ }++ /**+ * Check which user IDs from the given list have at least one message.+ */+ static checkUsersHaveMessages = async (+ db: LobeChatDatabase,+ userIds: string[],+ ): Promise<Set<string>> => {+ if (userIds.length === 0) return new Set();+ const result = await db+ .select({ userId: messages.userId })+ .from(messages)+ .where(inArray(messages.userId, userIds))+ .groupBy(messages.userId);+ return new Set(result.map((r) => r.userId));+ };+}++export { HumanApprovalAlreadyResolvedError } from './plugin';+export * from './types';+export { redactCreatorPrivateBlob, sanitizeVisitorError, toVisitorMessage } from './visitor';diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.tsnew file mode 100644index 00000000000..add87317a3d--- /dev/null+++ b/packages/database/src/models/message/lookup.ts@@ -0,0 +1,325 @@+import type { DBMessageItem, IThreadType } from '@lobechat/types';+import { ThreadType } from '@lobechat/types';+import type { SQL } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNull, lte, not, or, sql } from 'drizzle-orm';++import {+ agentsToSessions,+ embeddings,+ messageQueries,+ messages,+ threads,+ topics,+} from '../../schemas';+import { sanitizeBm25Query } from '../../utils/bm25';+import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { searchableMessage } from '../../utils/searchableMessage';+import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { MessageScope } from './scope';++export class MessageLookupQueries extends MessageScope {+ /**+ * Build where condition for thread queries+ *+ * Returns a condition that matches both parent messages and thread messages.+ */+ buildThreadQueryCondition = async (threadId: string): Promise<SQL | undefined> => {+ // Fetch the thread info to get sourceMessageId and type+ const thread = await this.db.query.threads.findFirst({+ where: and(+ eq(threads.id, threadId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),+ ),+ });++ if (!thread?.sourceMessageId || !thread?.topicId) {+ // Fallback to simple thread query if no source message+ return eq(messages.threadId, threadId);+ }++ // Get parent messages based on thread type+ const parentMessages = await this.getThreadParentMessages({+ sourceMessageId: thread.sourceMessageId,+ threadType: thread.type as IThreadType,+ topicId: thread.topicId,+ });++ const parentMessageIds = parentMessages.map((m) => m.id);++ if (parentMessageIds.length === 0) {+ return eq(messages.threadId, threadId);+ }++ // Match either thread messages or parent messages+ return or(eq(messages.threadId, threadId), inArray(messages.id, parentMessageIds));+ };++ /**+ * Build agent condition with legacy sessionId support+ */+ buildAgentCondition = async (agentId: string): Promise<SQL | undefined> => {+ // Get the associated sessionId for backward compatibility with legacy data+ const agentSession = await this.db+ .select({ sessionId: agentsToSessions.sessionId })+ .from(agentsToSessions)+ .where(and(eq(agentsToSessions.agentId, agentId), this.agentsToSessionsOwnership()))+ .limit(1);++ const associatedSessionId = agentSession[0]?.sessionId;++ // Build condition to match both new (agentId) and legacy (sessionId) data+ return associatedSessionId+ ? or(eq(messages.agentId, agentId), eq(messages.sessionId, associatedSessionId))+ : eq(messages.agentId, agentId);+ };++ findById = async (id: string) => {+ return this.db.query.messages.findFirst({+ where: and(eq(messages.id, id), this.ownership()),+ });+ };++ /**+ * Ids among `ids` that resolve to an agent-share VISITOR message under this+ * owner β the inverse of the `notShareVisitorMessage()` predicate every+ * creator-facing read applies.+ *+ * Creator-facing write entry points use this to reject visitor targets+ * (see `assertCreatorMessageTargets` in the server router helpers). Ids that+ * match no row at all are NOT reported, so callers keep their existing no-op+ * behaviour for stale/foreign ids and only fail on rows that really belong to+ * a visitor's conversation.+ */+ findShareVisitorMessageIds = async (ids: string[]): Promise<string[]> => {+ if (ids.length === 0) return [];++ const rows = await this.db+ .select({ id: messages.id })+ .from(messages)+ // Explicitly scoped visitor-inclusive: this method's whole job is to+ // return visitor ids so the router-level `assertCreatorMessageTargets`+ // can reject them, so bypass the instance's visitor exclusion.+ .where(and(inArray(messages.id, ids), this.workspaceScope(), not(notShareVisitorMessage())));++ return rows.map((row) => row.id);+ };++ findByClientId = async (clientId: string) => {+ return this.db.query.messages.findFirst({+ where: and(eq(messages.clientId, clientId), this.ownership()),+ });+ };++ findLatestAssistantMessageByThread = async ({+ agentId,+ threadId,+ topicId,+ }: {+ agentId: string;+ threadId: string;+ topicId: string;+ }) =>+ this.db.query.messages.findFirst({+ orderBy: [desc(messages.createdAt), desc(messages.id)],+ where: and(+ this.ownership(),+ eq(messages.agentId, agentId),+ inArray(+ messages.topicId,+ this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ ),+ ),+ eq(messages.threadId, threadId),+ eq(messages.role, 'assistant'),+ ),+ });++ /**+ * Resolve the `role='verify'` delivery-checker card for an Agent Run (created+ * with `metadata.verifyOperationId = operationId`). Used by auto-repair to+ * persist the failure feedback onto the card it belongs to.+ */+ findVerifyMessageByOperationId = async (operationId: string) => {+ return this.db.query.messages.findFirst({+ where: and(+ this.ownership(),+ eq(messages.role, 'verify'),+ sql`${messages.metadata}->>'verifyOperationId' = ${operationId}`,+ ),+ orderBy: [desc(messages.createdAt)],+ });+ };++ /**+ * Resolve the newest assistant row an Agent Run produced, by the creation+ * provenance `call_llm` stamps on every assistant row it creates or reuses+ * (`metadata.operationId`). Scoped by `topicId` so the JSONB predicate runs+ * inside the topic's own (indexed) rows rather than across the whole table.+ *+ * Used by the completion lifecycle to recover the run's real final reply+ * when the runtime state no longer carries this run's messages β the+ * topic-wide "latest assistant" would be an earlier turn's reply.+ */+ findLatestAssistantByOperationId = async ({+ operationId,+ topicId,+ }: {+ operationId: string;+ topicId: string;+ }) => {+ return this.db.query.messages.findFirst({+ where: and(+ this.ownership(),+ inArray(+ messages.topicId,+ this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ ),+ ),+ eq(messages.role, 'assistant'),+ sql`${messages.metadata}->>'operationId' = ${operationId}`,+ ),+ orderBy: [desc(messages.createdAt)],+ });+ };++ /**+ * Get parent messages for a thread+ *+ * @param params - Parameters for getting parent messages+ * @param params.sourceMessageId - The ID of the source message that started the thread+ * @param params.topicId - The topic ID the thread belongs to+ * @param params.threadType - The type of thread (Continuation, Standalone, or Isolation)+ * @returns Parent messages based on thread type:+ * - Continuation: All messages from the topic up to and including the source message+ * - Standalone: Only the source message itself+ * - Isolation: No parent messages (completely isolated thread)+ */+ getThreadParentMessages = async (params: {+ sourceMessageId: string;+ threadType: IThreadType;+ topicId: string;+ }): Promise<DBMessageItem[]> => {+ const { sourceMessageId, topicId, threadType } = params;++ // For Isolation type, return empty array (no parent messages)+ if (threadType === ThreadType.Isolation) {+ return [];+ }++ // For Standalone type, only return the source message+ if (threadType === ThreadType.Standalone) {+ const sourceMessage = await this.db.query.messages.findFirst({+ where: and(eq(messages.id, sourceMessageId), this.ownership()),+ });++ return sourceMessage ? [sourceMessage as DBMessageItem] : [];+ }++ // For Continuation type, get the source message first to know its createdAt+ const sourceMessage = await this.db.query.messages.findFirst({+ where: and(eq(messages.id, sourceMessageId), this.ownership()),+ });++ if (!sourceMessage) return [];++ // Get all main conversation messages up to and including the source message+ // Use `or` with explicit id match to handle timestamp precision issues+ // (JavaScript Date has millisecond precision, but PostgreSQL timestamptz has microsecond precision)+ const result = await this.db+ .select()+ .from(messages)+ .where(+ and(+ this.ownership(),+ eq(messages.topicId, topicId),+ isNull(messages.threadId), // Only main conversation messages (not in any thread)+ or(+ lte(messages.createdAt, sourceMessage.createdAt),+ eq(messages.id, sourceMessageId), // Ensure source message is always included+ ),+ ),+ )+ .orderBy(asc(messages.createdAt));++ return result as DBMessageItem[];+ };++ findMessageQueriesById = async (messageId: string) => {+ const result = await this.db+ .select({+ embeddings: embeddings.embeddings,+ id: messageQueries.id,+ query: messageQueries.rewriteQuery,+ rewriteQuery: messageQueries.rewriteQuery,+ userQuery: messageQueries.userQuery,+ })+ .from(messageQueries)+ .where(and(eq(messageQueries.messageId, messageId)))+ .leftJoin(embeddings, eq(embeddings.id, messageQueries.embeddingsId));++ if (result.length === 0) return undefined;++ return result[0];+ };++ // Plain select builder instead of `db.query...findMany`: the relational+ // query API re-qualifies raw SQL fragments to the outer table alias, which+ // breaks the `topics`-referencing NOT EXISTS inside `notShareVisitorMessage`.+ queryBySessionId = async (sessionId?: string | null) => {+ const result = await this.db+ .select()+ .from(messages)+ // Visitor messages have no sessionId, so the null-session (inbox) branch+ // would otherwise sweep them in.+ .where(and(this.ownership(), this.matchSession(sessionId), notShareVisitorMessage()))+ .orderBy(asc(messages.createdAt));++ return result as DBMessageItem[];+ };++ queryByKeyword = async (keyword: string) => {+ if (!keyword.trim()) return [];++ const bm25Query = sanitizeBm25Query(keyword);+ const candidateResult = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled+ ? await this.ftsSearchCandidateSource.ftsSearchCandidates({+ entity: 'messages',+ filters: {},+ pagination: {},+ query: { fields: ['content'], text: keyword },+ })+ : undefined;+ const candidateIds = candidateResult?.candidates.map(({ id }) => id);+ const result = await this.db+ .select()+ .from(messages)+ .where(+ and(+ this.ownership(),+ notShareVisitorMessage(),+ searchableMessage(),+ candidateIds+ ? inJsonStringArray(messages.id, candidateIds)+ : sql`${messages.content} @@@ ${bm25Query}`,+ ),+ )+ .orderBy(desc(messages.createdAt));++ return result as DBMessageItem[];+ };+}diff --git a/packages/database/src/models/message/plugin.ts b/packages/database/src/models/message/plugin.tsnew file mode 100644index 00000000000..d5a214360c5--- /dev/null+++ b/packages/database/src/models/message/plugin.ts@@ -0,0 +1,442 @@+import type { MessageMetadata, MessagePluginItem } from '@lobechat/types';+import type { SQL } from 'drizzle-orm';+import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, sql } from 'drizzle-orm';++import { clampToolIdentifier } from '@/utils/clampToolIdentifier';++import { messagePlugins, messages } from '../../schemas';+import { notShareVisitorMessage } from '../../utils/shareVisitor';+import type { MessageLookupQueries } from './lookup';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';++export class HumanApprovalAlreadyResolvedError extends Error {+ constructor(messageId: string) {+ super(`Human approval is no longer pending for tool message ${messageId}`);+ this.name = 'HumanApprovalAlreadyResolvedError';+ }+}++export class MessagePluginStore extends MessageScope {+ private readonly lookups: MessageLookupQueries;++ constructor(args: MessageScopeArgs, deps: { lookups: MessageLookupQueries }) {+ super(...args);+ this.lookups = deps.lookups;+ }++ updatePluginState = async (id: string, state: Record<string, any>): Promise<void> => {+ const updated = await this.db+ .update(messagePlugins)+ .set({+ // Plugin-state patches own complete top-level keys. Merge them in SQL so+ // concurrent writers of different keys cannot overwrite each other.+ state: sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(state)}::jsonb`,+ })+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))+ .returning({ id: messagePlugins.id });++ if (updated.length === 0) throw new Error('Plugin not found');+ };++ updateMessagePlugin = async (id: string, value: Partial<MessagePluginItem>) => {+ const item = await this.db.query.messagePlugins.findFirst({+ where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),+ });+ if (!item) throw new Error('Plugin not found');++ return this.db+ .update(messagePlugins)+ .set({+ ...value,+ apiName: clampToolIdentifier(value.apiName),+ identifier: clampToolIdentifier(value.identifier),+ })+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()));+ };++ /**+ * Row-lock the plugin rows of an approval batch (`SELECT β¦ FOR UPDATE`).+ * Only meaningful on a transaction-bound store: the approval repository+ * (`MessageApprovalRepo`) calls it after locking the message rows, matching+ * deferred completion's lock order (message before plugin).+ */+ lockApprovalPluginsForUpdate = async (ids: string[]) =>+ this.db+ .select({+ id: messagePlugins.id,+ intervention: messagePlugins.intervention,+ state: messagePlugins.state,+ })+ .from(messagePlugins)+ .where(and(inArray(messagePlugins.id, ids), this.pluginsOwnership()))+ .for('update');++ /**+ * Write the approval columns (intervention / error / state) of one plugin+ * row. Returns `false` when the row is outside this scope.+ */+ patchApprovalPlugin = async (+ id: string,+ value: Pick<Partial<typeof messagePlugins.$inferInsert>, 'error' | 'intervention' | 'state'>,+ ): Promise<boolean> => {+ const [updated] = await this.db+ .update(messagePlugins)+ .set(value)+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))+ .returning({ id: messagePlugins.id });+ return Boolean(updated);+ };++ /**+ * Fetch the `message_plugins` row associated with a tool message. Tool-call+ * metadata (identifier / apiName / arguments / type / toolCallId /+ * intervention) lives on this row, not on the `messages` row returned by+ * {@link findById}.+ *+ * Returns `undefined` when the message has no plugin row. Normalizes the+ * DB row (nullable columns) into the optional-field shape of+ * {@link MessagePluginItem} so callers don't need to juggle `null` vs+ * `undefined`.+ */+ findMessagePlugin = async (messageId: string): Promise<MessagePluginItem | undefined> => {+ const row = await this.db.query.messagePlugins.findFirst({+ where: and(eq(messagePlugins.id, messageId), this.pluginsOwnership()),+ });+ if (!row) return undefined;+ return {+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ clientId: row.clientId ?? undefined,+ error: row.error ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ state: row.state ?? undefined,+ toolCallId: row.toolCallId ?? undefined,+ type: row.type ?? 'default',+ userId: row.userId,+ };+ };++ /**+ * List tool/plugin rows for a topic in stable first-seen order.+ *+ * This is used by onboarding analytics to reconstruct successful assistant+ * creation results before the topic is moved into inbox.+ */+ listMessagePluginsByTopic = async (+ topicId: string,+ ): Promise<Array<MessagePluginItem & { metadata?: MessageMetadata }>> => {+ const rows = await this.db+ .select({+ apiName: messagePlugins.apiName,+ arguments: messagePlugins.arguments,+ clientId: messagePlugins.clientId,+ error: messagePlugins.error,+ id: messagePlugins.id,+ identifier: messagePlugins.identifier,+ intervention: messagePlugins.intervention,+ metadata: messages.metadata,+ state: messagePlugins.state,+ toolCallId: messagePlugins.toolCallId,+ type: messagePlugins.type,+ userId: messagePlugins.userId,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(and(eq(messages.topicId, topicId), this.ownership(), this.pluginsOwnership()))+ .orderBy(asc(messages.createdAt), asc(messages.id));++ return rows.map((row) => ({+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ clientId: row.clientId ?? undefined,+ error: row.error ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ metadata: row.metadata ?? undefined,+ state: row.state ?? undefined,+ toolCallId: row.toolCallId ?? undefined,+ type: row.type ?? 'default',+ userId: row.userId,+ }));+ };++ /**+ * The `state` of the most recent call to one tool API in a topic that+ * produced any β a failed or aborted call leaves no state. Lets a tool read+ * back what an earlier call in the same conversation produced, e.g. the group+ * a builder conversation last created with `createGroup`.+ *+ * Scoped like a message query for the same branch: without `threadId` only+ * the main conversation counts; with it, the thread plus the parent messages+ * its type inherits β never a sibling thread.+ */+ findLatestPluginStateInTopic = async (params: {+ apiName: string;+ identifier: string;+ threadId?: string | null;+ topicId: string;+ }): Promise<Record<string, any> | undefined> => {+ const threadCondition = params.threadId+ ? await this.lookups.buildThreadQueryCondition(params.threadId)+ : isNull(messages.threadId);++ const [row] = await this.db+ .select({ state: messagePlugins.state })+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(+ and(+ eq(messages.topicId, params.topicId),+ threadCondition,+ eq(messagePlugins.identifier, params.identifier),+ eq(messagePlugins.apiName, params.apiName),+ isNotNull(messagePlugins.state),+ this.ownership(),+ this.pluginsOwnership(),+ ),+ )+ .orderBy(desc(messages.createdAt), desc(messages.id))+ .limit(1);++ return row?.state ?? undefined;+ };++ /**+ * List the tool/plugin rows produced by ONE agent operation, for the+ * per-operation file-edit scan.+ *+ * An operation has no direct foreign key on `message_plugins`, so its rows are+ * bracketed two ways, OR-ed together:+ * 1. Time window β same `topicId` + `threadId`, with the owning message's+ * `createdAt` inside `[startedAt, completedAt]` (`completedAt` falls back to+ * now for an op still finalizing). The primary path for in-process runs.+ * 2. Heterogeneous match β the message carries+ * `metadata.heterogeneousToolStateOperationId === operationId` directly,+ * which a CLI-backed run stamps regardless of when the row lands. Mirrors+ * the jsonb predicate in {@link findVerifyMessageByOperationId}.+ *+ * TRADE-OFF (v1): the time window is racy β two operations running+ * concurrently in the SAME topic+thread can bleed each other's tool calls into+ * the window. Accepted for now; the heterogeneous path is exact where it+ * applies. Rows carry `createdAt` so the caller can globally order tool calls+ * merged across an operation tree before folding them.+ */+ listMessagePluginsForOperation = async (params: {+ completedAt?: Date | null;+ operationId: string;+ startedAt: Date;+ threadId?: string | null;+ topicId: string;+ }): Promise<Array<MessagePluginItem & { content?: string; createdAt: Date }>> => {+ const completedAt = params.completedAt ?? new Date();++ const withinWindow = and(+ eq(messages.topicId, params.topicId),+ params.threadId ? eq(messages.threadId, params.threadId) : isNull(messages.threadId),+ gte(messages.createdAt, params.startedAt),+ lte(messages.createdAt, completedAt),+ );++ // The two branches are resolved SEPARATELY β never OR-ed into one WHERE (an+ // `... AND (withinWindow OR heteroMatch)` is unindexable and seq-scans every+ // plugin row the user owns). They are also SHAPED differently on purpose:+ //+ // - Time window: one index-friendly range scan joined to its plugin rows.+ // - Heterogeneous match: resolved id-FIRST, not as a plugin JOIN. The+ // `metadata->>'heterogeneousToolStateOperationId'` predicate carries a 0.5%+ // default selectivity estimate, so joining it to `message_plugins` makes the+ // planner scan / nested-loop the user's ENTIRE plugin history (100k+ rows,+ // 100s+ per call for heavy users β it returns ~0 rows but pays the full scan+ // every time, since most ops never stamp the key). Looking up the few+ // matching message ids in a JOIN-free query first, then fetching those rows+ // by primary key, leaves the planner no join to mis-order: the lookup is+ // single-table (index-served once the metadata expression is indexed; a+ // bounded scan otherwise) and the fetch is a pure PK access. Kept+ // topic-agnostic to preserve the prior behaviour exactly β a late CLI row+ // can land outside the op's window (and, rarely, its topic).+ const projection = {+ apiName: messagePlugins.apiName,+ arguments: messagePlugins.arguments,+ clientId: messagePlugins.clientId,+ // The tool message's text body. Heterogeneous CLI adapters (claude-code+ // Bash) persist the command's stdout here rather than in a structured+ // `state` field, and the completion-time github Work scan reads the gh+ // CLI's printed entity URL from it.+ content: messages.content,+ createdAt: messages.createdAt,+ error: messagePlugins.error,+ id: messagePlugins.id,+ identifier: messagePlugins.identifier,+ intervention: messagePlugins.intervention,+ state: messagePlugins.state,+ toolCallId: messagePlugins.toolCallId,+ type: messagePlugins.type,+ userId: messagePlugins.userId,+ };++ const scan = (condition: SQL | undefined) =>+ this.db+ .select(projection)+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(and(this.ownership(), this.pluginsOwnership(), condition));++ const fetchHeterogeneous = async () => {+ const idRows = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ this.ownership(),+ sql`${messages.metadata}->>'heterogeneousToolStateOperationId' = ${params.operationId}`,+ ),+ );+ const ids = idRows.map((row) => row.id);+ if (ids.length === 0) return [];+ return scan(inArray(messagePlugins.id, ids));+ };++ const [windowRows, heterogeneousRows] = await Promise.all([+ scan(withinWindow),+ fetchHeterogeneous(),+ ]);++ const byId = new Map<string, (typeof windowRows)[number]>();+ for (const row of windowRows) byId.set(row.id, row);+ for (const row of heterogeneousRows) if (!byId.has(row.id)) byId.set(row.id, row);++ const rows = [...byId.values()].sort(+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id),+ );++ return rows.map((row) => ({+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ clientId: row.clientId ?? undefined,+ content: row.content ?? undefined,+ createdAt: row.createdAt,+ error: row.error ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ state: row.state ?? undefined,+ toolCallId: row.toolCallId ?? undefined,+ type: row.type ?? 'default',+ userId: row.userId,+ }));+ };++ /**+ * Load specific tool-call rows by their message ids, ownership-scoped and+ * pinned to one topic. Serves the LOCAL hetero run work scan+ * (`work.registerShellWorksForRun`): a desktop-local CLI run has no+ * `agent_operations` row, so the client reports the exact tool message ids it+ * persisted instead of the server reconstructing an operation window. The+ * topic pin means a caller can never scan rows outside the conversation it+ * claims to complete.+ */+ listMessagePluginsByIds = async (params: {+ ids: string[];+ topicId: string;+ }): Promise<Array<MessagePluginItem & { content?: string; createdAt: Date }>> => {+ if (params.ids.length === 0) return [];++ const rows = await this.db+ .select({+ apiName: messagePlugins.apiName,+ arguments: messagePlugins.arguments,+ clientId: messagePlugins.clientId,+ // The tool message's text body β claude-code Bash persists the+ // command's stdout here (see listMessagePluginsForOperation).+ content: messages.content,+ createdAt: messages.createdAt,+ error: messagePlugins.error,+ id: messagePlugins.id,+ identifier: messagePlugins.identifier,+ intervention: messagePlugins.intervention,+ state: messagePlugins.state,+ toolCallId: messagePlugins.toolCallId,+ type: messagePlugins.type,+ userId: messagePlugins.userId,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messagePlugins.id, messages.id))+ .where(+ and(+ inArray(messagePlugins.id, params.ids),+ eq(messages.topicId, params.topicId),+ this.ownership(),+ this.pluginsOwnership(),+ // A desktop-local hetero run never happens inside an agent-share+ // visitor topic, so excluding them costs nothing and stops a creator+ // from surfacing a visitor's tool calls as their own Work cards.+ notShareVisitorMessage(),+ ),+ );++ const sorted = [...rows].sort(+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.id.localeCompare(b.id),+ );++ return sorted.map((row) => ({+ apiName: row.apiName ?? undefined,+ arguments: row.arguments ?? undefined,+ clientId: row.clientId ?? undefined,+ content: row.content ?? undefined,+ createdAt: row.createdAt,+ error: row.error ?? undefined,+ id: row.id,+ identifier: row.identifier ?? undefined,+ intervention: row.intervention ?? undefined,+ state: row.state ?? undefined,+ toolCallId: row.toolCallId ?? undefined,+ type: row.type ?? 'default',+ userId: row.userId,+ }));+ };++ /**+ * Resolve the tool result message id for a toolCallId β the stable identifier+ * the model emitted for the call. Lets server-side services push async state+ * onto a tool card when all they hold is the call id recorded at creation+ * time (e.g. the goal loop updating the `createGoal` card via+ * `task.context.origin.toolCallId`).+ */+ findToolMessageIdByToolCallId = async (+ toolCallId: string,+ /**+ * Restrict the match to calls made by one assistant message.+ *+ * `tool_call_id` is provider-supplied and only unique in practice β the+ * column carries a plain index, not a unique constraint. Callers that act+ * on the row (rather than just reading it) should scope the match, or a+ * reused id from another turn resolves to an unrelated historical result.+ */+ parentId?: string,+ ): Promise<string | null> => {+ const rows = parentId+ ? await this.db+ .select({ id: messagePlugins.id })+ .from(messagePlugins)+ .innerJoin(messages, eq(messages.id, messagePlugins.id))+ .where(+ and(+ eq(messagePlugins.toolCallId, toolCallId),+ eq(messages.parentId, parentId),+ this.pluginsOwnership(),+ ),+ )+ .limit(1)+ : await this.db+ .select({ id: messagePlugins.id })+ .from(messagePlugins)+ .where(and(eq(messagePlugins.toolCallId, toolCallId), this.pluginsOwnership()))+ .limit(1);++ return rows[0]?.id ?? null;+ };+}diff --git a/packages/database/src/models/message/query.ts b/packages/database/src/models/message/query.tsnew file mode 100644index 00000000000..12565ae323a--- /dev/null+++ b/packages/database/src/models/message/query.ts@@ -0,0 +1,637 @@+import type {+ ChatMessageError,+ ChatToolPayload,+ MessageMetadata,+ QueryMessageParams,+ UIChatMessage,+ WorkAccessScope,+} from '@lobechat/types';+import {+ getDurationMs,+ logTimingSink as logTiming,+ runTimedSinkStage as runTimedStage,+} from '@lobechat/utils';+import type { SQL } from 'drizzle-orm';+import {+ and,+ asc,+ count,+ desc,+ eq,+ gte,+ inArray,+ isNotNull,+ isNull,+ lt,+ ne,+ or,+ sql,+} from 'drizzle-orm';++import { messagePlugins, messages } from '../../schemas';+import { notShareVisitorMessage } from '../../utils/shareVisitor';+import type { MessageLookupQueries } from './lookup';+import type { MessagePageQueries } from './queryWithWhere';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';+import type {+ MessageGroupNodeWindow,+ MessageRoundCursor,+ ModelTimingContext,+ QueryTopicByCursorParams,+ TopicMessagesByCursorResult,+ TopicTranscriptResult,+ VisitorRedactionOptions,+} from './types';+import { toVisitorMessage } from './visitor';++/** Default rounds per cursor page. */+const DEFAULT_ROUND_LIMIT = 10;+/** Default safety cap on rows scanned per cursor page. */+const DEFAULT_ROUND_COUNT_BUDGET = 2000;+/**+ * Row ceiling for the cursor path's underlying `queryWithWhere` fetch. The `where`+ * already bounds rows to the resolved round window; this only prevents an+ * unbounded scan and keeps `queryWithWhere`'s newest-first trim disabled (the+ * result stays below `pageSize`, so the trim guard never fires).+ */+const CURSOR_PAGE_CEILING = 100_000;++export class MessageConversationQueries extends MessageScope {+ private readonly lookups: MessageLookupQueries;+ private readonly page: MessagePageQueries;++ constructor(+ args: MessageScopeArgs,+ deps: { lookups: MessageLookupQueries; page: MessagePageQueries },+ ) {+ super(...args);+ this.lookups = deps.lookups;+ this.page = deps.page;+ }++ /**+ * The newest user message of each given topic, keyed by topic id. Used to+ * pre-inject recent same-channel history for IM platforms that can't read+ * chat history at runtime (e.g. WeChat). Only `role = 'user'` rows with+ * non-empty text are considered.+ */+ queryLastUserMessageByTopics = async (topicIds: string[]): Promise<Map<string, string>> => {+ if (topicIds.length === 0) return new Map();++ const rows = await this.db+ .selectDistinctOn([messages.topicId], {+ content: messages.content,+ topicId: messages.topicId,+ })+ .from(messages)+ .where(+ and(+ this.ownership(),+ inArray(messages.topicId, topicIds),+ eq(messages.role, 'user'),+ isNotNull(messages.content),+ ne(messages.content, ''),+ ),+ )+ .orderBy(messages.topicId, desc(messages.createdAt));++ const result = new Map<string, string>();+ for (const row of rows) {+ const content = (row.content ?? '').trim();+ if (row.topicId && content) result.set(row.topicId, content);+ }+ return result;+ };++ /**+ * Query messages by params (high-level API)+ *+ * This is the main query method that handles common query patterns.+ * For custom queries, use `queryWithWhere` directly.+ */+ query = async (+ {+ agentId,+ before,+ current = 0,+ includeFileWorks,+ pageSize = 1000,+ sessionId,+ skipWorks,+ topicId,+ groupId,+ threadId,+ }: QueryMessageParams = {},+ options: {+ /**+ * Opt IN to agent-share visitor messages. Visitor conversations persist+ * under the CREATOR's `userId` (only `topics.senderId` marks them), so+ * `this.ownership()` alone lets a creator read a visitor's full transcript+ * by passing its `topicId` β bypassing `allowCreatorViewSessions=false`.+ * Defaults to false so every creator-facing caller fails closed; only the+ * share-scoped read path ({@link MessageModel.queryForVisitor}) sets it.+ */+ allowShareVisitor?: boolean;+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ timing?: ModelTimingContext;+ /** See {@link QueryMessagesOptions.workAccessScope}. */+ workAccessScope?: WorkAccessScope;+ } = {},+ ) => {+ const queryStartedAt = Date.now();+ // Effective visitor gate: per-call `allowShareVisitor` OR the instance's+ // `includeShareVisitor`. Combined so `queryForVisitor(...)` still works+ // on a default-scoped instance (its explicit param overrides), AND a+ // share-runtime instance stops needing the param at every call site.+ const includeVisitor = options.allowShareVisitor || this.includeShareVisitor;+ const timing = options.timing;++ // Topic-scope shortcut: when the caller pins a `topicId` and hasn't opted+ // in to visitor rows, resolve the topic's `senderId` ONCE and either fail+ // closed (visitor topic) or drop the per-row NOT EXISTS predicate that+ // `queryWithWhere` / `queryMessageGroupNodes` would otherwise re-check for+ // every message in the topic. Every row inside a topic shares its parent+ // topic's visitor/creator identity, so a single indexed topic lookup is+ // strictly stronger than the correlated subquery repeated per row.+ let topicScopeVerified = false;+ if (topicId && !includeVisitor) {+ const scope = await this.resolveTopicVisitorScope(topicId);+ if (scope === 'visitor') {+ logTiming(timing, 'db.message.query:done', {+ messageCount: 0,+ stageMs: getDurationMs(queryStartedAt),+ });+ return [];+ }+ topicScopeVerified = true;+ }+ // `queryWithWhere` already ANDs `notShareVisitorMessage()` via+ // `ownership()`, so the previous per-branch `shareVisitorCondition` in+ // the `where` was pure duplication β dropped. When `topicScopeVerified`+ // is true the predicate is redundant altogether (the topic has been+ // classified once), and we pass that verdict downstream via+ // `allowShareVisitor: effectiveIncludeVisitor` so `queryWithWhere` swaps+ // its scope from `ownership()` to `workspaceScope()` and skips the+ // per-row NOT EXISTS.+ const effectiveIncludeVisitor = includeVisitor || topicScopeVerified;+ logTiming(timing, 'db.message.query:start', {+ current,+ hasAgentId: !!agentId,+ hasGroupId: !!groupId,+ hasSessionId: !!sessionId,+ hasThreadId: !!threadId,+ hasTopicId: !!topicId,+ pageSize,+ });++ // Build agent condition (handles legacy sessionId lookup)+ let agentCondition: SQL | undefined;+ if (agentId) {+ agentCondition = await runTimedStage(+ timing,+ 'db.message.query.buildAgentCondition',+ () => this.lookups.buildAgentCondition(agentId),+ { hasAgentId: true },+ );+ } else if (sessionId) {+ agentCondition = this.matchSession(sessionId);+ }++ // For thread queries, we need to fetch complete thread data (parent + thread messages)+ if (threadId) {+ const threadCondition = await runTimedStage(+ timing,+ 'db.message.query.buildThreadCondition',+ () => this.lookups.buildThreadQueryCondition(threadId),+ { hasThreadId: true },+ );+ // A topic thread may contain replies from delegated agents. When the topic is known,+ // scope the complete thread to it instead of filtering those replies by the parent agent.+ const threadScopeCondition = topicId ? this.matchTopic(topicId) : agentCondition;+ const messageItems = await this.page.queryWithWhere({+ allowShareVisitor: effectiveIncludeVisitor,+ before,+ current,+ includeFileWorks,+ pageSize,+ postProcessUrl: options.postProcessUrl,+ skipWorks,+ timing,+ topicId: topicId ?? undefined,+ workAccessScope: options.workAccessScope,+ where: and(threadScopeCondition, threadCondition),+ });+ logTiming(timing, 'db.message.query:done', {+ messageCount: messageItems.length,+ stageMs: getDurationMs(queryStartedAt),+ });+ return messageItems;+ }++ // For Group Chat queries: filter by groupId only (not agentId)+ // In Group Chat, all messages (user, supervisor, workers) should have groupId+ // and may have different agentIds, so we only filter by groupId + topicId+ if (groupId) {+ const whereCondition = and(+ eq(messages.groupId, groupId),+ this.matchTopic(topicId),+ this.matchThread(threadId),+ );++ const messageItems = await this.page.queryWithWhere({+ allowShareVisitor: effectiveIncludeVisitor,+ before,+ current,+ includeFileWorks,+ pageSize,+ postProcessUrl: options.postProcessUrl,+ skipWorks,+ timing,+ topicId: topicId ?? undefined,+ workAccessScope: options.workAccessScope,+ where: whereCondition,+ });+ logTiming(timing, 'db.message.query:done', {+ messageCount: messageItems.length,+ stageMs: getDurationMs(queryStartedAt),+ });+ return messageItems;+ }++ // A concrete topic is the conversation boundary and may legitimately+ // contain messages from multiple agents (for example callAgent replies).+ // Inbox queries have no topic, so they still require agent/session scope.+ const conversationCondition = topicId+ ? this.matchTopic(topicId)+ : and(agentCondition ?? this.matchSession(sessionId), this.matchTopic(topicId));++ // Standard query with conversation/topic/group filters+ const whereCondition = and(+ conversationCondition,+ this.matchGroup(groupId),+ this.matchThread(threadId),+ );++ const messageItems = await this.page.queryWithWhere({+ allowShareVisitor: effectiveIncludeVisitor,+ before,+ current,+ includeFileWorks,+ pageSize,+ postProcessUrl: options.postProcessUrl,+ skipWorks,+ timing,+ topicId: topicId ?? undefined,+ where: whereCondition,+ workAccessScope: options.workAccessScope,+ });+ logTiming(timing, 'db.message.query:done', {+ messageCount: messageItems.length,+ stageMs: getDurationMs(queryStartedAt),+ });+ return messageItems;+ };++ /**+ * Visitor-facing twin of {@link query} for agent-share reads.+ *+ * Share messages persist under the CREATOR's account (see `shareChat.ts`),+ * so `query()`'s joined `sender` and the billing/model-snapshot fields+ * describe the creator, not the visitor reading them. `redaction` carries the+ * share's own `showModelInfo` / `showErrorDetails` switches; omitting it+ * strips everything (fail closed).+ */+ queryForVisitor = async (+ params: QueryMessageParams = {},+ options: {+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ redaction?: VisitorRedactionOptions;+ timing?: ModelTimingContext;+ /**+ * The visitor's share scope for Work summaries. Omitting it skips Work+ * assembly entirely (fail closed): the ordinary scope would join the+ * CREATOR's Works, which must never reach a visitor surface.+ */+ workAccessScope?: WorkAccessScope;+ } = {},+ ): Promise<UIChatMessage[]> => {+ // The only caller allowed past `query()`'s visitor guard: the topic was+ // already resolved and authorized as this visitor's own share topic.+ const messageItems = await this.query(+ { ...params, skipWorks: params.skipWorks || !options.workAccessScope },+ { ...options, allowShareVisitor: true },+ );+ return messageItems.map((message) => toVisitorMessage(message, options.redaction));+ };++ /**+ * Exact per-topic turn count for one role, used by `maxTurnsPerTopic`.+ *+ * MUST NOT reuse {@link MessageModel.count}: its `analyticsConditions()` ANDs+ * in `notShareVisitorMessage()`, which excludes every message whose topic has+ * a non-null `senderId` β i.e. every agent-share visitor topic. That+ * predicate is correct for personal analytics (visitor usage is reported+ * separately), but it would make `count()` return 0 forever for a share+ * topic, silently disabling the turn cap.+ *+ * Safe without a visitor/ownership check here: the caller (shareChat router /+ * `reserveShareVisitorTurn`) already resolved and authorized the topic, and+ * `this.ownership()` matches because share messages carry the creator's+ * `userId` (the model is constructed with `share.ownerId`).+ */+ countByTopic = async ({ role, topicId }: { role: string; topicId: string }): Promise<number> => {+ const result = await this.db+ .select({ count: count(messages.id) })+ .from(messages)+ .where(and(this.ownership(), eq(messages.topicId, topicId), eq(messages.role, role)));++ return result[0].count;+ };++ /**+ * Return a lightweight, ownership-scoped transcript for a topic.+ *+ * Unlike the conversation query, this intentionally does not infer missing+ * session, group, or thread filters as `IS NULL`, and it does not replace raw+ * message-group members with synthetic nodes. Consumers such as the CLI need+ * the complete persisted transcript and exact database pagination.+ */+ queryTopicTranscript = async ({+ limit,+ offset,+ topicId,+ }: {+ limit: number;+ offset: number;+ topicId: string;+ }): Promise<TopicTranscriptResult> => {+ // Creator-facing only (CLI / topic transcript router): agent-share visitor+ // messages live under the creator's `userId`, so ownership alone would hand+ // the creator a visitor's full transcript from a raw topic id.+ const where = and(this.ownership(), eq(messages.topicId, topicId), notShareVisitorMessage());++ const [items, totalResult] = await Promise.all([+ this.db+ .select({+ agentId: messages.agentId,+ error: messages.error,+ metadata: messages.metadata,+ model: messages.model,+ pluginError: messagePlugins.error,+ provider: messages.provider,+ reasoning: messages.reasoning,+ toolCallId: messagePlugins.toolCallId,+ usage: messages.usage,+ content: messages.content,+ createdAt: messages.createdAt,+ id: messages.id,+ messageGroupId: messages.messageGroupId,+ parentId: messages.parentId,+ role: messages.role,+ threadId: messages.threadId,+ tools: messages.tools,+ })+ .from(messages)+ .leftJoin(messagePlugins, and(eq(messagePlugins.id, messages.id), this.pluginsOwnership()))+ .where(where)+ .orderBy(asc(messages.createdAt), asc(messages.id))+ .limit(limit)+ .offset(offset),+ this.db+ .select({ count: count(messages.id) })+ .from(messages)+ .where(where),+ ]);++ return {+ items: items.map(({ tools, usage, ...message }) => ({+ ...message,+ error: message.error as ChatMessageError | null,+ metadata: message.metadata as MessageMetadata | null,+ tools: Array.isArray(tools) ? (tools as ChatToolPayload[]) : null,+ usage: usage ?? message.metadata?.usage ?? null,+ })),+ total: totalResult[0]?.count ?? 0,+ };+ };++ /**+ * Lightweight parent/group links for the FULL message tree of a topic,+ * INCLUDING messages hidden inside MessageGroups (compression / parallel).+ *+ * `query` replaces grouped messages with synthetic group nodes that expose+ * neither their members' `parentId` nor (for compaction) the group's+ * `parentMessageId`, so branch-ancestry can't be reconstructed from `query`+ * output alone. This returns the raw `id β parentId` / `messageGroupId` links+ * so callers (e.g. server-runtime regenerate pruning) can walk ancestry across+ * a compacted range.+ */+ queryTopicMessageTree = async ({+ threadId,+ topicId,+ }: {+ threadId?: string | null;+ topicId: string;+ }): Promise<{ id: string; messageGroupId: string | null; parentId: string | null }[]> => {+ return this.db+ .select({+ id: messages.id,+ messageGroupId: messages.messageGroupId,+ parentId: messages.parentId,+ })+ .from(messages)+ .where(and(this.ownership(), this.matchTopic(topicId), this.matchThread(threadId)));+ };++ /**+ * Cursor-paginated read of a topic's mainline conversation, aligned to round+ * boundaries (a mainline `user` message starts a round). Built for callers that+ * only DISPLAY history and never resend it to the model β server-runtime+ * (gateway) and local hetero agents β where eagerly loading the whole transcript+ * is wasteful on long topics. Legacy client mode keeps using `query` (full+ * fetch) because it resends the entire session each turn.+ *+ * Initial load (`cursor` omitted) returns the newest `roundLimit` rounds, or+ * fewer if `countBudget` is reached first, but the current round is always+ * whole. Pass the returned `nextCursor` to load the previous rounds (scroll up).+ * Unlike offset paging, cursors land on round boundaries, so consecutive pages+ * are gap-free and never split a round.+ */+ queryTopicMessagesByCursor = async (+ {+ countBudget = DEFAULT_ROUND_COUNT_BUDGET,+ cursor,+ groupId,+ includeFileWorks,+ roundLimit = DEFAULT_ROUND_LIMIT,+ skipWorks,+ topicId,+ }: QueryTopicByCursorParams,+ options: {+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ timing?: ModelTimingContext;+ } = {},+ ): Promise<TopicMessagesByCursorResult> => {+ // Same visitor gate as `query`: a creator's read of an agent-share visitor+ // topic fails closed, and a verified creator topic skips the per-row check.+ if ((await this.resolveTopicVisitorScope(topicId)) === 'visitor') {+ return { hasMore: false, messages: [], nextCursor: null };+ }++ // Mainline = this topic (and its chat group, if any), not in a thread. Like+ // the standard `query`, a concrete topic is the conversation boundary: it is+ // NOT narrowed by agent/session, because a topic may legitimately hold rows+ // from several agents (e.g. `callAgent` / delegated replies).+ const mainlineWhere = and(+ this.matchTopic(topicId),+ this.matchGroup(groupId),+ this.matchThread(undefined),+ );++ const { lowerBound, hasMore } = await this.resolveRoundWindow({+ countBudget,+ cursor,+ mainlineWhere,+ roundLimit,+ });++ // MessageGroup nodes (compression / comparison) are partitioned across pages+ // by the same `[lowerBound, cursor)` window as mainline rows, so each group is+ // emitted exactly once over a full backward walk. The oldest page (`!hasMore`)+ // leaves the lower side open so groups dated before the first remaining+ // mainline row β including a topic whose whole history was compressed β stay+ // reachable instead of vanishing.+ const groupNodeWindow: MessageGroupNodeWindow = {+ before: cursor?.createdAt ?? null,+ from: hasMore && lowerBound ? lowerBound.createdAt : null,+ };++ // No lower bound means no mainline rows remain β either the topic has none+ // (e.g. compression moved every message into a group) or nothing older than+ // the cursor is left. The page is then group-only: fetch no mainline rows (an+ // unbounded `where` would wrongly reload the entire topic) but still assemble+ // the remaining group nodes.+ //+ // Otherwise bound the window on BOTH sides: at/after the resolved round start,+ // and β when paging older β strictly before the cursor. Without the upper+ // bound the window would also re-include every newer round already loaded.+ const where = lowerBound+ ? and(+ mainlineWhere,+ this.messageAtOrAfter(lowerBound),+ cursor ? this.messageStrictlyBefore(cursor) : undefined,+ )+ : sql`false`;++ const messages = await this.page.queryWithWhere({+ allowShareVisitor: true,+ current: 0,+ includeFileWorks,+ pageSize: CURSOR_PAGE_CEILING,+ postProcessUrl: options.postProcessUrl,+ skipWorks,+ timing: options.timing,+ topicId,+ where,+ // Only assemble group nodes within this page's window (not the whole topic),+ // so scroll-up pages don't repeat groups or eagerly load compressed history.+ groupNodeWindow,+ });++ // `lowerBound.createdAt` is already the lossless microsecond cursor string.+ return { hasMore, messages, nextCursor: hasMore && lowerBound ? lowerBound : null };+ };++ /**+ * Resolve the round window for a cursor page: walk mainline rows newest-first+ * and stop at the `roundLimit`-th round boundary (a `user` message) or the+ * `countBudget` safety cap, whichever comes first. Returns the lower bound (the+ * oldest included round's start) and whether older rounds remain.+ */+ private resolveRoundWindow = async ({+ countBudget,+ cursor,+ mainlineWhere,+ roundLimit,+ }: {+ countBudget: number;+ cursor?: MessageRoundCursor | null;+ mainlineWhere: SQL | undefined;+ roundLimit: number;+ }): Promise<{ hasMore: boolean; lowerBound: { createdAt: string; id: string } | null }> => {+ const olderThanCursor = cursor ? this.messageStrictlyBefore(cursor) : undefined;++ const rows = (await this.db+ .select({+ // Microsecond-precision UTC string. `createdAt` is a timestamptz whose+ // now() default can carry microseconds, but a JS Date keeps only+ // milliseconds β a Date-derived cursor would round sub-millisecond+ // boundaries and let rows leak between adjacent pages. Carry the lossless+ // value in the cursor and compare it back with a ::timestamptz cast.+ createdAtIso: sql<string>`to_char(${messages.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,+ id: messages.id,+ role: messages.role,+ })+ .from(messages)+ .where(and(this.ownership(), isNull(messages.messageGroupId), mainlineWhere, olderThanCursor))+ .orderBy(desc(messages.createdAt), desc(messages.id))+ .limit(countBudget + 1)) as { createdAtIso: string; id: string; role: string }[];++ if (rows.length === 0) return { hasMore: false, lowerBound: null };++ let rounds = 0;+ let boundaryIndex = -1;+ for (let i = 0; i < rows.length; i += 1) {+ if (rows[i].role === 'user') {+ rounds += 1;+ boundaryIndex = i;+ if (rounds >= roundLimit) break;+ }+ // Safety cap: once a full budget has been walked and at least one whole+ // round is captured, stop at the last boundary instead of scanning further.+ if (i + 1 >= countBudget && rounds >= 1) break;+ }++ // No `user` turn in the visible window β an oversized newest round, or a tail+ // with no user turn. Fall back to the oldest fetched row; that slice is a+ // partial round the renderer roots as an orphan chain. Lazy step loading is+ // the proper fix (a later stage).+ if (boundaryIndex === -1) boundaryIndex = rows.length - 1;++ const boundaryRow = rows[boundaryIndex];+ const hasMore = boundaryIndex < rows.length - 1 || rows.length > countBudget;++ return { hasMore, lowerBound: { createdAt: boundaryRow.createdAtIso, id: boundaryRow.id } };+ };++ /**+ * `(createdAt, id)` strictly before the cursor β the "older than" half-open+ * bound. Compares against the cursor's lossless microsecond string cast to+ * `timestamptz`, so sub-millisecond boundaries stay exact.+ */+ private messageStrictlyBefore = (cursor: MessageRoundCursor) =>+ or(+ sql`${messages.createdAt} < ${cursor.createdAt}::timestamptz`,+ and(+ sql`${messages.createdAt} = ${cursor.createdAt}::timestamptz`,+ lt(messages.id, cursor.id),+ ),+ );++ /** `(createdAt, id)` at or after the lower bound β the inclusive window start. */+ private messageAtOrAfter = (bound: { createdAt: string; id: string }) =>+ or(+ sql`${messages.createdAt} > ${bound.createdAt}::timestamptz`,+ and(sql`${messages.createdAt} = ${bound.createdAt}::timestamptz`, gte(messages.id, bound.id)),+ );+}diff --git a/packages/database/src/models/message/queryByIds.ts b/packages/database/src/models/message/queryByIds.tsnew file mode 100644index 00000000000..c0fb8542c41--- /dev/null+++ b/packages/database/src/models/message/queryByIds.ts@@ -0,0 +1,559 @@+import { parse } from '@lobechat/conversation-flow';+import type {+ ChatAudioItem,+ ChatFileItem,+ ChatVideoItem,+ ModelUsage,+ ThreadStatus,+ UIChatMessage,+} from '@lobechat/types';+import { MessageGroupType } from '@lobechat/types';+import { logTimingSink as logTiming, runTimedSinkStage as runTimedStage } from '@lobechat/utils';+import { and, asc, eq, gte, inArray, lte, sql } from 'drizzle-orm';+import pMap from 'p-map';++import {+ documents,+ files,+ messageGroups,+ messagePlugins,+ messageQueries,+ messages,+ messagesFiles,+ messageTranslates,+ messageTTS,+ threads,+ users,+} from '../../schemas';+import { notFileBackedPlaceholder } from '../../utils/fileBackedPlaceholder';+import { notShareVisitorTopicRef } from '../../utils/shareVisitor';+import { buildWorkspaceWhere } from '../../utils/workspace';+import type { FileDocumentsMap } from './attachments';+import {+ createChatImageItem,+ FILE_URL_POST_PROCESS_CONCURRENCY,+ fileDocumentColumns,+ fileDocumentsOrder,+ materializeChatAudioItem,+ toFileDocumentsMap,+} from './attachments';+import type { MessageRelationQueries } from './relations';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';+import type { MessageGroupNodeWindow, ModelTimingContext } from './types';++export class MessageByIdsQueries extends MessageScope {+ private readonly relations: MessageRelationQueries;++ constructor(args: MessageScopeArgs, deps: { relations: MessageRelationQueries }) {+ super(...args);+ this.relations = deps.relations;+ }++ /**+ * Query messages by their IDs with full relations+ *+ * This is useful for getting full message data when you already have the IDs.+ * It reuses the same transformation logic as queryWithWhere.+ *+ * @param messageIds - Array of message IDs to query+ * @param options - Query options (postProcessUrl for file URL transformation)+ * @returns Messages with all related data (files, plugins, translations, etc.)+ */+ queryByIds = async (+ messageIds: string[],+ options: {+ /**+ * Opt IN to agent-share visitor rows. Reserved for internal callers+ * (`queryMessageGroupNodes`) that already resolved and authorized the+ * parent topic via {@link resolveTopicVisitorScope}; every row shares+ * that topic's visitor/creator identity, so the per-row NOT EXISTS+ * predicate baked into `this.ownership()` is redundant once the topic+ * itself has been classified. External callers must leave this false.+ */+ allowShareVisitor?: boolean;+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ } = {},+ ): Promise<UIChatMessage[]> => {+ if (messageIds.length === 0) return [];++ const { postProcessUrl } = options;+ const scope =+ options.allowShareVisitor || this.includeShareVisitor+ ? this.workspaceScope()+ : this.ownership();++ // 1. Query messages with joins+ const result = await this.db+ .select({+ id: messages.id,+ role: messages.role,+ content: messages.content,+ editorData: messages.editorData,+ reasoning: messages.reasoning,+ search: messages.search,+ metadata: messages.metadata,+ usage: messages.usage,+ error: messages.error,++ model: messages.model,+ provider: messages.provider,++ createdAt: messages.createdAt,+ updatedAt: messages.updatedAt,++ sessionId: messages.sessionId,+ topicId: messages.topicId,+ parentId: messages.parentId,+ threadId: messages.threadId,++ // Group chat fields+ groupId: messages.groupId,+ agentId: messages.agentId,+ targetId: messages.targetId,++ sender: {+ // `id` MUST be the first selected field β see queryWithWhere's sender+ // selection for why (drizzle left-join nested-object nullification).+ id: users.id,+ avatar: users.avatar,+ fullName: users.fullName,+ username: users.username,+ },++ tools: messages.tools,+ tool_call_id: messagePlugins.toolCallId,++ plugin: {+ apiName: messagePlugins.apiName,+ arguments: messagePlugins.arguments,+ identifier: messagePlugins.identifier,+ type: messagePlugins.type,+ },+ pluginError: messagePlugins.error,+ pluginIntervention: messagePlugins.intervention,+ pluginState: messagePlugins.state,++ translate: {+ content: messageTranslates.content,+ from: messageTranslates.from,+ to: messageTranslates.to,+ },++ ttsId: messageTTS.id,+ ttsContentMd5: messageTTS.contentMd5,+ ttsFile: messageTTS.fileId,+ ttsVoice: messageTTS.voice,+ })+ .from(messages)+ .where(and(scope, inArray(messages.id, messageIds)))+ .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))+ .leftJoin(messageTranslates, eq(messageTranslates.id, messages.id))+ .leftJoin(messageTTS, eq(messageTTS.id, messages.id))+ .leftJoin(users, eq(users.id, messages.userId))+ .orderBy(asc(messages.createdAt));++ if (result.length === 0) return [];++ // 2. Run parallel queries for better performance+ const taskMessageIds = result.filter((m) => m.role === 'task').map((m) => m.id as string);++ const [rawRelatedFileList, chunksList, messageQueriesList, threadData] = await Promise.all([+ // 2a. Get related files+ this.db+ .select({+ fileType: files.fileType,+ id: messagesFiles.fileId,+ messageId: messagesFiles.messageId,+ metadata: files.metadata,+ name: files.name,+ size: files.size,+ url: files.url,+ })+ .from(messagesFiles)+ // Same anti-leak guard as queryMessageFileRelations: tombstone files+ // the viewer lost access to instead of leaking name/size/url.+ .leftJoin(+ files,+ and(+ eq(files.id, messagesFiles.fileId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),+ ),+ )+ .where(inArray(messagesFiles.messageId, messageIds)),++ // 2b. Get related file chunks (visibility-guarded like queryWithWhere)+ this.relations.queryMessageChunkRelations(messageIds),++ // 2c. Get related message queries (RAG)+ this.db+ .select({+ id: messageQueries.id,+ messageId: messageQueries.messageId,+ rewriteQuery: messageQueries.rewriteQuery,+ userQuery: messageQueries.userQuery,+ })+ .from(messageQueries)+ .where(inArray(messageQueries.messageId, messageIds)),++ // 2d. Get thread info for task messages+ taskMessageIds.length > 0+ ? this.db+ .select({+ metadata: threads.metadata,+ sourceMessageId: threads.sourceMessageId,+ status: threads.status,+ threadId: threads.id,+ title: threads.title,+ })+ .from(threads)+ .where(+ and(+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ threads,+ ),+ inArray(threads.sourceMessageId, taskMessageIds),+ ),+ )+ : Promise.resolve([]),+ ]);++ // 3. Process file results+ const relatedFileList = await pMap(+ rawRelatedFileList,+ async (file) => {+ // Tombstoned by the visibility guard above β nothing to presign.+ if (file.name === null) return { ...file, url: '' };+ return {+ ...file,+ url: postProcessUrl+ ? await postProcessUrl(+ file.url,+ file as unknown as { fileType: string; id?: string | null },+ )+ : (file.url as string),+ };+ },+ { concurrency: FILE_URL_POST_PROCESS_CONCURRENCY },+ );++ // Get associated document content. Exclude tombstoned files β their parsed+ // document content must not leak through the unguarded documents join.+ const fileIds = relatedFileList+ .filter((file) => file.name !== null)+ .map((file) => file.id)+ .filter(Boolean);++ let documentsMap: FileDocumentsMap = {};++ if (fileIds.length > 0) {+ const documentsList = await this.db+ .select(fileDocumentColumns)+ .from(documents)+ .where(and(inArray(documents.fileId, fileIds), notFileBackedPlaceholder()))+ .orderBy(...fileDocumentsOrder);++ documentsMap = toFileDocumentsMap(documentsList);+ }++ const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));+ const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));+ const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));+ const fileList = relatedFileList.filter(+ (i) =>+ !(i.fileType || '').startsWith('image') &&+ !(i.fileType || '').startsWith('video') &&+ !(i.fileType || '').startsWith('audio'),+ );++ // 4. Build thread map+ const threadMap = new Map(+ threadData.map((t) => {+ const metadata = t.metadata as Record<string, unknown> | null;+ return [+ t.sourceMessageId!,+ {+ clientMode: metadata?.clientMode as boolean | undefined,+ duration: metadata?.duration as number | undefined,+ status: t.status as ThreadStatus,+ threadId: t.threadId,+ title: t.title ?? undefined,+ totalCost: metadata?.totalCost as number | undefined,+ totalMessages: metadata?.totalMessages as number | undefined,+ totalTokens: metadata?.totalTokens as number | undefined,+ totalToolCalls: metadata?.totalToolCalls as number | undefined,+ },+ ];+ }),+ );++ // 6. Transform messages to UIChatMessage format+ return result.map(+ ({+ model,+ provider,+ translate,+ ttsId,+ ttsFile,+ ttsContentMd5,+ ttsVoice,+ sender,+ ...item+ }) => {+ const messageQuery = messageQueriesList.find((relation) => relation.messageId === item.id);+ return {+ ...item,+ // Same presence contract as queryWithWhere: collapse a null-id sender+ // (deleted account) to `null` so clients can rely on `sender?.id`.+ sender: sender?.id ? sender : null,+ chunksList: chunksList+ .filter((relation) => relation.messageId === item.id)+ .map((c) => ({+ ...c,+ similarity: c.similarity === null ? undefined : Number(c.similarity),+ })),++ extra: {+ model,+ provider,+ translate,+ tts: ttsId+ ? {+ contentMd5: ttsContentMd5,+ file: ttsFile,+ voice: ttsVoice,+ }+ : undefined,+ },+ fileList: fileList+ .filter((relation) => relation.messageId === item.id)+ .map<ChatFileItem>(({ id, url, size, fileType, name }) =>+ // Nulled by the visibility guard: the viewer lost access to the+ // referenced file. Emit a tombstone (id only) so the UI renders+ // a no-access placeholder.+ name === null+ ? { fileType: '', id, inaccessible: true, name: '', size: 0, url: '' }+ : {+ content: documentsMap[id]?.content,+ originalCharCount: documentsMap[id]?.originalCharCount,+ fileType: fileType!,+ id,+ name,+ size: size!,+ url,+ },+ ),+ imageList: imageList+ .filter((relation) => relation.messageId === item.id)+ .map(({ fileType, id, metadata, name, url }) =>+ createChatImageItem({ fileType, id, metadata, name: name!, url }),+ ),++ model,++ provider,+ ragQuery: messageQuery?.rewriteQuery,+ ragQueryId: messageQuery?.id,+ ragRawQuery: messageQuery?.userQuery,+ // Add taskDetail for task messages+ taskDetail: item.role === 'task' ? threadMap.get(item.id as string) : undefined,+ // Prefer the dedicated `usage` column, falling back to legacy+ // `metadata.usage` for rows written before the migration.+ usage: item.usage ?? (item.metadata as { usage?: ModelUsage } | null)?.usage,+ videoList: videoList+ .filter((relation) => relation.messageId === item.id)+ .map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),+ audioList: audioList+ .filter((relation) => relation.messageId === item.id)+ .map<ChatAudioItem>(materializeChatAudioItem),+ } as unknown as UIChatMessage;+ },+ );+ };++ /**+ * Query MessageGroup nodes for a topic+ * - compressedGroup: includes pinnedMessages and compressedMessages arrays+ * - compareGroup: includes children array+ *+ * @param topicId - The topic ID to query groups for+ * @param timeRange - Optional time range to filter groups (for pagination support)+ */+ queryMessageGroupNodes = async (+ topicId: string,+ timeRange?: { endTime: Date; startTime: Date },+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>,+ timing?: ModelTimingContext,+ options: { allowShareVisitor?: boolean; window?: MessageGroupNodeWindow } = {},+ ): Promise<UIChatMessage[]> => {+ // Effective visitor gate β see `queryMessageGroupNodesForPage`. Absent+ // this predicate, a creator's default `query({ topicId })` on a visitor+ // topic returns no messages but still returns the group's synthetic+ // `compressedGroup` node (with its `content` summary) or `compareGroup`+ // node, leaking the visitor conversation shape.+ const includeVisitor = options.allowShareVisitor || this.includeShareVisitor;++ // 1. Query MessageGroups for this topic, optionally filtered by time range+ const whereConditions = [+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups),+ eq(messageGroups.topicId, topicId),+ ...(includeVisitor ? [] : [notShareVisitorTopicRef(messageGroups.topicId)]),+ ];++ // Add time range filter if provided (for pagination)+ if (timeRange) {+ whereConditions.push(+ gte(messageGroups.createdAt, timeRange.startTime),+ lte(messageGroups.createdAt, timeRange.endTime),+ );+ }++ // Explicit half-open `[from, before)` window from cursor pagination, compared+ // against lossless microsecond strings so page boundaries stay exact.+ if (options.window?.from) {+ whereConditions.push(sql`${messageGroups.createdAt} >= ${options.window.from}::timestamptz`);+ }+ if (options.window?.before) {+ whereConditions.push(sql`${messageGroups.createdAt} < ${options.window.before}::timestamptz`);+ }++ const groups = await runTimedStage(+ timing,+ 'db.message.messageGroups.groups.select',+ () =>+ this.db+ .select()+ .from(messageGroups)+ .where(and(...whereConditions))+ .orderBy(asc(messageGroups.createdAt)),+ { hasTimeRange: !!timeRange, topicId },+ );+ logTiming(timing, 'db.message.messageGroups.groups.select:rows', { rowCount: groups.length });++ if (groups.length === 0) return [];++ const groupIds = groups.map((g) => g.id);++ // 2. Get all message IDs that belong to these groups (using messageGroupId relation)+ const groupMessageRecords = await runTimedStage(+ timing,+ 'db.message.messageGroups.messages.select',+ () =>+ this.db+ .select({+ favorite: messages.favorite,+ id: messages.id,+ messageGroupId: messages.messageGroupId,+ })+ .from(messages)+ .where(+ and(+ // The parent topic has already been classified by the caller+ // (via `resolveTopicVisitorScope`) or the model was constructed+ // as a share-runtime instance β either way, the per-row NOT+ // EXISTS predicate baked into `ownership()` is redundant for+ // messages that belong to a group inside a verified topic.+ includeVisitor ? this.workspaceScope() : this.ownership(),+ inArray(messages.messageGroupId, groupIds),+ ),+ )+ .orderBy(asc(messages.createdAt)),+ { groupCount: groupIds.length },+ );+ logTiming(timing, 'db.message.messageGroups.messages.select:rows', {+ rowCount: groupMessageRecords.length,+ });++ // 3. Query full message data using queryByIds (reuses all transformation logic)+ const allMessageIds = groupMessageRecords.map((m) => m.id as string);+ const fullMessages = await runTimedStage(+ timing,+ 'db.message.messageGroups.queryByIds',+ () => this.queryByIds(allMessageIds, { allowShareVisitor: includeVisitor, postProcessUrl }),+ { messageCount: allMessageIds.length },+ );++ // Create a map for quick lookup+ const messageMap = new Map(fullMessages.map((m) => [m.id, m]));+ const favoriteMap = new Map(groupMessageRecords.map((m) => [m.id, m.favorite]));++ // 4. Build MessageGroup nodes+ return groups.map((group) => {+ // Get messages for this group+ const groupMsgIds = groupMessageRecords+ .filter((m) => m.messageGroupId === group.id)+ .map((m) => m.id as string);++ const groupMsgs = groupMsgIds+ .map((id) => messageMap.get(id))+ .filter(Boolean) as UIChatMessage[];++ if (group.type === MessageGroupType.Compression) {+ // compressedGroup: extract pinnedMessages (favorite=true)+ const pinnedMessages = groupMsgIds+ .filter((id) => favoriteMap.get(id) === true)+ .map((id) => {+ const m = messageMap.get(id);+ return m+ ? {+ content: m.content,+ createdAt: m.createdAt,+ id: m.id,+ model: m.model,+ provider: m.provider,+ role: m.role,+ }+ : null;+ })+ .filter(Boolean);++ // compressedMessages: parse messages through conversation-flow for proper grouping+ // This transforms raw messages into displayMessages format (e.g., assistantGroup)+ const { flatList } = parse(groupMsgs);+ const compressedMessages = flatList;++ // Get the last message ID for parent-child linking in conversation-flow+ const lastMessageId = groupMsgIds.at(-1);++ return {+ compressedMessages,+ content: group.content,+ createdAt: group.createdAt,+ id: group.id,+ lastMessageId,+ metadata: group.metadata,+ pinnedMessages,+ role: 'compressedGroup',+ topicId: group.topicId,+ updatedAt: group.updatedAt,+ } as unknown as UIChatMessage;+ } else {+ // compareGroup (parallel): include children with basic info+ const children = groupMsgs.map((m) => ({+ content: m.content,+ createdAt: m.createdAt,+ id: m.id,+ model: m.model,+ provider: m.provider,+ role: m.role,+ }));++ return {+ children,+ createdAt: group.createdAt,+ id: group.id,+ role: 'compareGroup',+ topicId: group.topicId,+ updatedAt: group.updatedAt,+ } as unknown as UIChatMessage;+ }+ });+ };+}diff --git a/packages/database/src/models/message/queryWithWhere.ts b/packages/database/src/models/message/queryWithWhere.tsnew file mode 100644index 00000000000..c536a4815ad--- /dev/null+++ b/packages/database/src/models/message/queryWithWhere.ts@@ -0,0 +1,489 @@+import type {+ ChatAudioItem,+ ChatFileItem,+ ChatVideoItem,+ ModelUsage,+ UIChatMessage,+ WorkSummaryItem,+} from '@lobechat/types';+import {+ getDurationMs,+ logTimingSink as logTiming,+ runTimedSinkStage as runTimedStage,+} from '@lobechat/utils';+import { and, desc, eq, isNull, lt, or } from 'drizzle-orm';++import { messagePlugins, messages, messageTranslates, messageTTS, users } from '../../schemas';+import { createChatImageItem, materializeChatAudioItem } from './attachments';+import type { MessageByIdsQueries } from './queryByIds';+import type { MessageRelationQueries } from './relations';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';+import type { MessageGroupNodeWindow, ModelTimingContext, QueryMessagesOptions } from './types';++export class MessagePageQueries extends MessageScope {+ private readonly relations: MessageRelationQueries;+ private readonly byIds: MessageByIdsQueries;++ constructor(+ args: MessageScopeArgs,+ deps: { relations: MessageRelationQueries; byIds: MessageByIdsQueries },+ ) {+ super(...args);+ this.relations = deps.relations;+ this.byIds = deps.byIds;+ }++ /**+ * Query messages with full relations (files, plugins, translations, etc.)+ *+ * This is the low-level query method that accepts a custom where condition.+ * Use this for building custom query scenarios.+ *+ * Features:+ * - Filters out messages that belong to MessageGroups (compression/parallel)+ * - Includes MessageGroup nodes (compressedGroup/compareGroup) in the result+ * - compressedGroup nodes include pinnedMessages array (favorite=true messages)+ * - compareGroup nodes include children array (parallel messages)+ *+ * @param options - Query options including where condition and pagination+ * @returns Messages with all related data, including MessageGroup nodes+ */+ queryWithWhere = async (options: QueryMessagesOptions = {}): Promise<UIChatMessage[]> => {+ const {+ where,+ before,+ current = 0,+ includeFileWorks,+ pageSize = 1000,+ postProcessUrl,+ skipWorks,+ topicId,+ timing,+ allowShareVisitor,+ workAccessScope,+ groupNodeWindow,+ } = options;+ const totalStartedAt = Date.now();+ const offset = current * pageSize;+ // See {@link QueryMessagesOptions.allowShareVisitor}. Combined with the+ // instance's `includeShareVisitor` so either widens the scope.+ const scope =+ allowShareVisitor || this.includeShareVisitor ? this.workspaceScope() : this.ownership();++ // Round-cursor paging: only rows strictly older than the `(createdAt, id)`+ // tuple. The id tie-break mirrors the sort order below, so rows sharing a+ // createdAt with the cursor are neither skipped nor duplicated.+ const beforeCondition = before+ ? or(+ lt(messages.createdAt, before.createdAt),+ and(eq(messages.createdAt, before.createdAt), lt(messages.id, before.id)),+ )+ : undefined;++ // 1. get basic messages with joins, excluding messages that belong to MessageGroups+ const result = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.baseSelect',+ () =>+ this.db+ .select({+ id: messages.id,+ role: messages.role,+ content: messages.content,+ editorData: messages.editorData,+ reasoning: messages.reasoning,+ search: messages.search,+ metadata: messages.metadata,+ usage: messages.usage,+ error: messages.error,++ model: messages.model,+ provider: messages.provider,++ createdAt: messages.createdAt,+ updatedAt: messages.updatedAt,++ sessionId: messages.sessionId,+ topicId: messages.topicId,+ parentId: messages.parentId,+ threadId: messages.threadId,++ // Group chat fields+ groupId: messages.groupId,+ agentId: messages.agentId,+ targetId: messages.targetId,++ sender: {+ // `id` MUST be the first selected field: drizzle decides whether a+ // left-joined nested selection is null from its first column, so+ // leading with a nullable column (avatar) collapsed every+ // avatar-less sender to `sender: null`.+ id: users.id,+ avatar: users.avatar,+ fullName: users.fullName,+ username: users.username,+ },++ tools: messages.tools,+ tool_call_id: messagePlugins.toolCallId,++ plugin: {+ apiName: messagePlugins.apiName,+ arguments: messagePlugins.arguments,+ identifier: messagePlugins.identifier,+ type: messagePlugins.type,+ },+ pluginError: messagePlugins.error,+ pluginIntervention: messagePlugins.intervention,+ pluginState: messagePlugins.state,++ translate: {+ content: messageTranslates.content,+ from: messageTranslates.from,+ to: messageTranslates.to,+ },++ ttsId: messageTTS.id,+ ttsContentMd5: messageTTS.contentMd5,+ ttsFile: messageTTS.fileId,+ ttsVoice: messageTTS.voice,+ })+ .from(messages)+ .where(+ and(+ scope,+ // Filter out messages that belong to MessageGroups+ isNull(messages.messageGroupId),+ where,+ beforeCondition,+ ),+ )+ .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id))+ .leftJoin(messageTranslates, eq(messageTranslates.id, messages.id))+ .leftJoin(messageTTS, eq(messageTTS.id, messages.id))+ .leftJoin(users, eq(users.id, messages.userId))+ // Page from the NEWEST messages, not the oldest. `desc` + limit/offset+ // fetches the most recent `pageSize` rows, so a topic with more than+ // `pageSize` mainline messages keeps its latest turns (including the+ // final answer) instead of silently dropping them β the previous+ // `asc + limit` truncated exactly the newest batch, which is the worst+ // possible slice for a chat transcript. The page is reversed back to+ // ascending immediately below, so every downstream consumer is+ // unaffected; only *which* rows are fetched changed. See.+ .orderBy(desc(messages.createdAt), desc(messages.id))+ .limit(pageSize)+ .offset(offset),+ { current, pageSize },+ );+ logTiming(timing, 'db.message.queryWithWhere.baseSelect:rows', { rowCount: result.length });++ // Restore ascending (createdAt, id) order so downstream assembly β the+ // MessageGroup time window, work-summary anchoring, and the final merge sort β+ // behaves exactly as before the newest-first fetch above.+ result.reverse();++ // When the newest page is truncated (it filled `pageSize`), its oldest rows+ // may sit mid-round. The renderer roots a slice at a single parent, so a slice+ // cut inside a round can strand sibling chains and drop them from the screen.+ // Align the lower boundary to a round start β a mainline `user` message β so+ // the slice is one contiguous chain. Never trim to empty: an oversized single+ // round with no user message in view is kept whole (the proper fix for those+ // is lazy step loading). Thread queries pass no `topicId` and are untouched.+ //+ // Scope: this serves the single "most recent page" load (`current === 0`)+ // and the round-cursor `before` pages that walk older history β the only+ // shapes the chat read path requests; `current`/`pageSize` offset paging is+ // dead code here (the very premise of). The trim is deliberately NOT+ // offset-exact: rows dropped from one page reappear at the TOP of the next+ // `before` page (its cursor is the trimmed page's oldest kept row), so the+ // round-cursor walk loses nothing by construction.+ if (topicId && (current === 0 || before) && result.length >= pageSize) {+ const firstRoundStart = result.findIndex((message) => message.role === 'user');+ if (firstRoundStart > 0) result.splice(0, firstRoundStart);+ }++ const messageIds = result.map((message) => message.id as string);++ const messageGroupNodesPromise = this.queryMessageGroupNodesForPage({+ allowShareVisitor: allowShareVisitor || this.includeShareVisitor,+ current,+ hasBeforeCursor: !!before,+ postProcessUrl,+ result,+ timing,+ topicId,+ window: groupNodeWindow,+ });++ const taskMessageIds = result+ .filter((message) => message.role === 'task')+ .map((message) => {+ return message.id as string;+ });++ const [+ messageGroupNodes,+ { documentsMap, relatedFileList },+ chunksList,+ messageQueriesList,+ threadData,+ worksByMessageId,+ ] = await Promise.all([+ messageGroupNodesPromise,+ this.relations.queryMessageFileRelations(messageIds, postProcessUrl, timing),+ this.relations.queryMessageChunkRelations(messageIds, timing),+ this.relations.queryMessageQueryRelations(messageIds, timing),+ this.relations.queryMessageThreadRelations(taskMessageIds, timing),+ skipWorks+ ? ({} as Record<string, WorkSummaryItem[]>)+ : this.relations.queryMessageWorkSummaries(+ result,+ includeFileWorks,+ timing,+ workAccessScope,+ ),+ ]);++ if (messageIds.length === 0 && messageGroupNodes.length === 0) {+ logTiming(timing, 'db.message.queryWithWhere:done', {+ messageGroupCount: 0,+ rowCount: 0,+ stageMs: getDurationMs(totalStartedAt),+ });+ return [];+ }++ const imageList = relatedFileList.filter((i) => (i.fileType || '').startsWith('image'));+ const videoList = relatedFileList.filter((i) => (i.fileType || '').startsWith('video'));+ const audioList = relatedFileList.filter((i) => (i.fileType || '').startsWith('audio'));+ const fileList = relatedFileList.filter(+ (i) =>+ !(i.fileType || '').startsWith('image') &&+ !(i.fileType || '').startsWith('video') &&+ !(i.fileType || '').startsWith('audio'),+ );++ const threadMap = this.relations.createThreadMap(threadData);++ // 6. Transform regular messages+ const transformedMessages = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.transform',+ () =>+ result.map(+ ({+ model,+ provider,+ translate,+ ttsId,+ ttsFile,+ ttsContentMd5,+ ttsVoice,+ sender,+ ...item+ }) => {+ const messageQuery = messageQueriesList.find(+ (relation) => relation.messageId === item.id,+ );+ return {+ ...item,+ // LEFT JOIN β users row is null only when the sender account was+ // deleted (rare, since `messages.user_id` cascades on user delete).+ // Collapse a null-id sender to `null` so the client can rely on+ // `sender?.id` as the presence check.+ sender: sender?.id ? sender : null,+ chunksList: chunksList+ .filter((relation) => relation.messageId === item.id)+ .map((c) => ({+ ...c,+ similarity: c.similarity === null ? undefined : Number(c.similarity),+ })),++ extra: {+ model,+ provider,+ translate,+ tts: ttsId+ ? {+ contentMd5: ttsContentMd5,+ file: ttsFile,+ voice: ttsVoice,+ }+ : undefined,+ },+ fileList: fileList+ .filter((relation) => relation.messageId === item.id)++ .map<ChatFileItem>(({ id, url, size, fileType, name }) =>+ // Nulled by the visibility guard: the viewer lost access to+ // the referenced file. Emit a tombstone (id only) so the UI+ // renders a no-access placeholder.+ name === null+ ? { fileType: '', id, inaccessible: true, name: '', size: 0, url: '' }+ : {+ content: documentsMap[id]?.content,+ originalCharCount: documentsMap[id]?.originalCharCount,+ fileType: fileType!,+ id,+ name,+ size: size!,+ url,+ },+ ),+ imageList: imageList+ .filter((relation) => relation.messageId === item.id)+ .map(({ fileType, id, metadata, name, url }) =>+ createChatImageItem({ fileType, id, metadata, name: name!, url }),+ ),++ model,++ provider,+ ragQuery: messageQuery?.rewriteQuery,+ ragQueryId: messageQuery?.id,+ ragRawQuery: messageQuery?.userQuery,+ // Add taskDetail for task messages+ taskDetail: item.role === 'task' ? threadMap.get(item.id as string) : undefined,+ // Prefer the dedicated `usage` column, falling back to legacy+ // `metadata.usage` for rows written before the migration.+ usage: item.usage ?? (item.metadata as { usage?: ModelUsage } | null)?.usage,+ videoList: videoList+ .filter((relation) => relation.messageId === item.id)++ .map<ChatVideoItem>(({ id, url, name }) => ({ alt: name!, id, url })),+ // Work summaries for this message's root operation, resolved+ // server-side (attached only to the round's anchor message).+ works: worksByMessageId[item.id as string],+ audioList: audioList+ .filter((relation) => relation.messageId === item.id)+ .map<ChatAudioItem>(materializeChatAudioItem),+ } as unknown as UIChatMessage;+ },+ ),+ {+ chunkCount: chunksList.length,+ fileCount: relatedFileList.length,+ messageQueryCount: messageQueriesList.length,+ rowCount: result.length,+ },+ );++ // 7. Merge regular messages with MessageGroup nodes and sort by createdAt+ const allItems = [...transformedMessages, ...messageGroupNodes];+ allItems.sort((a, b) => {+ const aTime = new Date(a.createdAt).getTime();+ const bTime = new Date(b.createdAt).getTime();+ return aTime - bTime;+ });++ logTiming(timing, 'db.message.queryWithWhere:done', {+ messageGroupCount: messageGroupNodes.length,+ resultCount: allItems.length,+ rowCount: result.length,+ stageMs: getDurationMs(totalStartedAt),+ });++ return allItems;+ };++ private queryMessageGroupNodesForPage = async ({+ allowShareVisitor,+ current,+ hasBeforeCursor,+ postProcessUrl,+ result,+ timing,+ topicId,+ window,+ }: {+ /**+ * Effective visitor gate resolved by the caller (per-call+ * `allowShareVisitor` OR the instance's `includeShareVisitor`). Threaded+ * through so the underlying `messageGroups` where-clause fails closed on+ * a creator's default read of a visitor topic β otherwise a bare+ * workspace/topicId filter would still surface the group's synthetic+ * `compressedGroup`/`compareGroup` nodes (with content summaries) even+ * though the row query returned nothing.+ */+ allowShareVisitor?: boolean;+ current: number;+ /**+ * The page was fetched with a round-cursor (`before`): scope group nodes to+ * the page's time window instead of the whole topic β page 0 already+ * returned every group node, so an unwindowed fetch here would only+ * duplicate them.+ */+ hasBeforeCursor?: boolean;+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ result: { createdAt: Date }[];+ timing?: ModelTimingContext;+ topicId?: string;+ /** Explicit group window (cursor pagination); overrides the row-derived one. */+ window?: MessageGroupNodeWindow;+ }): Promise<UIChatMessage[]> => {+ if (!topicId) return [];++ if (window) {+ return runTimedStage(+ timing,+ 'db.message.queryWithWhere.messageGroups',+ () =>+ this.byIds.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {+ allowShareVisitor,+ window,+ }),+ { current, hasMessages: result.length > 0, topicId },+ );+ }++ if (result.length === 0) {+ if (current !== 0 || hasBeforeCursor) return [];++ return runTimedStage(+ timing,+ 'db.message.queryWithWhere.messageGroups',+ () =>+ this.byIds.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {+ allowShareVisitor,+ }),+ { current, hasMessages: false, topicId },+ );+ }++ if (current === 0 && !hasBeforeCursor) {+ return runTimedStage(+ timing,+ 'db.message.queryWithWhere.messageGroups',+ () =>+ this.byIds.queryMessageGroupNodes(topicId, undefined, postProcessUrl, timing, {+ allowShareVisitor,+ }),+ { current, hasMessages: true, topicId },+ );+ }++ const firstMessageTime = result[0].createdAt;+ const lastMessageTime = result.at(-1)!.createdAt;++ return runTimedStage(+ timing,+ 'db.message.queryWithWhere.messageGroups',+ () =>+ this.byIds.queryMessageGroupNodes(+ topicId,+ {+ endTime: lastMessageTime,+ startTime: firstMessageTime,+ },+ postProcessUrl,+ timing,+ { allowShareVisitor },+ ),+ { current, hasMessages: true, topicId },+ );+ };+}diff --git a/packages/database/src/models/message/relations.ts b/packages/database/src/models/message/relations.tsnew file mode 100644index 00000000000..d195498f8a6--- /dev/null+++ b/packages/database/src/models/message/relations.ts@@ -0,0 +1,326 @@+import type { TaskDetail, ThreadStatus, WorkAccessScope, WorkSummaryItem } from '@lobechat/types';+import { logTimingSink as logTiming, runTimedSinkStage as runTimedStage } from '@lobechat/utils';+import { and, eq, inArray } from 'drizzle-orm';+import pMap from 'p-map';++import {+ chunks,+ documents,+ fileChunks,+ files,+ messageQueries,+ messageQueryChunks,+ messagesFiles,+ threads,+} from '../../schemas';+import { notFileBackedPlaceholder } from '../../utils/fileBackedPlaceholder';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { WorkModel } from '../work';+import type { FileDocumentsMap, MessageRelatedFile } from './attachments';+import {+ FILE_URL_POST_PROCESS_CONCURRENCY,+ fileDocumentColumns,+ fileDocumentsOrder,+ getMessageWorkRootId,+ toFileDocumentsMap,+} from './attachments';+import { MessageScope } from './scope';+import type { ModelTimingContext, QueryMessagesOptions } from './types';++interface MessageChunkRelation {+ fileId: string;+ filename: string | null;+ fileType: string | null;+ fileUrl: string | null;+ id: string | null;+ messageId: string | null;+ similarity: string | null;+ text: string | null;+}++interface MessageQueryRelation {+ id: string;+ messageId: string;+ rewriteQuery: string | null;+ userQuery: string | null;+}++interface MessageThreadRelation {+ metadata: unknown;+ sourceMessageId: string | null;+ status: string | null;+ threadId: string;+ title: string | null;+}++interface MessageFileRelations {+ documentsMap: FileDocumentsMap;+ relatedFileList: MessageRelatedFile[];+}++export class MessageRelationQueries extends MessageScope {+ queryMessageFileRelations = async (+ messageIds: string[],+ postProcessUrl: QueryMessagesOptions['postProcessUrl'],+ timing?: ModelTimingContext,+ ): Promise<MessageFileRelations> => {+ if (messageIds.length === 0) return { documentsMap: {}, relatedFileList: [] };++ const rawRelatedFileList = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.relatedFiles.select',+ () =>+ this.db+ .select({+ fileType: files.fileType,+ id: messagesFiles.fileId,+ messageId: messagesFiles.messageId,+ metadata: files.metadata,+ name: files.name,+ size: files.size,+ url: files.url,+ })+ .from(messagesFiles)+ // Guard the referenced file, not just the relation: in a shared+ // conversation (chat group / workspace task) the message is visible+ // to every member, but a file its owner switched back to private+ // must degrade to a tombstone (id only) instead of leaking+ // name/size/url. Same anti-leak join pattern as the agent knowledge+ // reads in agent.ts.+ .leftJoin(+ files,+ and(+ eq(files.id, messagesFiles.fileId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),+ ),+ )+ .where(inArray(messagesFiles.messageId, messageIds)),+ { messageCount: messageIds.length },+ );+ logTiming(timing, 'db.message.queryWithWhere.relatedFiles.select:rows', {+ rowCount: rawRelatedFileList.length,+ });++ const relatedFileList = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.relatedFiles.postProcess',+ () =>+ pMap(+ rawRelatedFileList,+ async (file) => {+ // Tombstoned by the visibility guard above β nothing to presign.+ if (file.name === null) return { ...file, url: '' };+ return {+ ...file,+ url: postProcessUrl+ ? await postProcessUrl(+ file.url,+ file as unknown as { fileType: string; id?: string | null },+ )+ : (file.url as string),+ };+ },+ { concurrency: FILE_URL_POST_PROCESS_CONCURRENCY },+ ),+ { fileCount: rawRelatedFileList.length },+ );++ // Exclude tombstoned files β their parsed document content must not leak+ // through the unguarded documents join below.+ const fileIds = relatedFileList+ .filter((file) => file.name !== null)+ .map((file) => file.id)+ .filter(Boolean);++ if (fileIds.length === 0) return { documentsMap: {}, relatedFileList };++ const documentsList = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.documents.select',+ () =>+ this.db+ .select(fileDocumentColumns)+ .from(documents)+ .where(and(inArray(documents.fileId, fileIds), notFileBackedPlaceholder()))+ .orderBy(...fileDocumentsOrder),+ { fileCount: fileIds.length },+ );++ const documentsMap = toFileDocumentsMap(documentsList);++ return { documentsMap, relatedFileList };+ };++ queryMessageChunkRelations = async (+ messageIds: string[],+ timing?: ModelTimingContext,+ ): Promise<MessageChunkRelation[]> => {+ if (messageIds.length === 0) return [];++ const chunksList = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.chunks.select',+ () =>+ this.db+ .select({+ fileId: files.id,+ fileType: files.fileType,+ fileUrl: files.url,+ filename: files.name,+ id: chunks.id,+ messageId: messageQueryChunks.messageId,+ similarity: messageQueryChunks.similarity,+ text: chunks.text,+ })+ .from(messageQueryChunks)+ .leftJoin(chunks, eq(chunks.id, messageQueryChunks.chunkId))+ .leftJoin(fileChunks, eq(fileChunks.chunkId, chunks.id))+ // Guard the referenced file like queryMessageFileRelations: in a+ // shared conversation, RAG reference chunks of a file its owner+ // switched back to private must not leak filename/url/text to other+ // members. The inner join drops those chunk rows entirely.+ .innerJoin(+ files,+ and(+ eq(fileChunks.fileId, files.id),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),+ ),+ )+ .where(inArray(messageQueryChunks.messageId, messageIds)),+ { messageCount: messageIds.length },+ );+ logTiming(timing, 'db.message.queryWithWhere.chunks.select:rows', {+ rowCount: chunksList.length,+ });++ return chunksList;+ };++ /**+ * Resolve Work summaries for a page of messages and key them by anchor+ * message id β the LAST message (rows are createdAt-asc, so last occurrence)+ * carrying each `metadata.work.rootOperationId`. Works ride the message-list+ * payload so the in-message Works chips and the sidebar summary read from one+ * source instead of a dedicated work-summary fetch. Attaching only to the+ * round's last message (not every row sharing the operation) keeps the+ * payload flat β the client re-keys by `rootOperationId`, so which row+ * physically carries it doesn't matter.+ */+ queryMessageWorkSummaries = async (+ rows: { id: unknown; metadata: unknown }[],+ includeFileWorks?: boolean,+ timing?: ModelTimingContext,+ workAccessScope?: WorkAccessScope,+ ): Promise<Record<string, WorkSummaryItem[]>> => {+ const anchorByRootId = new Map<string, string>();+ for (const row of rows) {+ const rootOperationId = getMessageWorkRootId(row.metadata);+ if (rootOperationId) anchorByRootId.set(rootOperationId, row.id as string);+ }+ if (anchorByRootId.size === 0) return {};++ const summaryMap = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.workSummaries',+ () =>+ new WorkModel(+ this.db,+ this.userId,+ this.workspaceId,+ workAccessScope,+ ).listSummariesByRootOperations({+ includeFileWorks,+ rootOperationIds: Array.from(anchorByRootId.keys()),+ }),+ { rootOperationCount: anchorByRootId.size },+ );++ const worksByMessageId: Record<string, WorkSummaryItem[]> = {};+ for (const [rootOperationId, messageId] of anchorByRootId) {+ const works = summaryMap[rootOperationId];+ if (works && works.length > 0) worksByMessageId[messageId] = works;+ }+ logTiming(timing, 'db.message.queryWithWhere.workSummaries:rows', {+ messageCount: Object.keys(worksByMessageId).length,+ });+ return worksByMessageId;+ };++ queryMessageQueryRelations = async (+ messageIds: string[],+ timing?: ModelTimingContext,+ ): Promise<MessageQueryRelation[]> => {+ if (messageIds.length === 0) return [];++ const messageQueriesList = await runTimedStage(+ timing,+ 'db.message.queryWithWhere.messageQueries.select',+ () =>+ this.db+ .select({+ id: messageQueries.id,+ messageId: messageQueries.messageId,+ rewriteQuery: messageQueries.rewriteQuery,+ userQuery: messageQueries.userQuery,+ })+ .from(messageQueries)+ .where(inArray(messageQueries.messageId, messageIds)),+ { messageCount: messageIds.length },+ );+ logTiming(timing, 'db.message.queryWithWhere.messageQueries.select:rows', {+ rowCount: messageQueriesList.length,+ });++ return messageQueriesList;+ };++ queryMessageThreadRelations = async (+ taskMessageIds: string[],+ timing?: ModelTimingContext,+ ): Promise<MessageThreadRelation[]> => {+ if (taskMessageIds.length === 0) return [];++ return runTimedStage(+ timing,+ 'db.message.queryWithWhere.taskThreads.select',+ () =>+ this.db+ .select({+ metadata: threads.metadata,+ sourceMessageId: threads.sourceMessageId,+ status: threads.status,+ threadId: threads.id,+ title: threads.title,+ })+ .from(threads)+ .where(+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),+ inArray(threads.sourceMessageId, taskMessageIds),+ ),+ ),+ { taskMessageCount: taskMessageIds.length },+ );+ };++ createThreadMap = (threadData: MessageThreadRelation[]) =>+ new Map<string, TaskDetail>(+ threadData.map((thread) => {+ const metadata = thread.metadata as Record<string, unknown> | null;+ return [+ thread.sourceMessageId!,+ {+ clientMode: metadata?.clientMode as boolean | undefined,+ duration: metadata?.duration as number | undefined,+ status: thread.status as ThreadStatus,+ threadId: thread.threadId,+ title: thread.title ?? undefined,+ totalCost: metadata?.totalCost as number | undefined,+ totalMessages: metadata?.totalMessages as number | undefined,+ totalTokens: metadata?.totalTokens as number | undefined,+ totalToolCalls: metadata?.totalToolCalls as number | undefined,+ },+ ];+ }),+ );+}diff --git a/packages/database/src/models/message/scope.ts b/packages/database/src/models/message/scope.tsnew file mode 100644index 00000000000..30a5078a82b--- /dev/null+++ b/packages/database/src/models/message/scope.ts@@ -0,0 +1,169 @@+import { INBOX_SESSION_ID } from '@lobechat/const';+import { and, eq, inArray, isNull, or } from 'drizzle-orm';++import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';+import {+ agentsToSessions,+ messagePlugins,+ messages,+ messageTranslates,+ messageTTS,+ topics,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { idGenerator } from '../../utils/idGenerator';+import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { buildWorkspaceWhere } from '../../utils/workspace';+import type { MessageModelOptions } from './types';++export type MessageScopeArgs = ConstructorParameters<typeof MessageScope>;++/**+ * Shared user/workspace scope of every `MessageModel` sub-domain: the+ * constructor arguments plus the ownership predicates and id/match helpers+ * that each query and mutation module builds on.+ */+export class MessageScope {+ protected userId: string;++ protected db: LobeChatDatabase;++ protected ftsSearchCandidateSource?: FtsSearchCandidateSource;++ protected workspaceId?: string;++ /**+ * When true, {@link ownership} (and by extension every creator-scoped+ * read/write below) stops ANDing {@link notShareVisitorMessage}. Reserved+ * for surfaces that are share-runtime by design (agent-share visitor+ * router, share-scoped abuse guards) and for the agent runtime paths that+ * persist or clean up a visitor turn under the CREATOR's identity.+ * Defaults to false so every ordinary creator-facing caller fails closed.+ */+ protected includeShareVisitor: boolean;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ ftsSearchCandidateSource?: FtsSearchCandidateSource,+ options: MessageModelOptions = {},+ ) {+ this.userId = userId;+ this.db = db;+ this.workspaceId = workspaceId;+ this.ftsSearchCandidateSource = ftsSearchCandidateSource;+ this.includeShareVisitor = options.includeShareVisitor ?? false;+ }++ /**+ * Workspace/user scope plus the live parent-topic fence, WITHOUT the visitor+ * exclusion. Topic-less rows remain valid. Backing store for+ * {@link ownership} and the escape hatch for methods that resolve the+ * effective visitor gate per-call ({@link deleteMessage},+ * {@link deleteMessages}, {@link query} via `allowShareVisitor`, β¦).+ */+ protected workspaceScope = () =>+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),+ or(+ isNull(messages.topicId),+ inArray(+ messages.topicId,+ this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ ),+ ),+ );++ /**+ * Default visitor exclusion applied by {@link ownership} β see+ * `notShareVisitorMessage` in `../utils/shareVisitor`. Returns `undefined`+ * when the instance was constructed with `includeShareVisitor: true`.+ */+ protected notShareVisitor = () =>+ this.includeShareVisitor ? undefined : notShareVisitorMessage();++ protected ownership = () => and(this.workspaceScope(), this.notShareVisitor());++ /**+ * One indexed lookup of a topic's `senderId` in this user/workspace scope+ * (`buildWorkspaceWhere` on `topics`). Returned once and reused: every row+ * that belongs to a topic shares that topic's visitor/creator identity, so+ * once the topic itself has been classified the per-row NOT EXISTS predicate+ * from {@link notShareVisitorMessage} is redundant for the rest of the same+ * call. Callers pass the resolved verdict downstream (as+ * `allowShareVisitor: true` for a verified creator topic) to swap the+ * relevant `ownership()` sites over to plain `workspaceScope()`.+ *+ * Fails closed: returns `'visitor'` when the topic doesn't exist under this+ * scope OR carries a non-null `senderId`, so an unauthorized topicId gets+ * the same empty result as before.+ */+ protected resolveTopicVisitorScope = async (topicId: string): Promise<'creator' | 'visitor'> => {+ const rows = await this.db+ .select({ senderId: topics.senderId })+ .from(topics)+ .where(+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ eq(topics.id, topicId),+ ),+ )+ .limit(1);+ if (rows.length === 0) return 'visitor';+ return rows[0].senderId === null ? 'creator' : 'visitor';+ };++ /**+ * Scope predicate without the recycle-bin filter β restore / purge internals+ * only. Keeps the visitor exclusion of {@link ownership} so a creator-facing+ * restore or purge can never reach an agent-share visitor row.+ */+ protected trashScope = () =>+ and(+ buildWorkspaceWhere(+ { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },+ messages,+ ),+ this.notShareVisitor(),+ );++ protected pluginsOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);++ protected translatesOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTranslates);++ protected ttsOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTTS);++ protected agentsToSessionsOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentsToSessions);++ // 18-char hash (was 14): widen the message id space β the coordinator-driven+ // hetero subagent flow allocates many ids per run, and a few extra chars keep+ // collision odds negligible at that volume.+ protected genId = () => idGenerator('messages', 18);++ protected matchSession = (sessionId?: string | null) => {+ if (sessionId === INBOX_SESSION_ID) return isNull(messages.sessionId);++ return sessionId ? eq(messages.sessionId, sessionId) : isNull(messages.sessionId);+ };++ protected matchTopic = (topicId?: string | null) =>+ topicId ? eq(messages.topicId, topicId) : isNull(messages.topicId);++ protected matchGroup = (groupId?: string | null) =>+ groupId ? eq(messages.groupId, groupId) : isNull(messages.groupId);++ protected matchThread = (threadId?: string | null) => {+ if (!!threadId) return eq(messages.threadId, threadId);+ return isNull(messages.threadId);+ };+}diff --git a/packages/database/src/models/message/spine.ts b/packages/database/src/models/message/spine.tsnew file mode 100644index 00000000000..b60e977c6cf--- /dev/null+++ b/packages/database/src/models/message/spine.ts@@ -0,0 +1,166 @@+import { and, desc, eq, isNull, not, sql } from 'drizzle-orm';++import { messages } from '../../schemas';+import { MessageScope } from './scope';++export class MessageSpineQueries extends MessageScope {+ /**+ * Id of the latest main-thread (`threadId IS NULL`) "spine" message in a+ * topic: the most recent message that is NOT a tool and NOT a signal-tagged+ * reactive turn (Monitor stdout callbacks etc.). This is the chain anchor for+ * the heterogeneous-agent write side: the next normal+ * turn parents off it, producing a `user β asst β asst β¦` spine with tools as+ * inline children.+ *+ * Read straight from the DB and ordered by `createdAt`, it is independent of+ * the in-memory current-assistant pointer β which can regress to the run's+ * seed placeholder on a cold / non-sticky serverless replica. Anchoring here+ * instead keeps consecutive cold-replica steps chained linearly rather than+ * forking onto a stale node (the remote "ζιΎ" bug). No `createdAt` floor is+ * needed: a topic runs at most one operation at a time, so the latest spine+ * message IS this run's continuation point.+ *+ * Excludes `role:'tool'` (inline children) and TOOLLESS signal-tagged+ * assistants (`metadata->'signal'` with no tools), which are tool-child+ * callbacks β anchoring a normal turn onto a callback would orphan it under+ * the read side's tool-only signal collection. A signal turn that DID emit+ * tools is back on the main chain and stays a spine candidate.+ */+ getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> =>+ this.getLatestSpineMessageId({ topicId, threadId: null });++ /**+ * Whether `descendantId` belongs to the branch rooted at `ancestorId`.+ *+ * Used when reconciling a client-selected conversation tail with the latest+ * server row: a newer row may be a sibling from a historical callback fork,+ * not an advancement of the branch the user is viewing.+ */+ isMessageDescendantOf = async ({+ ancestorId,+ descendantId,+ topicId,+ }: {+ ancestorId: string;+ descendantId: string;+ topicId: string;+ }): Promise<boolean> => {+ const result = await this.db.execute(sql`+ WITH RECURSIVE ancestors(id, parent_id) AS (+ SELECT id, parent_id+ FROM messages+ WHERE id = ${descendantId}+ AND topic_id = ${topicId}+ AND ${this.ownership()}+ UNION+ SELECT parent.id, parent.parent_id+ FROM messages parent+ JOIN ancestors child ON parent.id = child.parent_id+ WHERE parent.topic_id = ${topicId}+ )+ SELECT 1 AS hit FROM ancestors WHERE id = ${ancestorId} LIMIT 1+ `);++ return result.rows.length > 0;+ };++ /**+ * Thread-aware variant of {@link getLastMainThreadSpineMessageId}: the id of+ * the latest "spine" message (the most recent message that is NOT a tool and+ * NOT a signal-tagged reactive turn) in a topic, scoped to the main thread+ * (`threadId IS NULL`) or to a specific thread.+ *+ * Like the main-thread query it EXCLUDES `role:'tool'` and TOOLLESS+ * signal-tagged assistants: tools are inline children of their assistant turn,+ * so the conversation head a new turn parents off is the assistant, never the+ * tool result that landed under it. A tools-bearing signal turn is main-chain+ * and remains a spine candidate.+ *+ * Used by `sendMessageInServer` to make `parentId` server-authoritative and+ * close the concurrent-append race: the client computes `parentId` from a+ * local snapshot whose spine tail may already have advanced (e.g. another+ * assistant turn was written while the user was composing), so trusting it+ * would fork the new turn off a stale node. Ordering by `createdAt` is safe+ * because a topic runs at most one operation at a time.+ */+ getLatestSpineMessageId = async ({+ topicId,+ threadId,+ }: {+ threadId?: string | null;+ topicId: string;+ }): Promise<string | undefined> => {+ const [row] = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, topicId),+ not(eq(messages.role, 'tool')),+ threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),+ // Exclude signal-tagged assistants β BUT only the toolless ones. The+ // writer tags a turn `signal` at stream_start before it knows the turn+ // will call tools; a signal turn that DOES emit a tool_use is really+ // back on the main chain (see `reduceToolsChunk`'s spine promotion),+ // so it must stay a spine candidate or a cold replica re-forks the+ // wire off the pre-signal turn. Match the read side, which likewise+ // treats a tools-bearing message as non-signal (`getMessageSignal`).+ //+ // Key existence (`jsonb_exists`) is used instead of `metadata -> 'signal'+ // IS NULL`, which crashes the serverless Postgres engine as a WHERE+ // predicate (rt_fetch out-of-bounds, SQLSTATE XX000 β the `->` operator+ // only survives in SELECT/ORDER BY). Toolless is expressed with plain+ // jsonb equality (`= '[]'` / IS NULL) rather than `jsonb_array_length`,+ // which is unproven on this engine as a qual.+ sql`NOT (+ COALESCE(jsonb_exists(${messages.metadata}, 'signal'), false)+ AND (${messages.tools} IS NULL OR ${messages.tools} = '[]'::jsonb)+ )`,+ this.ownership(),+ ),+ )+ .orderBy(desc(messages.createdAt))+ .limit(1);++ return row?.id;+ };++ /**+ * Fallback anchor for {@link getLatestSpineMessageId}: the latest non-tool+ * message in a topic/thread, WITHOUT the toolless-signal exclusion.+ *+ * A topic whose main thread holds nothing but toolless signal turns has no+ * spine candidate, so the spine lookup returns undefined and the caller would+ * persist the new turn with `parentId: undefined` β a second root that forks+ * the conversation tree. The renderer walks that forest depth-first, so an+ * earlier root's long-running subtree gets emitted before a later root and the+ * newest reply surfaces ABOVE older messages.+ *+ * `role:'tool'` stays excluded: tool results are inline children of their+ * assistant turn, and anchoring a normal turn onto one orphans it under the+ * read side's tool-only signal collection.+ */+ getLatestNonToolMessageId = async ({+ topicId,+ threadId,+ }: {+ threadId?: string | null;+ topicId: string;+ }): Promise<string | undefined> => {+ const [row] = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, topicId),+ not(eq(messages.role, 'tool')),+ threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),+ this.ownership(),+ ),+ )+ .orderBy(desc(messages.createdAt))+ .limit(1);++ return row?.id;+ };+}diff --git a/packages/database/src/models/message/tool.ts b/packages/database/src/models/message/tool.tsnew file mode 100644index 00000000000..4b15b5b64fb--- /dev/null+++ b/packages/database/src/models/message/tool.ts@@ -0,0 +1,248 @@+import type { ChatToolPayload, HeterogeneousToolStateSnapshot } from '@lobechat/types';+import { and, eq, sql } from 'drizzle-orm';++import { merge } from '@/utils/merge';+import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';++import { messagePlugins, messages } from '../../schemas';+import { MessageScope } from './scope';++export class MessageToolMutations extends MessageScope {+ /**+ * Update tool message with content, metadata, pluginState, and pluginError in a single transaction+ * This prevents race conditions when updating multiple fields+ */+ updateToolMessage = async (+ id: string,+ params: {+ content?: string;+ heterogeneousToolState?: HeterogeneousToolStateSnapshot;+ metadata?: Record<string, any>;+ pluginError?: any;+ pluginState?: Record<string, any>;+ /** Replace rather than merge when withholding a complete tool result. */+ replacePluginState?: boolean;+ /** Finalize a deferred placeholder once; later callbacks cannot replace its result. */+ onlyIfEmpty?: boolean;+ },+ ): Promise<{ applied: boolean; snapshotSeq?: number; success: boolean }> => {+ const {+ content,+ heterogeneousToolState,+ metadata,+ pluginState,+ pluginError,+ replacePluginState,+ } = params;++ // `undefined` while no branch has looked for the row yet; see `update` above+ // for why a write that matches nothing must not report success.+ let matchedRow: boolean | undefined;+ let applied = true;+ let snapshotSeq: number | undefined;++ try {+ await this.db.transaction(async (trx) => {+ if (params.onlyIfEmpty) {+ const [message] = await trx+ .select({ content: messages.content })+ .from(messages)+ .where(and(eq(messages.id, id), this.ownership()))+ .for('update');+ matchedRow = !!message;+ if (!message) return;+ if (message.content) {+ applied = false;+ return;+ }+ }++ let existingMetadata: Record<string, any> | undefined;++ if (metadata !== undefined || heterogeneousToolState !== undefined) {+ const baseQuery = trx+ .select({ metadata: messages.metadata })+ .from(messages)+ .where(and(eq(messages.id, id), this.ownership()))+ .limit(1);+ const [existingMessage] = heterogeneousToolState+ ? await baseQuery.for('update')+ : await baseQuery;++ matchedRow = !!existingMessage;+ if (!existingMessage) return;++ existingMetadata = (existingMessage.metadata ?? {}) as Record<string, any>;++ if (heterogeneousToolState) {+ const currentOperationId = existingMetadata.heterogeneousToolStateOperationId;+ const rawCurrentSeq = existingMetadata.heterogeneousToolStateSeq;+ const currentSeq =+ currentOperationId === heterogeneousToolState.operationId &&+ typeof rawCurrentSeq === 'number' &&+ Number.isFinite(rawCurrentSeq)+ ? rawCurrentSeq+ : 0;++ if (heterogeneousToolState.snapshotSeq <= currentSeq) {+ applied = false;+ snapshotSeq = currentSeq;+ return;+ }++ snapshotSeq = heterogeneousToolState.snapshotSeq;+ }+ }++ // Update messages table (content, metadata)+ if (+ content !== undefined ||+ metadata !== undefined ||+ heterogeneousToolState !== undefined+ ) {+ const messageUpdateData: Record<string, any> = {};++ if (content !== undefined) {+ messageUpdateData.content = sanitizeNullBytes(content);+ }++ if (metadata !== undefined || heterogeneousToolState !== undefined) {+ const mergedMetadata = merge(existingMetadata || {}, metadata || {});+ messageUpdateData.metadata = heterogeneousToolState+ ? merge(mergedMetadata, {+ heterogeneousToolStateOperationId: heterogeneousToolState.operationId,+ heterogeneousToolStateSeq: heterogeneousToolState.snapshotSeq,+ })+ : mergedMetadata;+ }++ if (Object.keys(messageUpdateData).length > 0) {+ const [updated] = await trx+ .update(messages)+ .set(messageUpdateData)+ .where(and(eq(messages.id, id), this.ownership()))+ .returning({ id: messages.id });++ matchedRow = !!updated;+ }+ }++ // Update messagePlugins table (pluginState, pluginError)+ if (pluginState !== undefined || pluginError !== undefined) {+ const pluginUpdateData: Record<string, any> = {};++ if (pluginState !== undefined) {+ const sanitizedState = sanitizeNullBytes(pluginState);+ // Snapshot writes replace the whole runtime state. Ordinary patches+ // own complete top-level keys and merge inside the UPDATE so an+ // answer write cannot race away an intervention-terminal write.+ pluginUpdateData.state =+ heterogeneousToolState || replacePluginState+ ? sanitizedState+ : sql`coalesce(${messagePlugins.state}, '{}'::jsonb) || ${JSON.stringify(sanitizedState)}::jsonb`;+ }++ if (pluginError !== undefined) {+ pluginUpdateData.error = sanitizeNullBytes(pluginError);+ }++ const [updatedPlugin] = await trx+ .update(messagePlugins)+ .set(pluginUpdateData)+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))+ .returning({ id: messagePlugins.id });++ // A plugin-only patch never touches `messages`, so the plugin row is+ // the only evidence the tool message exists.+ if (matchedRow === undefined) matchedRow = !!updatedPlugin;++ if (!updatedPlugin && heterogeneousToolState) {+ throw new Error(`No tool plugin matched id ${id}`);+ }+ }+ });++ if (matchedRow === false) {+ console.error(`Update tool message error: no tool message matched id ${id}`);+ return { applied: false, success: false };+ }++ return { applied, snapshotSeq, success: true };+ } catch (error) {+ console.error('Update tool message error:', error);+ return { applied: false, success: false };+ }+ };++ /**+ * Update tool arguments by toolCallId - updates both tool message plugin.arguments+ * and parent assistant message tools[].arguments in a single transaction+ *+ * This method uses toolCallId (the stable identifier from AI response) instead of+ * tool message ID, which allows updating arguments even when the tool message+ * hasn't been persisted yet (e.g., during intervention pending state).+ *+ * @param toolCallId - The tool call ID (stable identifier from AI response)+ * @param args - The new arguments string (already stringified JSON)+ */+ updateToolArguments = async (toolCallId: string, args: string): Promise<{ success: boolean }> => {+ try {+ await this.db.transaction(async (trx) => {+ // 1. Find tool plugin and tool message with parentId in one query+ const [toolResult] = await trx+ .select({+ parentId: messages.parentId,+ toolPluginId: messagePlugins.id,+ })+ .from(messagePlugins)+ .innerJoin(messages, eq(messages.id, messagePlugins.id))+ .where(and(eq(messagePlugins.toolCallId, toolCallId), this.ownership()))+ .limit(1);++ if (!toolResult?.parentId) {+ throw new Error(`No tool message found with toolCallId: ${toolCallId}`);+ }++ // 2. Get parent assistant message's tools+ const [parentMessage] = await trx+ .select({ id: messages.id, tools: messages.tools })+ .from(messages)+ .where(and(eq(messages.id, toolResult.parentId), this.ownership()))+ .limit(1);++ if (!parentMessage?.tools) {+ throw new Error(`No parent assistant message found for toolCallId: ${toolCallId}`);+ }++ const parentTools = parentMessage.tools as ChatToolPayload[];++ // 3. Update the parent assistant message's tools[].arguments+ const updatedTools = parentTools.map((tool) => {+ if (tool.id === toolCallId) {+ return { ...tool, arguments: args };+ }+ return tool;+ });++ // Execute both updates in parallel+ await Promise.all([+ // Update tool plugin arguments+ trx+ .update(messagePlugins)+ .set({ arguments: args })+ .where(and(eq(messagePlugins.id, toolResult.toolPluginId), this.pluginsOwnership())),+ // Update parent assistant message's tools+ trx+ .update(messages)+ .set({ tools: updatedTools })+ .where(and(eq(messages.id, parentMessage.id), this.ownership())),+ ]);+ });++ return { success: true };+ } catch (error) {+ console.error('Update tool arguments error:', error);+ return { success: false };+ }+ };+}diff --git a/packages/database/src/models/message/trash.ts b/packages/database/src/models/message/trash.tsnew file mode 100644index 00000000000..21bb4c1144e--- /dev/null+++ b/packages/database/src/models/message/trash.ts@@ -0,0 +1,322 @@+import type { ChatToolPayload } from '@lobechat/types';+import type { SQL } from 'drizzle-orm';+import { and, eq, inArray, isNull, not, or } from 'drizzle-orm';++import { messagePlugins, messages, topics } from '../../schemas';+import {+ isTrashed,+ restoreStamp,+ type SoftDeleteOptions,+ trashStamp,+} from '../../utils/softDelete';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { recomputeTopicUsage } from '../topicUsage';+import type { MessageBranchSnapshots } from './branchSnapshots';+import type { MessageScopeArgs } from './scope';+import { MessageScope } from './scope';+import type { SoftDeletedMessage } from './types';++export class MessageTrashMutations extends MessageScope {+ private readonly snapshots: MessageBranchSnapshots;++ constructor(args: MessageScopeArgs, deps: { snapshots: MessageBranchSnapshots }) {+ super(...args);+ this.snapshots = deps.snapshots;+ }++ /**+ * Move messages to the recycle bin. Mirrors {@link deleteMessages} step for+ * step β tool companions are pulled in, live children are re-parented onto+ * the nearest surviving ancestor, the active-branch pointer is reconciled and+ * the topic usage rollup recomputed β but the rows are stamped instead of+ * dropped. Returns one entry per stamped row with the tree data a restore+ * needs to splice it back (`parentId` + the child ids that were re-parented+ * away from it), and whether the row was an explicitly requested root or a+ * tool companion pulled in with it.+ */+ softDeleteMessages = async (+ ids: string[],+ options: SoftDeleteOptions,+ ): Promise<SoftDeletedMessage[]> => {+ if (ids.length === 0) return [];++ return this.db.transaction(async (tx) => {+ const requested = await tx+ .select({+ content: messages.content,+ id: messages.id,+ parentId: messages.parentId,+ projectId: topics.projectId,+ role: messages.role,+ tools: messages.tools,+ topicId: messages.topicId,+ })+ .from(messages)+ .leftJoin(+ topics,+ and(+ eq(messages.topicId, topics.id),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ )+ .where(and(this.ownership(), inArray(messages.id, ids)));+ if (requested.length === 0) return [];++ // Tool companions: the tool-result rows of a trashed assistant turn go+ // with it (same rule as the hard delete).+ const toolCallIds = requested+ .flatMap((row) => ((row.tools as ChatToolPayload[]) ?? []).map((tool) => tool.id))+ .filter(Boolean);+ const requestedIds = new Set(requested.map((row) => row.id));+ // toolCallId β the requested row that issued it, so each companion is+ // attributed to its own assistant turn rather than to the batch.+ const toolCallOwner = new Map<string, string>();+ for (const row of requested) {+ for (const tool of (row.tools as ChatToolPayload[]) ?? []) {+ if (tool.id) toolCallOwner.set(tool.id, row.id);+ }+ }+ const companionOwner = new Map<string, string>();+ let companions: typeof requested = [];+ if (toolCallIds.length > 0) {+ const companionRows = await tx+ .select({ id: messagePlugins.id, toolCallId: messagePlugins.toolCallId })+ .from(messagePlugins)+ .where(inArray(messagePlugins.toolCallId, toolCallIds));+ for (const row of companionRows) {+ const owner = row.toolCallId ? toolCallOwner.get(row.toolCallId) : undefined;+ if (owner && !requestedIds.has(row.id)) companionOwner.set(row.id, owner);+ }+ const companionIds = [...companionOwner.keys()];+ if (companionIds.length > 0) {+ companions = await tx+ .select({+ content: messages.content,+ id: messages.id,+ parentId: messages.parentId,+ projectId: topics.projectId,+ role: messages.role,+ tools: messages.tools,+ topicId: messages.topicId,+ })+ .from(messages)+ .leftJoin(+ topics,+ and(+ eq(messages.topicId, topics.id),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ )+ .where(and(this.ownership(), inArray(messages.id, companionIds)));+ }+ }++ const toDelete = [...requested, ...companions];+ const deleteIds = toDelete.map((row) => row.id);+ const deleteSet = new Set(deleteIds);+ const parentMap = new Map(toDelete.map((row) => [row.id, row.parentId] as const));++ const finalAncestorMap = new Map<string, string | null>();+ const findFinalAncestor = (id: string): string | null => {+ if (finalAncestorMap.has(id)) return finalAncestorMap.get(id)!;+ const parentId = parentMap.get(id);+ if (parentId === null || parentId === undefined) {+ finalAncestorMap.set(id, null);+ return null;+ }+ if (!deleteSet.has(parentId)) {+ finalAncestorMap.set(id, parentId);+ return parentId;+ }+ const ancestor = findFinalAncestor(parentId);+ finalAncestorMap.set(id, ancestor);+ return ancestor;+ };+ for (const id of deleteSet) findFinalAncestor(id);++ const activeBranchSnapshots = await this.snapshots.captureActiveBranchSnapshots(+ tx,+ [...new Set(finalAncestorMap.values())].filter((id): id is string => id !== null),+ );++ // Live children re-parented onto the nearest surviving ancestor β+ // remembered per message so a restore can hand them back.+ const children = await tx+ .select({ id: messages.id, parentId: messages.parentId })+ .from(messages)+ .where(+ and(+ this.ownership(),+ inArray(messages.parentId, deleteIds),+ not(inArray(messages.id, deleteIds)),+ ),+ );+ const childIdsByParent = new Map<string, string[]>();+ for (const child of children) {+ const list = childIdsByParent.get(child.parentId!) ?? [];+ list.push(child.id);+ childIdsByParent.set(child.parentId!, list);+ await tx+ .update(messages)+ .set({ parentId: finalAncestorMap.get(child.parentId!) ?? null })+ .where(and(eq(messages.id, child.id), this.ownership()));+ }++ await tx+ .update(messages)+ .set(trashStamp(options.deletedAt))+ .where(and(this.ownership(), inArray(messages.id, deleteIds)));++ await this.snapshots.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);++ const affectedTopicIds = [+ ...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),+ ];+ for (const topicId of affectedTopicIds) {+ await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);+ }++ return toDelete.map((row) => ({+ childIds: childIdsByParent.get(row.id) ?? [],+ content: row.content,+ id: row.id,+ isCompanion: !requestedIds.has(row.id),+ ownerId: companionOwner.get(row.id) ?? null,+ parentId: row.parentId,+ projectId: row.projectId,+ role: row.role,+ topicId: row.topicId,+ }));+ });+ };++ /**+ * Bring trashed messages back and splice them into their branch: the stamp+ * is cleared and the children recorded at trash time are re-parented onto+ * the message again (best effort β a child that has since moved or gone is+ * left alone). The active-branch pointer of the parent keeps pointing at+ * whatever branch is active today.+ */+ restoreMessages = async (+ entries: { childIds?: string[]; id: string; parentId?: string | null }[],+ ): Promise<string[]> => {+ if (entries.length === 0) return [];+ return this.db.transaction(async (tx) => {+ const ids = entries.map((entry) => entry.id);+ const rows = await tx+ .select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId })+ .from(messages)+ .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));+ if (rows.length === 0) return [];++ const parentIds = rows.map((row) => row.parentId).filter((id): id is string => !!id);+ const activeBranchSnapshots = await this.snapshots.captureActiveBranchSnapshots(+ tx,+ parentIds,+ );++ // Report what the write restored, not what the read saw: a purge that+ // commits in between leaves nothing to update, and the caller must not+ // count that row as restored.+ const updated = await tx+ .update(messages)+ .set(restoreStamp())+ .where(+ and(+ this.trashScope(),+ inArray(+ messages.id,+ rows.map((row) => row.id),+ ),+ isTrashed(messages.isDeleted),+ ),+ )+ .returning({ id: messages.id });+ const restoredIds = new Set(updated.map((row) => row.id));++ for (const entry of entries) {+ if (!restoredIds.has(entry.id) || !entry.childIds?.length) continue;+ await tx+ .update(messages)+ .set({ parentId: entry.id })+ .where(and(inArray(messages.id, entry.childIds), this.trashScope()));+ }++ // While the row was in the bin its children hung off its parent, and the+ // user may have picked one of them as the active branch there. They now+ // move back under the restored row, so carry that choice up to it β+ // otherwise reconciliation cannot find the child among the parent's+ // branches, drops the selection and the view can jump to a sibling.+ const restoredAncestorOf = new Map<string, string>();+ for (const entry of entries) {+ if (!restoredIds.has(entry.id)) continue;+ for (const childId of entry.childIds ?? []) restoredAncestorOf.set(childId, entry.id);+ }+ for (const snapshot of activeBranchSnapshots) {+ const ancestor = snapshot.activeBranchId && restoredAncestorOf.get(snapshot.activeBranchId);+ if (ancestor) snapshot.activeBranchId = ancestor;+ }++ await this.snapshots.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);++ const affectedTopicIds = [...new Set(rows.map((m) => m.topicId).filter(Boolean) as string[])];+ for (const topicId of affectedTopicIds) {+ await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);+ }+ return [...restoredIds];+ });+ };++ findTrashedByIds = async (ids: string[]) => {+ if (ids.length === 0) return [];+ return this.db+ .select({+ agentId: messages.agentId,+ id: messages.id,+ parentId: messages.parentId,+ sessionId: messages.sessionId,+ topicId: messages.topicId,+ })+ .from(messages)+ .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));+ };++ /**+ * Cascade helper for trashing an agent: stamps the live messages that hang+ * off the given agents or their legacy session shells WITHOUT a topic. Rows+ * inside a topic are hidden by that topic's own stamp; topic-less rows have+ * no parent to hide them (`workspaceScope()` treats them as live), so they+ * are stamped directly and registered as the agent's children. Their branch+ * stays intact, so a plain restore of the same ids brings them back.+ */+ softDeleteTopicless = async (+ parents: { agentIds?: string[]; sessionIds?: string[] },+ options: SoftDeleteOptions,+ ) => {+ const conditions: SQL[] = [];+ if (parents.agentIds?.length) conditions.push(inArray(messages.agentId, parents.agentIds));+ if (parents.sessionIds?.length)+ conditions.push(inArray(messages.sessionId, parents.sessionIds));+ if (conditions.length === 0) return [];++ return this.db+ .update(messages)+ .set(trashStamp(options.deletedAt))+ .where(and(isNull(messages.topicId), or(...conditions), this.ownership()))+ .returning({ content: messages.content, id: messages.id, role: messages.role });+ };++ /**+ * Hard delete for the purge sweep. Children were already re-parented at trash+ * time and usage already excludes stamped rows, so this is a plain delete+ * keyed on `scope()`.+ */+ purgeMessages = async (ids: string[]) => {+ if (ids.length === 0) return;+ // Only rows still stamped: a restore that commits between the purge's+ // registry read and this delete must win.+ return this.db+ .delete(messages)+ .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));+ };+}diff --git a/packages/database/src/models/message/types.ts b/packages/database/src/models/message/types.tsnew file mode 100644index 00000000000..edcc147100d--- /dev/null+++ b/packages/database/src/models/message/types.ts@@ -0,0 +1,276 @@+import type {+ ChatMessageError,+ ChatToolPayload,+ MessageMetadata,+ MessagePluginItem,+ ModelReasoning,+ ModelUsage,+ UIChatMessage,+ WorkAccessScope,+} from '@lobechat/types';+import type { TimingSink } from '@lobechat/utils';+import type { SQL } from 'drizzle-orm';++export interface HumanApprovalResolution {+ /** Conditional owner checked by rollback; never accepted as client authority. */+ claimedResolutionRequestId?: string;+ content?: string;+ id: string;+ intervention: Record<string, unknown>;+ pluginError?: MessagePluginItem['error'] | null;+ pluginState?: Record<string, unknown> | null;+ replacePluginState?: boolean;+}++/**+ * Options for querying messages with relations+ */+export interface QueryMessagesOptions {+ /**+ * Opt IN to agent-share visitor rows for this call, overriding the default+ * `ownership()` visitor exclusion. Combined via OR with the instance's+ * `includeShareVisitor` flag, so an instance already opted in stays opted+ * in and a default-scoped instance can still be widened per-call (this is+ * how {@link MessageModel.queryForVisitor} works before the share-runtime+ * routers switch to constructing the model with `{ includeShareVisitor:+ * true }`).+ */+ allowShareVisitor?: boolean;+ /**+ * Round-cursor for loading older history (see `QueryMessageParams.before`):+ * only rows strictly older than this `(createdAt, id)` tuple are fetched.+ */+ before?: { createdAt: Date; id: string };+ /**+ * Current page number (0-indexed)+ */+ current?: number;+ /**+ * Constrain MessageGroup assembly to an explicit `[from, before)` time window+ * instead of loading every group in the topic (or deriving the window from the+ * fetched rows). Set by cursor pagination so consecutive pages partition the+ * topic's groups exactly once: a scroll-up page neither repeats group nodes nor+ * drops the ones dated between (or older than) its mainline rows. Either bound+ * may be omitted to leave that side open. Bounds are lossless microsecond+ * timestamp strings compared with a `::timestamptz` cast.+ */+ groupNodeWindow?: MessageGroupNodeWindow;+ /**+ * Opt-in for `file` work summaries in the payload (see+ * `QueryMessageParams.includeFileWorks`).+ */+ includeFileWorks?: boolean;+ /**+ * Number of messages per page+ */+ pageSize?: number;+ /**+ * Post-process function for file URLs+ */+ postProcessUrl?: (+ path: string | null,+ file: { fileType: string; id?: string | null },+ ) => Promise<string>;+ /**+ * Skip the Work-summary assembly (see `QueryMessageParams.skipWorks`).+ */+ skipWorks?: boolean;+ timing?: ModelTimingContext;+ /**+ * Topic ID for MessageGroup aggregation queries+ */+ topicId?: string;+ /**+ * Custom where condition for message filtering+ */+ where?: SQL;+ /**+ * Agent Share boundary for the Work-summary assembly. Omitted = ordinary+ * scope, which never resolves a share visitor's Works; the share read path+ * passes `agentShareWorkAccessScope(...)` so a visitor gets exactly the+ * Works registered from their own share topic.+ */+ workAccessScope?: WorkAccessScope;+}++export interface TopicTranscriptMessage {+ agentId: string | null;+ content: string | null;+ createdAt: Date;+ error: ChatMessageError | null;+ id: string;+ messageGroupId: string | null;+ metadata: MessageMetadata | null;+ model: string | null;+ parentId: string | null;+ pluginError: unknown;+ provider: string | null;+ reasoning: ModelReasoning | null;+ role: string;+ threadId: string | null;+ toolCallId: string | null;+ tools: ChatToolPayload[] | null;+ usage: ModelUsage | null;+}++export interface TopicTranscriptResult {+ items: TopicTranscriptMessage[];+ total: number;+}++/**+ * Round-boundary cursor for {@link MessageModel.queryTopicMessagesByCursor}. Points+ * at a mainline `user` message (a round start); paging older fetches the rounds+ * strictly before it.+ */+export interface MessageRoundCursor {+ createdAt: string;+ id: string;+}++export interface QueryTopicByCursorParams {+ /**+ * Ignored: a concrete topic is the conversation boundary and may hold rows+ * from several agents/sessions (e.g. `callAgent` replies), same as `query`.+ * Accepted only so callers can forward their usual query params.+ */+ agentId?: string | null;+ /** Hard cap on rows walked when resolving the round window (safety, ~rows). */+ countBudget?: number;+ /** Omit for the initial (newest) page; pass a prior `nextCursor` to load older. */+ cursor?: MessageRoundCursor | null;+ /** Group chat topic: rows carry the group id, same filter as `query`. */+ groupId?: string | null;+ /** See {@link QueryMessageParams.includeFileWorks}. */+ includeFileWorks?: boolean;+ /** How many rounds to load per page (the current round is always whole). */+ roundLimit?: number;+ /** Ignored for the same reason as `agentId`. */+ sessionId?: string | null;+ skipWorks?: boolean;+ topicId: string;+}++export interface TopicMessagesByCursorResult {+ hasMore: boolean;+ messages: UIChatMessage[];+ /** Cursor to load the previous (older) page, or null when at the topic start. */+ nextCursor: MessageRoundCursor | null;+}++/** Half-open `[from, before)` MessageGroup window; see `groupNodeWindow`. */+export interface MessageGroupNodeWindow {+ before?: string | null;+ from?: string | null;+}++export interface ModelTimingContext extends TimingSink {}++/**+ * Shared, ownership-scoped filters for the analytics queries+ * (count / countGroupByTopic / topicMessageStats). All of these are+ * applied on top of the workspace ownership predicate, so the resulting+ * query never leaks across `userId Γ workspace`.+ */+export interface MessageAnalyticsFilters {+ agentId?: string;+ endDate?: string;+ range?: [string, string];+ role?: string;+ startDate?: string;+ topicId?: string;+}++/** A single `{ topicId, count }` row from a per-topic count aggregation. */+export interface TopicMessageCountItem {+ count: number;+ topicId: string;+}++/**+ * Distribution of message counts per topic, computed server-side.+ * Mirrors what a `SELECT count(*) ... GROUP BY topic_id` + percentile+ * aggregation would produce, so the CLI receives only the summary instead+ * of paginating raw rows.+ */+export interface TopicMessageStats {+ /** Per distinct message-count value, how many topics have it. Ascending. */+ histogram: { topics: number; userCount: number }[];+ max: number;+ mean: number;+ median: number;+ min: number;+ /** Number of topics with exactly one matching message ("one-shot"). */+ oneshot: number;+ /** oneshot / topics, in [0, 1]. 0 when there are no topics. */+ oneshotRatio: number;+ p90: number;+ p99: number;+ /** Number of topics that have at least one matching message. */+ topics: number;+ /** Total matching messages across all topics. */+ totalMessages: number;+}++/**+ * Opt-in escape hatch for the write paths that legitimately act on agent-share+ * visitor rows. Visitor messages are stored under the creator's `userId`, so+ * ownership alone cannot tell a creator action apart from a runtime action;+ * mutation entry points therefore fail closed and only the agent runtime (which+ * drives visitor turns under the creator's identity) passes this.+ */+export interface ShareVisitorWriteOptions {+ includeShareVisitor?: boolean;+}++/**+ * Constructor options for {@link MessageModel} β mirrors the twin flag on+ * {@link import('../topic').TopicModelOptions}. When `includeShareVisitor` is+ * true, the instance's `ownership()` predicate no longer excludes agent-share+ * visitor messages; the escape hatch that per-call {@link ShareVisitorWriteOptions}+ * used to be the only way to grant. Share-only surfaces should set this at+ * construction and stop threading per-call opt-ins through their code.+ */+export interface MessageModelOptions {+ includeShareVisitor?: boolean;+}++/**+ * Per-share switches that relax {@link toVisitorMessage}'s default redaction.+ * Both default to `false` (strip everything), so a caller that forgets to pass+ * options gets the fail-closed projection.+ */+export interface VisitorRedactionOptions {+ /**+ * `AgentShareConfig.showErrorDetails`. When false, a run failure is+ * projected down to a generic classified `type` (see+ * {@link sanitizeVisitorError}) instead of the raw+ * message/provider/budget/upstream-body payload `formatErrorForState`+ * builds.+ */+ showErrorDetails?: boolean;+ /**+ * `AgentShareConfig.showModelInfo`. When false, the creator's model /+ * provider choice and the token/cost snapshot are stripped everywhere they+ * appear, at any nesting depth.+ */+ showModelInfo?: boolean;+}++export interface SoftDeletedMessage {+ /** Live children that were re-parented away from this message at trash time. */+ childIds: string[];+ content: string | null;+ id: string;+ /** Pulled in as a tool companion of a requested message (never a root of its own). */+ isCompanion: boolean;+ /**+ * For a companion: the requested message whose tool call produced it, so the+ * caller can file it under the right root. `null` for requested rows.+ */+ ownerId: string | null;+ parentId: string | null;+ projectId: string | null;+ role: string;+ topicId: string | null;+}diff --git a/packages/database/src/models/message/visitor.ts b/packages/database/src/models/message/visitor.tsnew file mode 100644index 00000000000..5027506ad4e--- /dev/null+++ b/packages/database/src/models/message/visitor.ts@@ -0,0 +1,433 @@+import type {+ AssistantContentBlock,+ ChatMessageError,+ ChatMessageExtra,+ MessageMetadata,+ TaskDetail,+ UIChatMessage,+ UISignalCallbacksBlock,+ WorkSummaryItem,+} from '@lobechat/types';+import { AgentRuntimeErrorType, ChatErrorType } from '@lobechat/types';+import { isPlainRecord } from '@lobechat/utils/object';++import type { VisitorRedactionOptions } from './types';++/**+ * Fields on {@link UIChatMessage} that are safe to forward to an agent-share+ * visitor verbatim: the message's OWN presentational content (text,+ * attachments, tool activity, RAG citations) and structural links WITHIN the+ * same shared topic (thread/group/parent ids). None of these describe the+ * creator's account, billing, or model/provider choice.+ *+ * This is an ALLOWLIST, not a denylist, and that direction is deliberate:+ * `UIChatMessage` is a ~40-field DTO shared with the normal (non-share) chat+ * read path, so new fields land on it regularly as chat features ship. A+ * denylist fails OPEN on every such addition β a new field reaches visitors by+ * default until someone remembers to also strip it here. An allowlist fails+ * CLOSED: a new field is absent from the visitor DTO until a human+ * deliberately adds it below.+ *+ * Deliberately included despite being an id: `agentId` (the visitor already+ * knows which agent they are talking to β that's the whole premise of the+ * share link), `sessionId`/`traceId`/`observationId` (opaque ids scoped to+ * THIS execution of the visitor's OWN turn, reused by client actions such as+ * translate/regenerate that the share UI shares with normal chat).+ */+const VISITOR_MESSAGE_ALLOWED_KEYS = [+ 'id',+ 'role',+ 'content',+ 'createdAt',+ 'updatedAt',+ 'editorData',+ 'fileList',+ 'files',+ 'imageList',+ 'videoList',+ 'audioList',+ 'chunksList',+ 'plugin',+ 'pluginIntervention',+ 'tool_call_id',+ 'tools',+ 'reasoning',+ 'search',+ 'ragQuery',+ 'ragQueryId',+ 'ragRawQuery',+ 'parentId',+ 'threadId',+ 'topicId',+ 'groupId',+ 'targetId',+ 'agentId',+ 'sessionId',+ 'quotaId',+ 'branch',+ 'tasks',+ 'performance',+ 'observationId',+ 'traceId',+] as const satisfies readonly (keyof UIChatMessage)[];++type VisitorAllowedKey = (typeof VISITOR_MESSAGE_ALLOWED_KEYS)[number];++const pickAllowedKeys = (message: UIChatMessage): Pick<UIChatMessage, VisitorAllowedKey> => {+ const picked = {} as Pick<UIChatMessage, VisitorAllowedKey>;+ for (const key of VISITOR_MESSAGE_ALLOWED_KEYS) {+ if (key in message) (picked as Record<string, unknown>)[key] = message[key];+ }+ return picked;+};++/** Keep translate/TTS (visitor-facing rendering), drop the model snapshot. */+const sanitizeVisitorExtra = (extra: ChatMessageExtra | undefined): ChatMessageExtra | undefined =>+ extra ? { translate: extra.translate, tts: extra.tts } : extra;++/**+ * Shape shared by `pinnedMessages` entries and `compareGroup.children` entries+ * (`queryMessageGroupNodes` builds them with this exact narrow projection,+ * then casts the whole node `as unknown as UIChatMessage`, so+ * `UIChatMessage['pinnedMessages']` / `UIChatMessage['children']`'s declared+ * types do not describe them at runtime). Neither carries `sender`/`usage`,+ * only the model snapshot needs stripping.+ *+ * NOTE: on a `compressedGroup` node, `children` is NOT this narrow shape β it+ * lives inside `compressedMessages[].children` (an `AssistantContentBlock[]`+ * produced by `FlatListBuilder`) and carries `usage`, `error`, `tools`,+ * `metadata`, `performance`, and possibly nested `council` messages with+ * `sender`. See `toVisitorMessage` for the recursion that sanitizes those.+ */+interface VisitorGroupSnapshotProjection {+ content: string | null;+ createdAt: Date | number;+ id: string;+ model: string | null;+ provider: string | null;+ role: string;+}++const sanitizeVisitorGroupSnapshots = (+ items: VisitorGroupSnapshotProjection[],+): VisitorGroupSnapshotProjection[] =>+ items.map((item) => ({ ...item, model: null, provider: null }));++/** Cost/token figures are the same class of creator spend data as `usage`. */+const sanitizeVisitorTaskDetail = (taskDetail: TaskDetail | undefined): TaskDetail | undefined => {+ if (!taskDetail) return taskDetail;+ const {+ totalCost: _totalCost,+ totalTokens: _totalTokens,+ totalToolCalls: _totalToolCalls,+ ...rest+ } = taskDetail;+ return rest;+};++/**+ * Key names that identify the CREATOR's model/provider choice or spend/token+ * data wherever they occur inside an unbounded per-tool blob+ * (`pluginState`/`pluginError`, live Gateway event payloads). A builtin tool's+ * server runtime writes whatever shape it wants into `state`/error payloads β+ * e.g. `lobe-agent`'s `analyzeMedia` writes `{ model, provider, usage }`+ * straight into it β so unlike a short, fully enumerable list of top-level+ * `UIChatMessage` fields there is no finite set of "every tool's state shape"+ * to allowlist by hand: a new tool, or a new field on an existing tool's+ * `state`, must be safe BY DEFAULT. Recursing this fixed key set is the+ * fail-closed trade-off.+ */+const CREATOR_PRIVATE_BLOB_KEYS = new Set([+ 'model',+ 'provider',+ 'usage',+ 'cost',+ 'totalCost',+ 'totalTokens',+ 'promptTokens',+ 'completionTokens',+ 'inputTokens',+ 'outputTokens',+ // `AgentRuntimeService.publishSubAgentProgress`'s live `step_complete`+ // (`subagent_progress` phase) reads these off `state.usage.llm.tokens` under+ // the `total*` spelling rather than `inputTokens`/`outputTokens` β same+ // class of creator token-spend data, different key name.+ 'totalInputTokens',+ 'totalOutputTokens',+]);++/**+ * Recursively strip {@link CREATOR_PRIVATE_BLOB_KEYS} from an unbounded+ * JSON-like value at ANY nesting depth. Only descends into plain+ * objects/arrays (`isPlainRecord` already excludes `Date`/`Error`/class+ * instances) β anything else is returned as-is, since it cannot itself carry a+ * nested creator-identity field.+ *+ * Exported so `GatewayStreamNotifier`'s live Gateway-push chokepoint can apply+ * the SAME key set to `stream_start` (`model`/`provider`), `tool_end`+ * (`result`/`payload`, which can carry a tool's `state`), and `step_complete`+ * (`subagent_progress`'s sibling `model`/`totalCost`/token fields) β the live+ * WS payload equivalents of the persisted blobs this function was written for.+ */+export const redactCreatorPrivateBlob = <T>(value: T): T => {+ if (Array.isArray(value)) return value.map((item) => redactCreatorPrivateBlob(item)) as T;+ if (!isPlainRecord(value)) return value;++ const result: Record<string, unknown> = {};+ for (const [key, nested] of Object.entries(value)) {+ if (CREATOR_PRIVATE_BLOB_KEYS.has(key)) continue;+ result[key] = redactCreatorPrivateBlob(nested);+ }+ return result as T;+};++/**+ * `ChatMessageError.type` codes that are safe to forward to a visitor+ * VERBATIM, `message` included β because they are purpose-built,+ * business-level codes whose throw sites already write a clean, generic+ * `message` (never string-concatenated from a raw upstream payload) and whose+ * NAME itself says nothing about the creator's provider/model/account: "this+ * shared agent hit its per-topic turn cap", not "OpenAI rejected key sk-β¦".+ * Every other code β including the LEGITIMATE quota/rate-limit codes, whose+ * `message`/`body` are still built by `formatErrorForState` from the raw+ * upstream error β is projected to {@link VISITOR_PUBLIC_ERROR_TYPE}. Kept as+ * a narrow allowlist (fail closed) rather than an exclude list of "known+ * provider-identifying codes": some codes leak the provider through the TYPE+ * NAME alone (`OllamaServiceUnavailable`, `InvalidBedrockCredentials`, β¦), so+ * a denylist would need to enumerate those and would miss the next one a+ * model-runtime change adds.+ */+const VISITOR_SAFE_ERROR_TYPES = new Set<string>([+ ChatErrorType.ShareTurnLimitExceeded,+ ChatErrorType.ShareTopicLimitExceeded,+ ChatErrorType.ShareSpendLimitExceeded,+ ChatErrorType.ShareHeterogeneousAgentUnsupported,+ ChatErrorType.AgentShareProviderNotSupported,+]);++/**+ * Public fallback `type` for any `ChatMessageError` whose code is not in+ * {@link VISITOR_SAFE_ERROR_TYPES}. Reuses the existing generic+ * `AgentRuntimeError` bucket (already localized) rather than minting a new+ * code: the visitor only needs "the run failed, retry or contact the creator",+ * never which of the ~60 specific runtime codes fired.+ */+const VISITOR_PUBLIC_ERROR_TYPE = AgentRuntimeErrorType.AgentRuntimeError;++/**+ * Sanitize a `ChatMessageError` for a visitor β PROJECTION, not the recursive+ * {@link redactCreatorPrivateBlob} used for `pluginState`/`pluginError`.+ * `body` has no stable set of key names to strip: it is free-form per error+ * source and `formatErrorForState` deliberately copies `provider`, `budget`,+ * and the raw upstream diagnostic onto it for exactly the failures a visitor+ * can trigger on demand (bad key, exhausted quota, upstream 500) β so+ * recursing a fixed key set would miss the next shape a new error source+ * introduces. Dropping `body` wholesale and keeping only a classified `type`+ * (+ `message` for the allowlisted codes) fails closed instead: the client+ * re-derives its localized copy, alert styling, and error-card variant from+ * `type` alone.+ *+ * Bypassed entirely when the share sets `showErrorDetails` β the creator has+ * then explicitly opted into showing visitors the raw failure.+ */+export const sanitizeVisitorError = (+ error: ChatMessageError | null | undefined,+ options: VisitorRedactionOptions = {},+): ChatMessageError | null | undefined => {+ if (!error) return error;+ if (options.showErrorDetails) return error;++ const type = error.type as unknown;+ if (typeof type === 'string' && VISITOR_SAFE_ERROR_TYPES.has(type)) {+ return { message: error.message, type: error.type };+ }++ return { type: VISITOR_PUBLIC_ERROR_TYPE };+};++/**+ * `signalCallbacks[].callbacks[]` is a denormalized per-callback snapshot built+ * by `FlatListBuilder`, carrying a bare `model`/`provider` pair per callback+ * turn β same leak class as `pinnedMessages`/`children`'s group-node+ * snapshots.+ */+const sanitizeVisitorSignalCallbacks = (+ signalCallbacks: UISignalCallbacksBlock[] | undefined,+): UISignalCallbacksBlock[] | undefined =>+ signalCallbacks?.map((block) => ({+ ...block,+ callbacks: block.callbacks.map((callback) => ({+ ...callback,+ model: undefined,+ provider: undefined,+ })),+ }));++/**+ * `taskCompletions[]` blocks are denormalized post-task-summary snapshots built+ * by `FlatListBuilder`, each carrying its own `usage` β the same class of+ * creator spend data as the top-level `usage` field.+ */+const sanitizeVisitorTaskCompletions = (+ taskCompletions: AssistantContentBlock[] | undefined,+): AssistantContentBlock[] | undefined =>+ taskCompletions?.map(({ usage: _usage, ...rest }) => rest);++/**+ * `metadata.usage` / `metadata.cost` are the pre-migration duplicates of the+ * (denied) top-level `usage` field β kept on the type only so legacy rows+ * written before the dedicated `usage` column still type-check.+ * `queryWithWhere` itself falls back to `metadata.usage` for those rows, so+ * leaving `metadata` unsanitized would let the exact spend snapshot back in+ * through a legacy row's `metadata` blob. Every other `metadata` field is this+ * message's own presentational state and passes through untouched.+ */+const sanitizeVisitorMetadata = (+ metadata: MessageMetadata | null | undefined,+): MessageMetadata | null | undefined => {+ if (!metadata) return metadata;+ const { usage: _usage, cost: _cost, ...rest } = metadata;+ return rest;+};++/**+ * Project Work summaries for a share visitor. A visitor run executes as the+ * creator, so `userId` / `workspaceId` on every Work are the CREATOR's account+ * and workspace β dropped unconditionally, like the message-level `sender`.+ * The version spend snapshot is the creator's billing figure and follows the+ * `showModelInfo` gate (`stripSpend`).+ *+ * The identity keys are omitted rather than nulled (`userId` is non-nullable on+ * `WorkItem`); no visitor-facing Work surface reads them.+ */+const sanitizeVisitorWorks = (+ works: WorkSummaryItem[] | undefined,+ { stripSpend }: { stripSpend: boolean },+): WorkSummaryItem[] | undefined =>+ works?.map((work) => {+ const { userId: _userId, workspaceId: _workspaceId, ...rest } = work;+ const visible = stripSpend+ ? {+ ...rest,+ event: { ...rest.event, cumulativeCost: null, cumulativeUsage: null },+ totalCost: null,+ }+ : rest;+ return visible as WorkSummaryItem;+ });++/**+ * Strip creator-only fields from a message row before it reaches an+ * agent-share visitor. Creator account identity never crosses the share+ * boundary; the creator's model/provider/spend choices cross it only when the+ * share sets `showModelInfo`, and raw error payloads only when it sets+ * `showErrorDetails` ({@link VisitorRedactionOptions}).+ *+ * Built from {@link VISITOR_MESSAGE_ALLOWED_KEYS} plus explicit handling for+ * the fields that need transformation rather than a plain allow/deny.+ */+export const toVisitorMessage = (+ message: UIChatMessage,+ options: VisitorRedactionOptions = {},+): UIChatMessage => {+ const stripModelInfo = !options.showModelInfo;++ return {+ ...pickAllowedKeys(message),+ // `sender` is the CREATOR's account identity β never gated by any config+ // flag, since no share setting is about exposing whose account runs the+ // agent.+ sender: null,+ extra: stripModelInfo ? sanitizeVisitorExtra(message.extra) : message.extra,+ metadata: stripModelInfo ? sanitizeVisitorMetadata(message.metadata) : message.metadata,+ // Unbounded per-tool blobs: a tool runtime controls everything inside+ // them, so a fixed field allowlist can't classify their contents β the+ // creator-identity key set is recursed out instead.+ pluginError: stripModelInfo+ ? redactCreatorPrivateBlob(message.pluginError)+ : message.pluginError,+ pluginState: stripModelInfo+ ? redactCreatorPrivateBlob(message.pluginState)+ : message.pluginState,+ // Projected, not redacted β see `sanitizeVisitorError`.+ error: sanitizeVisitorError(message.error, options),+ ...(stripModelInfo+ ? {+ model: undefined,+ provider: undefined,+ signalCallbacks: sanitizeVisitorSignalCallbacks(message.signalCallbacks),+ taskCompletions: sanitizeVisitorTaskCompletions(message.taskCompletions),+ taskDetail: sanitizeVisitorTaskDetail(message.taskDetail),+ usage: undefined,+ }+ : {+ model: message.model,+ provider: message.provider,+ signalCallbacks: message.signalCallbacks,+ taskCompletions: message.taskCompletions,+ taskDetail: message.taskDetail,+ usage: message.usage,+ }),+ // Work summaries reach a visitor only when the query ran under their share+ // scope (see `queryForVisitor`), so every item here was registered from+ // this visitor's own topic. Creator identity is always dropped; spend+ // follows the `showModelInfo` gate β see `sanitizeVisitorWorks`.+ works: sanitizeVisitorWorks(message.works, { stripSpend: stripModelInfo }),+ // A compacted topic nests raw rows under the group node, and group chat+ // nests member messages, so anything less than a full recursive sanitize+ // would leave the creator's identity on everything inside it.+ ...(message.compressedMessages && {+ compressedMessages: message.compressedMessages.map((nested) =>+ toVisitorMessage(nested, options),+ ),+ }),+ ...(message.members && {+ members: message.members.map((nested) => toVisitorMessage(nested, options)),+ }),+ // `pinnedMessages` is only ever the narrow group-node projection (see+ // `queryMessageGroupNodes` in the Compression branch). Emit it in both+ // modes β sanitized when the model snapshot is not shared, otherwise+ // untouched.+ ...(message.pinnedMessages && {+ pinnedMessages: stripModelInfo+ ? (sanitizeVisitorGroupSnapshots(+ message.pinnedMessages as unknown as VisitorGroupSnapshotProjection[],+ ) as unknown as UIChatMessage['pinnedMessages'])+ : message.pinnedMessages,+ }),+ // `children` is polymorphic: a `compareGroup` node carries the same bare+ // {id, role, model, provider, content, createdAt} snapshot as+ // `pinnedMessages`; an `assistantGroup` node (produced inside+ // `compressedMessages` by `FlatListBuilder`) carries full+ // `AssistantContentBlock[]` with `usage`, `tools`, `error`, `metadata`,+ // `performance`, and possibly nested `council` messages with `sender` β+ // so a compareGroup-only narrow sanitize would let all of those through+ // for an assistantGroup child. Route by the PARENT `role` and recurse+ // assistantGroup children through `toVisitorMessage` itself so the+ // allowlist / error projection / usage & metadata stripping / council+ // recursion all apply.+ ...(message.children && {+ children:+ message.role === 'compareGroup'+ ? stripModelInfo+ ? (sanitizeVisitorGroupSnapshots(+ message.children as unknown as VisitorGroupSnapshotProjection[],+ ) as unknown as UIChatMessage['children'])+ : message.children+ : ((message.children as unknown as UIChatMessage[]).map((child) =>+ toVisitorMessage(child, options),+ ) as unknown as UIChatMessage['children']),+ }),+ // `AssistantContentBlock.council` on a nested assistantGroup child is a+ // `Message[]` of the supervisor's broadcast members, each carrying its+ // own `sender` / model / usage. `pickAllowedKeys` drops `council`+ // outright (fail closed), so re-attach a recursively sanitized copy+ // whenever the source carried one.+ ...((message as unknown as { council?: unknown }).council !== undefined &&+ ({+ council: ((message as unknown as { council?: UIChatMessage[] }).council ?? []).map(+ (member) => toVisitorMessage(member, options),+ ),+ } as unknown as Partial<UIChatMessage>)),+ } as UIChatMessage;+};diff --git a/packages/database/src/models/message/write.ts b/packages/database/src/models/message/write.tsnew file mode 100644index 00000000000..adfec8d3899--- /dev/null+++ b/packages/database/src/models/message/write.ts@@ -0,0 +1,534 @@+import type {+ CreateMessageParams,+ DBMessageItem,+ ModelUsage,+ NewMessageQueryParams,+ UpdateMessageParams,+} from '@lobechat/types';+import { runTimedSinkStage as runTimedStage } from '@lobechat/utils';+import { and, eq, inArray } from 'drizzle-orm';++import { clampToolIdentifier } from '@/utils/clampToolIdentifier';+import { merge } from '@/utils/merge';+import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';++import {+ messagePlugins,+ messageQueries,+ messageQueryChunks,+ messages,+ messagesFiles,+} from '../../schemas';+import type { Transaction } from '../../type';+import { buildWorkspacePayload } from '../../utils/workspace';+import { recomputeTopicUsage } from '../topicUsage';+import { MessageScope } from './scope';+import type { ModelTimingContext } from './types';++interface CreateUserAndAssistantMessagesParams {+ assistantMessage: CreateMessageParams;+ userMessage: CreateMessageParams;+}++interface CreateUserAndAssistantMessagesOptions {+ /**+ * Ids minted by the caller (the client) for the pair. Either side may be+ * omitted, in which case this model mints that one β an older client that+ * sends no ids keeps working unchanged.+ *+ * Honouring a caller-supplied id is what lets the UI render the pair under+ * its final ids immediately, instead of showing placeholders and re-keying+ * them once this insert returns.+ */+ ids?: {+ assistantMessageId?: string;+ userMessageId?: string;+ };+ timing?: ModelTimingContext;+}++interface CreateMessageInsertParams {+ createdAt?: CreateMessageParams['createdAt'];+ fromModel?: CreateMessageParams['model'];+ fromProvider?: CreateMessageParams['provider'];+ message: Omit<+ CreateMessageParams,+ | 'createdAt'+ | 'fileChunks'+ | 'files'+ | 'model'+ | 'plugin'+ | 'pluginIntervention'+ | 'pluginState'+ | 'provider'+ | 'ragQueryId'+ | 'updatedAt'+ >;+ updatedAt?: CreateMessageParams['updatedAt'];+}++interface CreateMessageRelationParams {+ fileChunks?: CreateMessageParams['fileChunks'];+ files?: CreateMessageParams['files'];+ plugin?: CreateMessageParams['plugin'];+ pluginError?: CreateMessageParams['pluginError'];+ pluginIntervention?: CreateMessageParams['pluginIntervention'];+ pluginState?: CreateMessageParams['pluginState'];+ ragQueryId?: CreateMessageParams['ragQueryId'];+}++interface SplitCreateMessageParams {+ insert: CreateMessageInsertParams;+ relations: CreateMessageRelationParams;+}++export class MessageWriteMutations extends MessageScope {+ /**+ * Row-lock message roots in id order (`SELECT β¦ FOR UPDATE`) and return+ * their content. Only meaningful on a transaction-bound instance; used by the+ * human-approval unit of work in `MessageApprovalRepo`.+ */+ lockContentForUpdate = async (ids: string[]) =>+ this.db+ .select({ content: messages.content, id: messages.id })+ .from(messages)+ .where(and(inArray(messages.id, ids), this.ownership()))+ .orderBy(messages.id)+ .for('update');++ /** Replace one message's content. Returns `false` when it is outside this scope. */+ updateContent = async (id: string, content: string): Promise<boolean> => {+ const [updated] = await this.db+ .update(messages)+ .set({ content })+ .where(and(eq(messages.id, id), this.ownership()))+ .returning({ id: messages.id });+ return Boolean(updated);+ };++ private splitCreateMessageParams = ({+ fileChunks,+ files,+ model: fromModel,+ plugin,+ pluginError,+ pluginIntervention,+ pluginState,+ provider: fromProvider,+ ragQueryId,+ updatedAt,+ createdAt,+ ...message+ }: CreateMessageParams): SplitCreateMessageParams => ({+ insert: {+ createdAt,+ fromModel,+ fromProvider,+ message,+ updatedAt,+ },+ relations: {+ fileChunks,+ files,+ plugin,+ pluginError,+ pluginIntervention,+ pluginState,+ ragQueryId,+ },+ });++ private buildMessageInsertValue = (+ { createdAt, fromModel, fromProvider, message, updatedAt }: CreateMessageInsertParams,+ id: string,+ ) => {+ // Ensure group message does not populate sessionId+ const normalizedMessage = message.groupId ? { ...message, sessionId: null } : message;+ const { usage: legacyUsage, ...metadata } =+ (normalizedMessage.metadata as Record<string, any> | undefined) || {};++ return buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ ...normalizedMessage,+ // Sanitize content to strip null bytes that PostgreSQL rejects+ content: sanitizeNullBytes(normalizedMessage.content),+ // TODO: remove this when the client is updated+ createdAt: createdAt ? new Date(createdAt) : undefined,+ id,+ metadata: normalizedMessage.metadata ? metadata : undefined,+ model: fromModel,+ provider: fromProvider,+ updatedAt: updatedAt ? new Date(updatedAt) : undefined,+ // Promote token usage into the dedicated `usage` column, preferring a+ // top-level `usage` over the legacy `metadata.usage`.+ usage: normalizedMessage.usage ?? (legacyUsage as ModelUsage | undefined),+ },+ );+ };++ private insertMessageRelationsInTransaction = async (+ trx: Transaction,+ {+ fileChunks,+ files,+ plugin,+ pluginError,+ pluginIntervention,+ pluginState,+ ragQueryId,+ }: CreateMessageRelationParams,+ message: CreateMessageInsertParams['message'],+ id: string,+ timing?: ModelTimingContext,+ timingPrefix: string = 'db.message.create',+ ): Promise<void> => {+ // Insert the plugin data if the message is a tool+ if (message.role === 'tool') {+ await runTimedStage(timing, `${timingPrefix}.plugin.insert`, () =>+ trx.insert(messagePlugins).values({+ apiName: clampToolIdentifier(plugin?.apiName),+ arguments: sanitizeNullBytes(plugin?.arguments),+ // A tool that fails on its first write only has pluginError to explain+ // itself; without it the model reads an empty tool result.+ error: sanitizeNullBytes(pluginError),+ id,+ identifier: clampToolIdentifier(plugin?.identifier),+ intervention: pluginIntervention,+ state: sanitizeNullBytes(pluginState),+ toolCallId: message.tool_call_id,+ type: plugin?.type,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ }),+ );+ }++ if (files && files.length > 0) {+ await runTimedStage(+ timing,+ `${timingPrefix}.files.insert`,+ () =>+ trx.insert(messagesFiles).values(+ files.map((file) => ({+ fileId: file,+ messageId: id,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ ),+ { fileCount: files.length },+ );+ }++ if (fileChunks && fileChunks.length > 0 && ragQueryId) {+ await runTimedStage(+ timing,+ `${timingPrefix}.fileChunks.insert`,+ () =>+ trx.insert(messageQueryChunks).values(+ fileChunks.map((chunk) => ({+ chunkId: chunk.id,+ messageId: id,+ queryId: ragQueryId,+ similarity: chunk.similarity?.toString(),+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ ),+ { chunkCount: fileChunks.length },+ );+ }+ };++ private createInTransaction = async (+ trx: Transaction,+ params: CreateMessageParams,+ id: string,+ timing?: ModelTimingContext,+ timingPrefix: string = 'db.message.create',+ ): Promise<DBMessageItem> => {+ const { insert, relations } = this.splitCreateMessageParams(params);++ const [item] = (await runTimedStage(+ timing,+ `${timingPrefix}.messages.insert`,+ () => trx.insert(messages).values(this.buildMessageInsertValue(insert, id)).returning(),+ {+ hasGroupId: !!insert.message.groupId,+ hasTopicId: !!insert.message.topicId,+ role: insert.message.role,+ },+ )) as DBMessageItem[];++ await this.insertMessageRelationsInTransaction(+ trx,+ relations,+ insert.message,+ id,+ timing,+ timingPrefix,+ );++ return item;+ };++ create = async (+ params: CreateMessageParams,+ id: string = this.genId(),+ timing?: ModelTimingContext,+ ): Promise<DBMessageItem> => {+ return runTimedStage(+ timing,+ 'db.message.create.transaction',+ () =>+ this.db.transaction(async (trx) => {+ const item = await this.createInTransaction(trx, params, id, timing);++ return item;+ }),+ {+ fileChunkCount: params.fileChunks?.length ?? 0,+ fileCount: params.files?.length ?? 0,+ hasTopicId: !!params.topicId,+ role: params.role,+ },+ );+ };++ createUserAndAssistantMessages = async (+ { userMessage, assistantMessage }: CreateUserAndAssistantMessagesParams,+ { ids, timing }: CreateUserAndAssistantMessagesOptions = {},+ ): Promise<{ assistantMessage: DBMessageItem; userMessage: DBMessageItem }> => {+ const userMessageId = ids?.userMessageId ?? this.genId();+ const assistantMessageId = ids?.assistantMessageId ?? this.genId();+ const createdAt = Date.now();+ const defaultUserCreatedAt = createdAt;+ const defaultAssistantCreatedAt = createdAt + 1;+ const userMessageWithTimestamp = {+ ...userMessage,+ createdAt: userMessage.createdAt ?? defaultUserCreatedAt,+ updatedAt:+ userMessage.updatedAt ?? (userMessage.createdAt ? undefined : defaultUserCreatedAt),+ };+ const assistantMessageWithParent = {+ ...assistantMessage,+ createdAt: assistantMessage.createdAt ?? defaultAssistantCreatedAt,+ parentId: userMessageId,+ updatedAt:+ assistantMessage.updatedAt ??+ (assistantMessage.createdAt ? undefined : defaultAssistantCreatedAt),+ };+ const topicIds = [+ ...new Set([userMessage.topicId, assistantMessage.topicId].filter(Boolean) as string[]),+ ];++ return runTimedStage(+ timing,+ 'db.message.createUserAndAssistant.transaction',+ () =>+ this.db.transaction(async (trx) => {+ const userPayload = this.splitCreateMessageParams(userMessageWithTimestamp);+ const assistantPayload = this.splitCreateMessageParams(assistantMessageWithParent);+ const insertedMessages = (await runTimedStage(+ timing,+ 'db.message.createUserAndAssistant.messages.insert',+ () =>+ trx+ .insert(messages)+ .values([+ this.buildMessageInsertValue(userPayload.insert, userMessageId),+ this.buildMessageInsertValue(assistantPayload.insert, assistantMessageId),+ ])+ .returning(),+ { hasTopicId: topicIds.length > 0, messageCount: 2 },+ )) as DBMessageItem[];+ const messageMap = new Map(insertedMessages.map((message) => [message.id, message]));++ await this.insertMessageRelationsInTransaction(+ trx,+ userPayload.relations,+ userPayload.insert.message,+ userMessageId,+ timing,+ 'db.message.createUserAndAssistant.user',+ );+ await this.insertMessageRelationsInTransaction(+ trx,+ assistantPayload.relations,+ assistantPayload.insert.message,+ assistantMessageId,+ timing,+ 'db.message.createUserAndAssistant.assistant',+ );++ const userMessageItem = messageMap.get(userMessageId);+ const assistantMessageItem = messageMap.get(assistantMessageId);++ if (!userMessageItem || !assistantMessageItem) {+ throw new Error('Failed to create user and assistant messages');+ }++ return { assistantMessage: assistantMessageItem, userMessage: userMessageItem };+ }),+ {+ assistantFileCount: assistantMessage.files?.length ?? 0,+ hasTopicId: topicIds.length > 0,+ userFileCount: userMessage.files?.length ?? 0,+ },+ );+ };++ batchCreate = async (newMessages: DBMessageItem[]) => {+ const messagesToInsert = newMessages.map((m) =>+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ // TODO: need a better way to handle this+ { ...m, role: m.role as any },+ ),+ );++ return this.db.transaction(async (trx) => {+ const result = await trx.insert(messages).values(messagesToInsert);++ return result;+ });+ };++ createMessageQuery = async (params: NewMessageQueryParams) => {+ const result = await this.db+ .insert(messageQueries)+ .values({ ...params, userId: this.userId, workspaceId: this.workspaceId ?? null })+ .returning();++ return result[0];+ };++ update = async (+ id: string,+ { imageList, metadata, usage, ...message }: Partial<UpdateMessageParams>,+ timing?: ModelTimingContext,+ ): Promise<{ success: boolean }> => {+ // Accept legacy callers that still send `metadata.usage`, but persist usage+ // exclusively in the dedicated top-level column.+ const { usage: legacyUsage, ...metadataPatch } = (metadata as Record<string, any>) || {};+ const usageToWrite = usage ?? (legacyUsage as ModelUsage | undefined);+ const shouldUpdateMetadata = !!metadata || !!usageToWrite;+ // A patch that matches no row is a lost write, not a no-op: the caller asked+ // to persist content onto `id` and it went nowhere. Batched writers key their+ // retry ledger off this flag, so reporting success here silently drops data.+ let matchedRow = false;+ try {+ await runTimedStage(+ timing,+ 'db.message.update.transaction',+ () =>+ this.db.transaction(async (trx) => {+ // 1. insert message files+ if (imageList && imageList.length > 0) {+ await runTimedStage(+ timing,+ 'db.message.update.imageFiles.insert',+ () =>+ trx.insert(messagesFiles).values(+ imageList.map((file) => ({+ fileId: file.id,+ messageId: id,+ userId: this.userId,+ workspaceId: this.workspaceId ?? null,+ })),+ ),+ { imageCount: imageList.length },+ );+ }++ // 2. Merge non-usage metadata. A usage-bearing update also removes+ // any legacy `metadata.usage` left on the existing row.+ let mergedMetadata: Record<string, any> | undefined;+ if (shouldUpdateMetadata) {+ const [existingMessage] = await runTimedStage(+ timing,+ 'db.message.update.metadata.select',+ () =>+ trx+ .select({ metadata: messages.metadata })+ .from(messages)+ .where(and(eq(messages.id, id), this.ownership())),+ );+ mergedMetadata = merge(existingMessage?.metadata || {}, metadataPatch);+ if (usageToWrite && mergedMetadata) delete mergedMetadata.usage;+ }+ const metadataToWrite = mergedMetadata;++ const [updated] = await runTimedStage(+ timing,+ 'db.message.update.messages.update',+ () =>+ trx+ .update(messages)+ .set({+ ...message,+ ...(metadataToWrite && { metadata: metadataToWrite }),+ ...(usageToWrite && { usage: usageToWrite }),+ })+ .where(and(eq(messages.id, id), this.ownership()))+ .returning({ topicId: messages.topicId }),+ { hasMetadata: !!metadataPatch, valueKeys: Object.keys(message) },+ );++ matchedRow = !!updated;++ if (+ updated?.topicId && // When this write carries token usage (assistant finalize / hetero+ // step), recompute the topic's denormalized usage rollup from its+ // messages. Gated on the *incoming* payload so streaming+ // content-only updates don't trigger needless recomputes.+ usageToWrite+ ) {+ await runTimedStage(+ timing,+ 'db.message.update.topic.recomputeUsage',+ () => recomputeTopicUsage(trx, this.userId, updated.topicId!, this.workspaceId),+ { topicCount: 1 },+ );+ }+ }),+ {+ hasImageList: !!imageList?.length,+ hasMetadata: shouldUpdateMetadata,+ valueKeys: Object.keys(message),+ },+ );++ if (!matchedRow) {+ console.error(`Update message error: no message matched id ${id}`);+ return { success: false };+ }++ return { success: true };+ } catch (error) {+ console.error('Update message error:', error);+ return { success: false };+ }+ };++ updateMetadata = async (id: string, metadata: Record<string, any>) => {+ const item = await this.db.query.messages.findFirst({+ where: and(eq(messages.id, id), this.ownership()),+ });++ if (!item) return;++ const { usage: usageToWrite, ...metadataPatch } = metadata as Record<string, any>;+ const mergedMetadata = merge(item.metadata || {}, metadataPatch);+ if (usageToWrite) delete mergedMetadata.usage;++ return this.db+ .update(messages)+ .set({+ metadata: mergedMetadata,+ ...(usageToWrite && { usage: usageToWrite }),+ })+ .where(and(eq(messages.id, id), this.ownership()));+ };+}diff --git a/packages/database/src/repositories/messageApproval/__tests__/index.test.ts b/packages/database/src/repositories/messageApproval/__tests__/index.test.tsnew file mode 100644index 00000000000..a5404f3f3b7--- /dev/null+++ b/packages/database/src/repositories/messageApproval/__tests__/index.test.ts@@ -0,0 +1,141 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { HumanApprovalAlreadyResolvedError } from '../../../models/message';+import { messagePlugins, messages, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { MessageApprovalRepo } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'message-approval-repo-user';+const otherUserId = 'message-approval-repo-other';+const repo = new MessageApprovalRepo(serverDB, userId);++const pending = { batchId: 'batch-1', itemIndex: 0, operationId: 'op-1', status: 'pending' };++const seedPendingTool = async (id: string, owner = userId) => {+ await serverDB.insert(messages).values({ content: 'before', id, role: 'tool', userId: owner });+ await serverDB.insert(messagePlugins).values({+ apiName: 'editFile',+ id,+ identifier: 'lobe-local-system',+ intervention: pending,+ state: { kept: true },+ toolCallId: `call-${id}`,+ userId: owner,+ });+};++const readRows = async (id: string) => {+ const [message] = await serverDB.select().from(messages).where(eq(messages.id, id));+ const [plugin] = await serverDB.select().from(messagePlugins).where(eq(messagePlugins.id, id));+ return { message, plugin };+};++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('MessageApprovalRepo', () => {+ it('publishes message content and plugin patch in one claim', async () => {+ await seedPendingTool('mar-claim');++ const result = await repo.resolve(+ [+ {+ content: 'approved',+ id: 'mar-claim',+ intervention: { resolutionRequestId: 'req-1', status: 'approved' },+ pluginState: { approvedBy: 'review' },+ },+ ],+ { publishResult: true },+ );++ expect(result).toBe('applied');+ const { message, plugin } = await readRows('mar-claim');+ expect(message.content).toBe('approved');+ expect(plugin.intervention).toEqual({+ ...pending,+ resolutionRequestId: 'req-1',+ status: 'approved',+ });+ expect(plugin.state).toEqual({ approvedBy: 'review', kept: true });+ });++ it('claims without publishing content until publishResult is set', async () => {+ await seedPendingTool('mar-claim-only');++ await repo.resolve([+ {+ content: 'private result',+ id: 'mar-claim-only',+ intervention: { resolutionRequestId: 'req-2', status: 'approved' },+ },+ ]);++ const { message, plugin } = await readRows('mar-claim-only');+ expect(message.content).toBe('before');+ expect(plugin.intervention).toMatchObject({ resolutionRequestId: 'req-2', status: 'approved' });+ });++ it('rejects a second winner and fails closed on rows outside the scope', async () => {+ await seedPendingTool('mar-own');+ await seedPendingTool('mar-foreign', otherUserId);+ const claim = {+ id: 'mar-own',+ intervention: { resolutionRequestId: 'req-3', status: 'approved' },+ };+ await repo.resolve([claim]);++ await expect(+ repo.resolve([+ { ...claim, intervention: { resolutionRequestId: 'req-4', status: 'rejected' } },+ ]),+ ).rejects.toBeInstanceOf(HumanApprovalAlreadyResolvedError);+ await expect(+ repo.resolve([{ ...claim, content: 'stolen', id: 'mar-foreign' }], { publishResult: true }),+ ).rejects.toThrow('Plugin not found: mar-foreign');++ const foreign = await readRows('mar-foreign');+ expect(foreign.message.content).toBe('before');+ expect(foreign.plugin.intervention).toEqual(pending);+ });++ it('restores the pre-claim snapshot for the owning request', async () => {+ await seedPendingTool('mar-restore');+ await repo.resolve(+ [+ {+ content: 'approved',+ id: 'mar-restore',+ intervention: { resolutionRequestId: 'req-5', status: 'approved' },+ },+ ],+ { publishResult: true },+ );++ await repo.restore([+ {+ claimedResolutionRequestId: 'req-5',+ content: 'before',+ id: 'mar-restore',+ intervention: pending,+ pluginState: { kept: true },+ },+ ]);++ const { message, plugin } = await readRows('mar-restore');+ expect(message.content).toBe('before');+ expect(plugin.intervention).toEqual(pending);+ expect(plugin.state).toEqual({ kept: true });+ });+});diff --git a/packages/database/src/repositories/messageApproval/index.ts b/packages/database/src/repositories/messageApproval/index.tsnew file mode 100644index 00000000000..8cce3fb742b--- /dev/null+++ b/packages/database/src/repositories/messageApproval/index.ts@@ -0,0 +1,164 @@+import { merge } from '@/utils/merge';++import { MessageLookupQueries } from '../../models/message/lookup';+import { HumanApprovalAlreadyResolvedError, MessagePluginStore } from '../../models/message/plugin';+import type { MessageScopeArgs } from '../../models/message/scope';+import type { HumanApprovalResolution, MessageModelOptions } from '../../models/message/types';+import { MessageWriteMutations } from '../../models/message/write';+import type { LobeChatDatabase } from '../../type';++/**+ * Human-approval claim and rollback for a batch of parked tool messages, as one+ * unit of work.+ *+ * A claim locks and writes both the message roots (published tool content) and+ * their `message_plugins` rows (intervention / state / error), so the+ * transaction lives here and composes the single-table pieces of+ * `MessageWriteMutations` and `MessagePluginStore`, each bound to the+ * transaction. `MessageModel.resolveHumanApproval` / `restoreHumanApproval`+ * forward to this repository.+ */+export class MessageApprovalRepo {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ private readonly options: MessageModelOptions = {},+ ) {}++ private stores = (trx: LobeChatDatabase) => {+ const args: MessageScopeArgs = [trx, this.userId, this.workspaceId, undefined, this.options];+ return {+ messages: new MessageWriteMutations(...args),+ plugins: new MessagePluginStore(args, { lookups: new MessageLookupQueries(...args) }),+ };+ };++ /**+ * Resolve an approval batch at one row-locking boundary. Every target is+ * checked before any write, so Web, Mobile, Stop, and notification actions+ * cannot each win a subset of the same assistant turn. Source adapters claim+ * only; content/state remain in their private resolution until the runtime+ * passes publishResult after afterToolCall. Stop may publish its fixed receipt.+ */+ resolve = async (+ resolutions: HumanApprovalResolution[],+ options: { publishResult?: boolean } = {},+ ): Promise<'applied' | 'idempotent'> => {+ if (resolutions.length === 0) return 'idempotent';++ const ids = resolutions.map(({ id }) => id);+ if (new Set(ids).size !== ids.length) {+ throw new Error('Human approval batch contains duplicate tool messages');+ }++ return this.db.transaction(async (trx) => {+ const stores = this.stores(trx as LobeChatDatabase);+ // Match deferred completion's lock order (message before plugin).+ const lockedMessages = await stores.messages.lockContentForUpdate(ids);+ const messagesById = new Map(lockedMessages.map((row) => [row.id, row]));+ const lockedRows = await stores.plugins.lockApprovalPluginsForUpdate(ids);+ const lockedById = new Map(lockedRows.map((row) => [row.id, row]));++ const rowStates = resolutions.map((resolution) => {+ const row = lockedById.get(resolution.id);+ if (!row) throw new Error(`Plugin not found: ${resolution.id}`);+ if (row.intervention?.status === 'pending') return 'pending' as const;++ const sameRequest =+ Boolean(resolution.intervention.resolutionRequestId) &&+ row.intervention?.resolutionRequestId === resolution.intervention.resolutionRequestId;+ const sameDecision = Object.entries(resolution.intervention).every(+ ([key, value]) =>+ JSON.stringify(row.intervention?.[key as keyof typeof row.intervention]) ===+ JSON.stringify(value),+ );+ if (sameRequest && sameDecision) return 'idempotent' as const;+ throw new HumanApprovalAlreadyResolvedError(resolution.id);+ });+ const pendingCount = rowStates.filter((state) => state === 'pending').length;+ if (pendingCount === 0 && !options.publishResult) return 'idempotent';+ if (pendingCount !== 0 && pendingCount !== resolutions.length) {+ throw new Error('Human approval batch contains a partial idempotent claim');+ }++ let published = false;+ for (const resolution of resolutions) {+ // An already claimed source answer can publish exactly once. A replay+ // retains the first final content, including a hook denial.+ if (+ pendingCount === 0 &&+ (messagesById.get(resolution.id)?.content ||+ (resolution.content === undefined &&+ resolution.pluginState === undefined &&+ resolution.pluginError === undefined))+ )+ continue;+ published = true;+ const row = lockedById.get(resolution.id)!;+ if (options.publishResult && resolution.content !== undefined) {+ const updatedMessage = await stores.messages.updateContent(+ resolution.id,+ resolution.content,+ );+ if (!updatedMessage) throw new Error(`Message not found: ${resolution.id}`);+ }++ const updatedPlugin = await stores.plugins.patchApprovalPlugin(resolution.id, {+ // Status/result is a claim patch, not a replacement. Preserve the+ // authoritative operation/batch/item identity stamped when the+ // parked tool row was created so subsequent source reads, Stop,+ // and rollback still address the same sealed batch.+ intervention: merge(row.intervention || {}, resolution.intervention),+ ...(options.publishResult &&+ resolution.pluginError !== undefined && { error: resolution.pluginError }),+ ...(options.publishResult &&+ resolution.pluginState !== undefined && {+ state: resolution.replacePluginState+ ? resolution.pluginState+ : merge(row.state || {}, resolution.pluginState || {}),+ }),+ });+ if (!updatedPlugin) throw new Error(`Plugin not found: ${resolution.id}`);+ }++ return published ? 'applied' : 'idempotent';+ });+ };++ /** Restore the exact pre-claim snapshot when continuation startup fails. */+ restore = async (resolutions: HumanApprovalResolution[]): Promise<void> => {+ if (resolutions.length === 0) return;++ await this.db.transaction(async (trx) => {+ const stores = this.stores(trx as LobeChatDatabase);+ const ids = resolutions.map(({ id }) => id);+ await stores.messages.lockContentForUpdate(ids);+ const lockedRows = await stores.plugins.lockApprovalPluginsForUpdate(ids);+ const lockedById = new Map(lockedRows.map((row) => [row.id, row]));++ for (const resolution of resolutions) {+ const locked = lockedById.get(resolution.id);+ if (!locked) throw new Error(`Plugin not found: ${resolution.id}`);+ if (+ resolution.claimedResolutionRequestId &&+ locked.intervention?.resolutionRequestId !== resolution.claimedResolutionRequestId+ ) {+ continue;+ }+ if (resolution.content !== undefined) {+ const updatedMessage = await stores.messages.updateContent(+ resolution.id,+ resolution.content,+ );+ if (!updatedMessage) throw new Error(`Message not found: ${resolution.id}`);+ }+ await stores.plugins.patchApprovalPlugin(resolution.id, {+ intervention: resolution.intervention,+ ...(resolution.pluginError !== undefined && { error: resolution.pluginError }),+ ...(resolution.pluginState !== undefined && { state: resolution.pluginState }),+ });+ }+ });+ };+}