🤯 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): replace schema-guaranteed fallbacks with shared row helpers (#21880)
Arvin Xu8b56604da087
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 6b989956313..2d7395c703e 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -1,9 +1,6 @@{"arguments.moreParams": "{{count}} params in total","arguments.title": "Arguments",- "builtins.builtin-dashboard.approve.dryRunWidget": "Approve dry run",- "builtins.builtin-dashboard.approve.requestPublish": "Approve publishing",- "builtins.builtin-dashboard.approveRemember.dryRunWidget": "Approve dry run, and don't ask again for the same access","builtins.builtin-dashboard.apiName.addWidgetToDashboard": "Add widget to dashboard","builtins.builtin-dashboard.apiName.createDashboard": "Create dashboard","builtins.builtin-dashboard.apiName.createWidgetDraft": "Create widget draft",@@ -13,6 +10,9 @@"builtins.builtin-dashboard.apiName.requestPublish": "Publish widget","builtins.builtin-dashboard.apiName.updateDashboard": "Update dashboard","builtins.builtin-dashboard.apiName.updateWidgetDraft": "Update widget draft",+ "builtins.builtin-dashboard.approve.dryRunWidget": "Approve dry run",+ "builtins.builtin-dashboard.approve.requestPublish": "Approve publishing",+ "builtins.builtin-dashboard.approveRemember.dryRunWidget": "Approve dry run, and don't ask again for the same access","builtins.builtin-dashboard.title": "Dashboards","builtins.builtin-goal.apiName.createGoal": "Start goal","builtins.claude-code.apiName.Agent": "Run subagent",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex e9f9785d22d..94b38233303 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -1,9 +1,6 @@{"arguments.moreParams": "等 {{count}} 个参数","arguments.title": "参数列表",- "builtins.builtin-dashboard.approve.dryRunWidget": "批准试运行",- "builtins.builtin-dashboard.approve.requestPublish": "批准发布",- "builtins.builtin-dashboard.approveRemember.dryRunWidget": "批准试运行,且相同权限不再询问","builtins.builtin-dashboard.apiName.addWidgetToDashboard": "添加组件到看板","builtins.builtin-dashboard.apiName.createDashboard": "创建看板","builtins.builtin-dashboard.apiName.createWidgetDraft": "创建组件草稿",@@ -13,6 +10,9 @@"builtins.builtin-dashboard.apiName.requestPublish": "发布组件","builtins.builtin-dashboard.apiName.updateDashboard": "更新看板","builtins.builtin-dashboard.apiName.updateWidgetDraft": "更新组件草稿",+ "builtins.builtin-dashboard.approve.dryRunWidget": "批准试运行",+ "builtins.builtin-dashboard.approve.requestPublish": "批准发布",+ "builtins.builtin-dashboard.approveRemember.dryRunWidget": "批准试运行,且相同权限不再询问","builtins.builtin-dashboard.title": "看板","builtins.builtin-goal.apiName.createGoal": "启动目标","builtins.claude-code.apiName.Agent": "运行子代理",diff --git a/packages/database/src/models/__tests__/favorite.test.ts b/packages/database/src/models/__tests__/favorite.test.tsindex 9adafadc953..f0beec0527c 100644--- a/packages/database/src/models/__tests__/favorite.test.ts+++ b/packages/database/src/models/__tests__/favorite.test.ts@@ -163,6 +163,15 @@ describe('FavoriteModel', () => {expect((await workspaceModel.query()).map((item) => item.id)).toEqual([foreign.id]);});+ it('leaves the scope untouched when it has no favorites to reorder', async () => {+ const foreign = await workspaceModel.add(topic('tpc_ws'));++ await personalModel.reorder([foreign.id]);++ expect(await personalModel.query()).toEqual([]);+ expect((await workspaceModel.query()).map((item) => item.id)).toEqual([foreign.id]);+ });+it('updates the snapshot of a favorite in scope', async () => {const item = await personalModel.add(topic('tpc_1', 'Old'));diff --git a/packages/database/src/models/agent/find.ts b/packages/database/src/models/agent/find.tsindex 6c905de3608..a88d33dcb6b 100644--- a/packages/database/src/models/agent/find.ts+++ b/packages/database/src/models/agent/find.ts@@ -221,8 +221,7 @@ export const getAgentVisibilityMeta = async (return {slug: row.slug,userId: row.userId,- /* v8 ignore next -- unreachable: agents.visibility is NOT NULL (default 'public'), so the `?? 'public'` fallback never runs */- visibility: (row.visibility as 'private' | 'public' | null) ?? 'public',+ visibility: row.visibility,};};diff --git a/packages/database/src/models/agent/list.ts b/packages/database/src/models/agent/list.tsindex a484e00a4ff..5e3e51cc5a9 100644--- a/packages/database/src/models/agent/list.ts+++ b/packages/database/src/models/agent/list.ts@@ -7,6 +7,7 @@ import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';import { notShareVisitorTopic } from '../../utils/shareVisitor';import { notTrashed } from '../../utils/softDelete';+import { countOf } from '../utils/rows';import { type AgentModelContext } from './context';import { type DeviceBindingCandidate } from './types';@@ -290,8 +291,7 @@ export const countAgents = async (]),);- /* v8 ignore next -- unreachable: count() without GROUP BY always returns exactly one non-null row */- return result[0]?.count ?? 0;+ return countOf(result, 'the agent count');};/**diff --git a/packages/database/src/models/agentDocuments/agentDocument/queries.ts b/packages/database/src/models/agentDocuments/agentDocument/queries.tsindex f097138dd1d..ded4cce7f81 100644--- a/packages/database/src/models/agentDocuments/agentDocument/queries.ts+++ b/packages/database/src/models/agentDocuments/agentDocument/queries.ts@@ -10,7 +10,7 @@ import {type AgentDocumentListSourceType,type AgentDocumentPolicy,type AgentDocumentWithRules,- DocumentLoadFormat,+ type DocumentLoadFormat,PolicyLoad,} from '../types';import { agentDocOwnership, type AgentDocumentContext, documentOwnership } from './context';@@ -210,12 +210,7 @@ export async function findContextByAgent(parentId: doc.parentId ?? null,policy,policyLoad: settings.policyLoad as PolicyLoad,- policyLoadFormat:- (settings.policyLoadFormat as DocumentLoadFormat | null) ??- /* v8 ignore start -- unreachable: agent_documents.policy_load_format is NOT NULL */- policy?.context?.policyLoadFormat ??- DocumentLoadFormat.RAW,- /* v8 ignore stop */+ policyLoadFormat: settings.policyLoadFormat as DocumentLoadFormat,policyLoadPosition: settings.policyLoadPosition,policyLoadRule: settings.policyLoadRule,sourceType: doc.sourceType,diff --git a/packages/database/src/models/agentDocuments/agentDocument/tree.ts b/packages/database/src/models/agentDocuments/agentDocument/tree.tsindex a5c392099a4..59b5c797f15 100644--- a/packages/database/src/models/agentDocuments/agentDocument/tree.ts+++ b/packages/database/src/models/agentDocuments/agentDocument/tree.ts@@ -1,6 +1,7 @@import { and, asc, eq, inArray, isNotNull, isNull, sql } from 'drizzle-orm';import { agentDocuments, documents } from '../../../schemas';+import { nonNull } from '../../utils/rows';import type { AgentDocument } from '../types';import { agentDocOwnership, type AgentDocumentContext } from './context';import { findByDocumentId } from './queries';@@ -61,9 +62,8 @@ export async function countChildrenByParentIds(.groupBy(documents.parentId);return new Map(- /* v8 ignore start -- unreachable `: []`: the WHERE clause (inArray / isNotNull on parent_id) never yields a NULL parent */- rows.flatMap((row) => (row.parentId ? [[row.parentId, Number(row.count)] as const] : [])),- /* v8 ignore stop */+ // The WHERE clause (inArray / isNotNull on parent_id) never yields a NULL parent.+ rows.map((row) => [nonNull(row.parentId, 'documents.parent_id'), Number(row.count)] as const),);}diff --git a/packages/database/src/models/agentDocuments/agentDocument/utils.ts b/packages/database/src/models/agentDocuments/agentDocument/utils.tsindex 26f22ead261..bdbf7809c0f 100644--- a/packages/database/src/models/agentDocuments/agentDocument/utils.ts+++ b/packages/database/src/models/agentDocuments/agentDocument/utils.ts@@ -2,13 +2,13 @@ import { eq, isNotNull, isNull, ne } from 'drizzle-orm';import { agentDocuments, type DocumentItem, documents } from '../../../schemas';import { deriveAgentDocumentFields } from '../deriveFields';-import {- type AgentDocument,- type AgentDocumentListItem,- type AgentDocumentListSourceType,- type AgentDocumentPolicy,+import type {+ AgentDocument,+ AgentDocumentListItem,+ AgentDocumentListSourceType,+ AgentDocumentPolicy,DocumentLoadFormat,- type PolicyLoad,+ PolicyLoad,} from '../types';import type { AgentDocumentListQueryRow, AgentDocumentQueryOptions } from './types';@@ -75,12 +75,7 @@ export function toAgentDocument(doc: DocumentItem,): AgentDocument {const policy = (settings.policy as AgentDocumentPolicy | null) ?? null;- const policyLoadFormat =- (settings.policyLoadFormat as DocumentLoadFormat | null) ??- /* v8 ignore start -- unreachable: agent_documents.policy_load_format is NOT NULL */- policy?.context?.policyLoadFormat ??- DocumentLoadFormat.RAW;- /* v8 ignore stop */+ const policyLoadFormat = settings.policyLoadFormat as DocumentLoadFormat;return {accessPublic: settings.accessPublic,@@ -106,8 +101,7 @@ export function toAgentDocument(policyLoadFormat,policyLoadPosition: settings.policyLoadPosition,policyLoadRule: settings.policyLoadRule,- /* v8 ignore next -- unreachable: documents.source is NOT NULL */- source: doc.source ?? null,+ source: doc.source,sourceType: doc.sourceType,templateId: settings.templateId ?? null,title: doc.title ?? doc.filename ?? '',diff --git a/packages/database/src/models/chunk.ts b/packages/database/src/models/chunk.tsindex b84334facd4..e78b94087c1 100644--- a/packages/database/src/models/chunk.ts+++ b/packages/database/src/models/chunk.ts@@ -45,10 +45,8 @@ export class ChunkModel {workspaceId: this.workspaceId ?? null,}));- /* v8 ignore else -- unreachable: `params` is non-empty here and INSERT … RETURNING yields one row per value */- if (fileChunksData.length > 0) {- await trx.insert(fileChunks).values(fileChunksData);- }+ // `params` is non-empty here and INSERT … RETURNING yields one row per value.+ await trx.insert(fileChunks).values(fileChunksData);return result;});diff --git a/packages/database/src/models/documentComment.ts b/packages/database/src/models/documentComment.tsindex 7167e0564a9..79386dcd65c 100644--- a/packages/database/src/models/documentComment.ts+++ b/packages/database/src/models/documentComment.ts@@ -22,6 +22,7 @@ import { documentCommentMentions, documentComments } from '../schemas/documentCoimport { documents } from '../schemas/file';import type { LobeChatDatabase } from '../type';import { notTrashed } from '../utils/softDelete';+import { nonNull } from './utils/rows';export const DOCUMENT_COMMENT_WORKSPACE_REQUIRED ='Document comments are workspace-scoped; a workspaceId is required';@@ -484,10 +485,11 @@ export class DocumentCommentModel {).groupBy(documentComments.parentCommentId): [];- /* v8 ignore next -- unreachable: the `[]` arm; inArray(parent_comment_id, rootIds) never matches a NULL parent */+ // inArray(parent_comment_id, rootIds) never matches a NULL parent.const countByRoot = new Map(- replyCounts.flatMap(({ parentCommentId, total }) =>- parentCommentId ? [[parentCommentId, total] as const] : [],+ replyCounts.map(+ ({ parentCommentId, total }) =>+ [nonNull(parentCommentId, 'document_comments.parent_comment_id'), total] as const,),);diff --git a/packages/database/src/models/documentLike.ts b/packages/database/src/models/documentLike.tsindex 906bb144b73..e861106b60a 100644--- a/packages/database/src/models/documentLike.ts+++ b/packages/database/src/models/documentLike.ts@@ -6,6 +6,7 @@ import { documents } from '../schemas/file';import { users } from '../schemas/user';import type { LobeChatDatabase } from '../type';import { notTrashed } from '../utils/softDelete';+import { countOf } from './utils/rows';export const DOCUMENT_LIKE_WORKSPACE_REQUIRED ='Document likes are workspace-scoped; a workspaceId is required';@@ -89,9 +90,9 @@ export class DocumentLikeModel {documentId: string,knownLiked?: boolean,): Promise<DocumentLikeSummary> => {- const [[totals], likers] = await Promise.all([+ const [totals, likers] = await Promise.all([tx- .select({ total: count() })+ .select({ count: count() }).from(documentLikes).where(eq(documentLikes.documentId, documentId)),tx@@ -121,8 +122,7 @@ export class DocumentLikeModel {.limit(1)).length > 0);- /* v8 ignore next -- unreachable: count() without GROUP BY always returns exactly one non-null row */- return { liked, likers, total: totals?.total ?? 0 };+ return { liked, likers, total: countOf(totals, 'the document like count') };};async like(documentId: string): Promise<LikeDocumentResult> {diff --git a/packages/database/src/models/environment.ts b/packages/database/src/models/environment.tsindex 3e798b4a62d..f117aa9a9af 100644--- a/packages/database/src/models/environment.ts+++ b/packages/database/src/models/environment.ts@@ -6,6 +6,7 @@ import type { EnvironmentItem, NewEnvironment } from '../schemas';import { environments, users } from '../schemas';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { nonNull } from './utils/rows';export interface EnvironmentCreator {avatar: string | null;@@ -282,17 +283,14 @@ export class EnvironmentModel {return rows.map(({ creatorAvatar, creatorFullName, creatorId, creatorUsername, ...row }) => ({...row,- // The id is what says a creator was found; a deleted account leaves the- // join empty and the row keeps its place in the listing with no creator.- /* v8 ignore next -- unreachable: environments.user_id is NOT NULL with an on-delete-restrict FK to users, so the left join always finds the creator */- creator: creatorId- ? {- avatar: creatorAvatar,- fullName: creatorFullName,- id: creatorId,- username: creatorUsername,- }- : null,+ // environments.user_id is NOT NULL with an on-delete-restrict FK to+ // users, so the left join always finds the creator.+ creator: {+ avatar: creatorAvatar,+ fullName: creatorFullName,+ id: nonNull(creatorId, 'the environment creator (users.id)'),+ username: creatorUsername,+ },}));};diff --git a/packages/database/src/models/generationBatch.ts b/packages/database/src/models/generationBatch.tsindex 8c8ebc484fc..9d777cef0db 100644--- a/packages/database/src/models/generationBatch.ts+++ b/packages/database/src/models/generationBatch.ts@@ -268,15 +268,12 @@ export class GenerationBatchModel {// 2. Collect asset file URLs that need to be deleted (video, cover, thumbnail)const filesToDelete: string[] = [];- /* v8 ignore next -- unreachable: a drizzle `with` many-relation always loads as an array */- if (batchWithGenerations.generations) {- for (const gen of batchWithGenerations.generations) {- const asset = gen.asset as ImageGenerationAsset | VideoGenerationAsset | null;- if (asset?.url) filesToDelete.push(asset.url);- if (asset?.thumbnailUrl) filesToDelete.push(asset.thumbnailUrl);- if (asset && 'coverUrl' in asset && asset.coverUrl) {- filesToDelete.push(asset.coverUrl);- }+ for (const gen of batchWithGenerations.generations) {+ const asset = gen.asset as ImageGenerationAsset | VideoGenerationAsset | null;+ if (asset?.url) filesToDelete.push(asset.url);+ if (asset?.thumbnailUrl) filesToDelete.push(asset.thumbnailUrl);+ if (asset && 'coverUrl' in asset && asset.coverUrl) {+ filesToDelete.push(asset.coverUrl);}}diff --git a/packages/database/src/models/generationTopic.ts b/packages/database/src/models/generationTopic.tsindex 8033ce62418..4bbc5ada001 100644--- a/packages/database/src/models/generationTopic.ts+++ b/packages/database/src/models/generationTopic.ts@@ -234,16 +234,13 @@ export class GenerationTopicModel {}// Add asset file URLs from all generations (video, cover, thumbnail)- /* v8 ignore next -- unreachable: a drizzle `with` many-relation always loads as an array */- if (topicWithBatches.batches) {- for (const batch of topicWithBatches.batches) {- for (const gen of batch.generations) {- const asset = gen.asset as ImageGenerationAsset | VideoGenerationAsset | null;- if (asset?.url) filesToDelete.push(asset.url);- if (asset?.thumbnailUrl) filesToDelete.push(asset.thumbnailUrl);- if (asset && 'coverUrl' in asset && asset.coverUrl) {- filesToDelete.push(asset.coverUrl);- }+ for (const batch of topicWithBatches.batches) {+ for (const gen of batch.generations) {+ const asset = gen.asset as ImageGenerationAsset | VideoGenerationAsset | null;+ if (asset?.url) filesToDelete.push(asset.url);+ if (asset?.thumbnailUrl) filesToDelete.push(asset.thumbnailUrl);+ if (asset && 'coverUrl' in asset && asset.coverUrl) {+ filesToDelete.push(asset.coverUrl);}}}diff --git a/packages/database/src/models/message/analytics.ts b/packages/database/src/models/message/analytics.tsindex 20529d63759..573dbfb9e4c 100644--- a/packages/database/src/models/message/analytics.ts+++ b/packages/database/src/models/message/analytics.ts@@ -9,6 +9,7 @@ import { agents, messages } from '../../schemas';import { notCopiedTranscript } from '../../utils/copiedTranscript';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../../utils/genWhere';import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { nonNull } from '../utils/rows';import { MessageScope } from './scope';import type { MessageAnalyticsFilters, TopicMessageCountItem, TopicMessageStats } from './types';@@ -338,11 +339,9 @@ export class MessageAnalyticsQueries extends MessageScope {const dateCountMap = new Map<string, number>();for (const item of result) {- /* v8 ignore else -- unreachable: `DATE(created_at)` is never null: `created_at` is NOT NULL */- if (item?.date) {- const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- dateCountMap.set(dateStr, item.count);- }+ // messages.created_at is NOT NULL, so DATE(created_at) is never NULL.+ const date = nonNull(item.date, 'DATE(messages.created_at)') as string;+ dateCountMap.set(dayjs(date).format('YYYY-MM-DD'), item.count);}while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {@@ -407,13 +406,11 @@ export class MessageAnalyticsQueries extends MessageScope {const dateTokenMap = new Map<string, number>();let maxTokens = 0;for (const item of result) {- /* v8 ignore else -- unreachable: `DATE(created_at)` is never null: `created_at` is NOT NULL */- 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;- }+ // messages.created_at is NOT NULL, so DATE(created_at) is never NULL.+ const date = nonNull(item.date, 'DATE(messages.created_at)') as string;+ const tokens = item.tokens || 0;+ dateTokenMap.set(dayjs(date).format('YYYY-MM-DD'), tokens);+ if (tokens > maxTokens) maxTokens = tokens;}const heatmapData: HeatmapsProps['data'] = [];diff --git a/packages/database/src/models/message/backgroundSubAgent.ts b/packages/database/src/models/message/backgroundSubAgent.tsindex 2822b9fe6b5..b9d3ef4a919 100644--- a/packages/database/src/models/message/backgroundSubAgent.ts+++ b/packages/database/src/models/message/backgroundSubAgent.ts@@ -1,6 +1,7 @@import { and, asc, eq, inArray, sql } from 'drizzle-orm';import { messagePlugins, messages } from '../../schemas';+import { nonNull } from '../utils/rows';import { MessageScope } from './scope';/**@@ -60,8 +61,11 @@ export class MessageBackgroundSubAgentQueries extends MessageScope {).orderBy(asc(messages.createdAt), asc(messages.id));- /* v8 ignore next -- unreachable: `state` is never null here: the WHERE clause requires `state->>'background' = 'true'` */- return rows.map((row) => ({ ...row, state: (row.state ?? {}) as Record<string, any> }));+ // The WHERE clause requires `state->>'background' = 'true'`, so `state` is never NULL.+ return rows.map((row) => ({+ ...row,+ state: nonNull(row.state, 'message_plugins.state') as Record<string, any>,+ }));};/**diff --git a/packages/database/src/models/message/branchSnapshots.ts b/packages/database/src/models/message/branchSnapshots.tsindex 419ff785ecb..6d8e6818faa 100644--- a/packages/database/src/models/message/branchSnapshots.ts+++ b/packages/database/src/models/message/branchSnapshots.ts@@ -3,6 +3,7 @@ import { and, asc, eq, inArray, not } from 'drizzle-orm';import { messages } from '../../schemas';import type { Transaction } from '../../type';+import { nonNull } from '../utils/rows';import { MessageScope } from './scope';interface ActiveBranchSnapshot {@@ -69,11 +70,11 @@ export class MessageBranchSnapshots extends MessageScope {const branchIdsByParent = new Map<string, string[]>();for (const branch of branchRows) {- /* v8 ignore next -- unreachable: `inArray(messages.parentId, …)` already excludes NULL parents */- if (!branch.parentId) continue;- const branchIds = branchIdsByParent.get(branch.parentId) ?? [];+ // `inArray(messages.parentId, …)` already excludes NULL parents.+ const parentId = nonNull(branch.parentId, 'messages.parent_id');+ const branchIds = branchIdsByParent.get(parentId) ?? [];branchIds.push(branch.id);- branchIdsByParent.set(branch.parentId, branchIds);+ branchIdsByParent.set(parentId, branchIds);}return branchIdsByParent;diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.tsindex e0d94728916..965494c419e 100644--- a/packages/database/src/models/message/lookup.ts+++ b/packages/database/src/models/message/lookup.ts@@ -18,6 +18,7 @@ import { ilikeContains } from '../../utils/like';import { searchableMessage } from '../../utils/searchableMessage';import { notShareVisitorMessage } from '../../utils/shareVisitor';import { buildWorkspaceWhere } from '../../utils/workspace';+import { nonNull } from '../utils/rows';import { MessageScope } from './scope';import { buildMessageSearchSnippet } from './searchSnippet';@@ -427,8 +428,8 @@ export class MessageLookupQueries extends MessageScope {return rows.map(({ content, ...row }) => ({...row,- /* v8 ignore next -- unreachable: `content` is never null: the ILIKE filter on `content` drops NULL rows */- ...buildMessageSearchSnippet(content ?? '', needle),+ // The ILIKE filter on `content` drops NULL rows.+ ...buildMessageSearchSnippet(nonNull(content, 'messages.content'), needle),}));};diff --git a/packages/database/src/models/message/query.ts b/packages/database/src/models/message/query.tsindex 859c1906d0c..246ead29165 100644--- a/packages/database/src/models/message/query.ts+++ b/packages/database/src/models/message/query.ts@@ -16,6 +16,7 @@ import { and, asc, count, desc, eq, inArray, isNotNull, ne } from 'drizzle-orm';import { messagePlugins, messages } from '../../schemas';import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { nonNull } from '../utils/rows';import { resolveCursorPageWindow } from './cursorWindow';import type { MessageLookupQueries } from './lookup';import type { MessagePageQueries } from './queryWithWhere';@@ -83,9 +84,9 @@ export class MessageConversationQueries extends MessageScope {const result = new Map<string, string>();for (const row of rows) {- /* v8 ignore next -- unreachable: `content` and `topicId` are never null: the WHERE clause filters both */- const content = (row.content ?? '').trim();- if (row.topicId && content) result.set(row.topicId, content);+ // The WHERE clause filters both `content` and `topicId` to non-NULL.+ const content = nonNull(row.content, 'messages.content').trim();+ if (content) result.set(nonNull(row.topicId, 'messages.topic_id'), content);}return result;};diff --git a/packages/database/src/models/message/search.ts b/packages/database/src/models/message/search.tsindex 588c688c2ff..2072bea84e3 100644--- a/packages/database/src/models/message/search.ts+++ b/packages/database/src/models/message/search.ts@@ -7,6 +7,7 @@ import { sanitizeBm25Query } from '../../utils/bm25';import { inJsonStringArray } from '../../utils/inJsonStringArray';import { searchableMessage } from '../../utils/searchableMessage';import { notChannelTopic } from '../../utils/topicVisibility';+import { nonNull } from '../utils/rows';import type { MessageLookupQueries } from './lookup';import type { MessageScopeArgs } from './scope';import { MessageScope } from './scope';@@ -245,8 +246,8 @@ export class MessageKeywordSearchQueries extends MessageScope {truncated,hasMore: rows.length > pageSize,items: rows.slice(0, pageSize).map(({ content, summary, ...row }) => {- /* v8 ignore next -- unreachable: `searchableMessage()` requires searchable text in `content` or `summary` */- const body = content || summary || '';+ // `searchableMessage()` requires searchable text in `content` or `summary`.+ const body = nonNull(content || summary, 'messages.content or messages.summary');return {...row,contentLength: body.length,diff --git a/packages/database/src/models/message/trash.ts b/packages/database/src/models/message/trash.tsindex 099845631f9..e6d8035623e 100644--- a/packages/database/src/models/message/trash.ts+++ b/packages/database/src/models/message/trash.ts@@ -11,6 +11,7 @@ import {} from '../../utils/softDelete';import { buildWorkspaceWhere } from '../../utils/workspace';import { recomputeTopicUsage } from '../topicUsage';+import { nonNull } from '../utils/rows';import type { MessageBranchSnapshots } from './branchSnapshots';import type { MessageScopeArgs } from './scope';import { MessageScope } from './scope';@@ -84,8 +85,8 @@ export class MessageTrashMutations extends MessageScope {.from(messagePlugins).where(inArray(messagePlugins.toolCallId, toolCallIds));for (const row of companionRows) {- /* v8 ignore next -- unreachable: `toolCallId` is never null: `inArray(messagePlugins.toolCallId, …)` excludes NULL */- const owner = row.toolCallId ? toolCallOwner.get(row.toolCallId) : undefined;+ // `inArray(messagePlugins.toolCallId, …)` excludes NULL.+ const owner = toolCallOwner.get(nonNull(row.toolCallId, 'message_plugins.tool_call_id'));if (owner && !requestedIds.has(row.id)) companionOwner.set(row.id, owner);}const companionIds = [...companionOwner.keys()];diff --git a/packages/database/src/models/task/documents.ts b/packages/database/src/models/task/documents.tsindex fb31b09486f..65724f69e97 100644--- a/packages/database/src/models/task/documents.ts+++ b/packages/database/src/models/task/documents.ts@@ -94,8 +94,7 @@ export const getDocumentsPinnedSince = async (return rows.map((row) => ({id: row.id,- /* v8 ignore next -- unreachable: documents.file_type is NOT NULL and the inner join always yields a document row */- kind: row.fileType ?? null,+ kind: row.fileType,title: row.title ?? null,}));};diff --git a/packages/database/src/models/task/rows.ts b/packages/database/src/models/task/rows.tsindex 26784f1486a..3e1701df74e 100644--- a/packages/database/src/models/task/rows.ts+++ b/packages/database/src/models/task/rows.ts@@ -3,6 +3,7 @@ import { and, eq, inArray, ne, or, sql } from 'drizzle-orm';import { tasks } from '../../schemas/task';import type { LobeChatDatabase } from '../../type';+import { countOf } from '../utils/rows';import { seqOwnership, type TaskModelContext, taskOwnership } from './context';import { isTaskIdentifierUniqueViolation, normalizeTaskRefs } from './utils';@@ -146,7 +147,7 @@ export const countTasksBlockingAgentDemotion = async (agentOwnerUserId: string,): Promise<number> => {if (!ctx.workspaceId) return 0;- const [row] = await ctx.db+ const rows = await ctx.db.select({ count: sql<number>`count(*)` }).from(tasks).where(@@ -156,8 +157,7 @@ export const countTasksBlockingAgentDemotion = async (or(eq(tasks.visibility, 'public'), ne(tasks.createdByUserId, agentOwnerUserId)),),);- /* v8 ignore next -- unreachable: an ungrouped count() always returns exactly one non-null row */- return Number(row?.count ?? 0);+ return countOf(rows, 'the assigned task count');};/**diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 590ef8a216d..9d95bfef011 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -12,6 +12,7 @@ import { topics } from '../schemas/topic';import type { LobeChatDatabase } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';import { topicsOwnership } from './task/context';+import { countOf } from './utils/rows';export const TERMINAL_TOPIC_STATUSES = new Set(['canceled',@@ -370,12 +371,10 @@ export class TaskTopicModel {if (options?.triggers?.length) conditions.push(inArray(taskTopics.trigger, options.triggers));const rows = await this.db- .select({ value: count() })+ .select({ count: count() }).from(taskTopics).where(and(...conditions));- /* v8 ignore start -- unreachable: an ungrouped count() always returns one row */- return rows[0]?.value ?? 0;- /* v8 ignore stop */+ return countOf(rows, 'the task topic count');}async findByTaskId(taskId: string): Promise<TaskTopicItem[]> {@@ -511,12 +510,11 @@ export class TaskTopicModel {const byTask = rows.map((row) => ({runs: row.runs,taskId: row.taskId,- /* v8 ignore start -- unreachable: every sum is wrapped in coalesce(…, 0), never NULL */- totalCost: Number(row.totalCost ?? 0),- totalInputTokens: Number(row.totalInputTokens ?? 0),- totalOutputTokens: Number(row.totalOutputTokens ?? 0),- totalTokens: Number(row.totalTokens ?? 0),- /* v8 ignore stop */+ // Every sum is wrapped in coalesce(…, 0), so none of them is NULL.+ totalCost: Number(row.totalCost),+ totalInputTokens: Number(row.totalInputTokens),+ totalOutputTokens: Number(row.totalOutputTokens),+ totalTokens: Number(row.totalTokens),}));return {diff --git a/packages/database/src/models/topic/find.ts b/packages/database/src/models/topic/find.tsindex f7355e3fd74..2339fe85be9 100644--- a/packages/database/src/models/topic/find.ts+++ b/packages/database/src/models/topic/find.ts@@ -28,6 +28,7 @@ import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../import { inJsonStringArray } from '../../utils/inJsonStringArray';import { searchableMessage } from '../../utils/searchableMessage';import { notChannelTopic } from '../../utils/topicVisibility';+import { nonNull } from '../utils/rows';import type { TopicModelContext } from './context';import type { TopicKeywordScope } from './types';@@ -177,8 +178,10 @@ export const findRunInitiators = async ().orderBy(agentOperations.topicId, desc(agentOperations.startedAt));- /* v8 ignore next -- unreachable: the null-topicId fallback; `inArray(agentOperations.topicId, …)` never matches a NULL topic_id */- return new Map(rows.flatMap((row) => (row.topicId ? [[row.topicId, row.userId]] : [])));+ // `inArray(agentOperations.topicId, …)` never matches a NULL topic_id.+ return new Map(+ rows.map((row) => [nonNull(row.topicId, 'agent_operations.topic_id'), row.userId]),+ );};/**diff --git a/packages/database/src/models/topic/runningOperation.ts b/packages/database/src/models/topic/runningOperation.tsindex 0e28bce8a67..5d142914bb8 100644--- a/packages/database/src/models/topic/runningOperation.ts+++ b/packages/database/src/models/topic/runningOperation.ts@@ -437,8 +437,6 @@ export const isRunningOperationAlive = async (// Claims `running`/`idle`, but a killed process never writes a terminal// status — age it out so the topic is not held forever.- /* v8 ignore start -- unreachable: the `Number.NaN` arm; agent_operations.created_at is NOT NULL DEFAULT now() */- const startedAt = operation.createdAt ? new Date(operation.createdAt).getTime() : Number.NaN;- /* v8 ignore stop */- return !Number.isFinite(startedAt) || Date.now() - startedAt < ABANDONED_OPERATION_TTL_MS;+ // agent_operations.created_at is NOT NULL DEFAULT now().+ return Date.now() - operation.createdAt.getTime() < ABANDONED_OPERATION_TTL_MS;};diff --git a/packages/database/src/models/topicComment.ts b/packages/database/src/models/topicComment.tsindex 110216277ce..097569942b7 100644--- a/packages/database/src/models/topicComment.ts+++ b/packages/database/src/models/topicComment.ts@@ -30,6 +30,7 @@ import type { TopicCommentAnchorPreview, TopicCommentItem } from '../schemas/topimport { topicCommentMentions, topicComments } from '../schemas/topicComment';import type { LobeChatDatabase, Transaction } from '../type';import { notTrashed } from '../utils/softDelete';+import { countOf, nonNull } from './utils/rows';export const TOPIC_COMMENT_WORKSPACE_REQUIRED ='Topic comments are workspace-scoped; a workspaceId is required';@@ -661,13 +662,12 @@ export class TopicCommentModel {if (!comment || comment.deletedAt) return false;- const [structuralReplies] = await tx- .select({ total: count() })+ const structuralReplies = await tx+ .select({ count: count() }).from(topicComments)- .where(eq(topicComments.parentCommentId, id)); // v8 ignore start -- unreachable: an ungrouped count() always returns one row+ .where(eq(topicComments.parentCommentId, id));- if ((structuralReplies?.total ?? 0) > 0) {- // v8 ignore stop+ if (countOf(structuralReplies, 'the structural reply count') > 0) {await tx.update(topicComments).set({ content: '', deletedAt: new Date(), editorData: null, updatedAt: new Date() })@@ -689,13 +689,12 @@ export class TopicCommentModel {.limit(1);if (parent?.deletedAt) {- const [siblings] = await tx- .select({ total: count() })+ const siblings = await tx+ .select({ count: count() }).from(topicComments)- .where(eq(topicComments.parentCommentId, parent.id)); // v8 ignore start -- unreachable: an ungrouped count() always returns one row+ .where(eq(topicComments.parentCommentId, parent.id));- if ((siblings?.total ?? 0) === 0)- // v8 ignore stop+ if (countOf(siblings, 'the sibling reply count') === 0)await tx.delete(topicComments).where(eq(topicComments.id, parent.id));}}@@ -855,8 +854,7 @@ export class TopicCommentModel {const replyCountByRootId = new Map<string, number>();for (const row of replyCountRows) {- /* v8 ignore next -- unreachable: grouped by inArray(parentCommentId, …), never NULL */- if (row.parentCommentId) replyCountByRootId.set(row.parentCommentId, row.total);+ replyCountByRootId.set(nonNull(row.parentCommentId, 'inArray(parent_comment_id)'), row.total);}return {@@ -934,8 +932,8 @@ export class TopicCommentModel {eq(topicComments.workspaceId, workspaceId),);- const [totalRow] = await this.db- .select({ total: count() })+ const totalRows = await this.db+ .select({ count: count() }).from(topicComments).where(and(scope, isNull(topicComments.deletedAt), isNull(topicComments.moderatedAt)));@@ -968,8 +966,8 @@ export class TopicCommentModel {return {countByMessage: Object.fromEntries(byMessage.map((row) => [row.messageId as string, row.messageCount]),- ), // v8 ignore start -- unreachable: an ungrouped count() always returns one row- total: totalRow?.total ?? 0, // v8 ignore stop+ ),+ total: countOf(totalRows, 'the topic comment count'),};}@@ -1026,9 +1024,8 @@ export const purgeExpiredTopicCommentModeration = async (.select({ parentCommentId: topicComments.parentCommentId }).from(topicComments).where(inArray(topicComments.parentCommentId, candidateIds));- /* v8 ignore next -- unreachable: children are selected by inArray(parentCommentId, …), never NULL */const idsWithChildren = new Set(- children.flatMap(({ parentCommentId }) => (parentCommentId ? [parentCommentId] : [])),+ children.map(({ parentCommentId }) => nonNull(parentCommentId, 'inArray(parent_comment_id)')),);const tombstoneIds = candidateIds.filter((id) => idsWithChildren.has(id));const hardDeleteIds = candidateIds.filter((id) => !idsWithChildren.has(id));diff --git a/packages/database/src/models/userSkill.ts b/packages/database/src/models/userSkill.tsindex d82d9198628..8080771d488 100644--- a/packages/database/src/models/userSkill.ts+++ b/packages/database/src/models/userSkill.ts@@ -11,6 +11,7 @@ import {} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { nonNull } from './utils/rows';/*** A user-level skill library on the `documents` table.@@ -329,11 +330,11 @@ export class UserSkillModel {// One pass over the children, not one per bundle.const byBundle = new Map<string, (typeof children)[number][]>();for (const child of children) {- /* v8 ignore next -- unreachable: children are selected by inArray(documents.parentId, …), which never matches a NULL parentId */- if (!child.parentId) continue;- const list = byBundle.get(child.parentId) ?? [];+ // Children are selected by inArray(documents.parentId, …), which never matches a NULL parentId.+ const parentId = nonNull(child.parentId, 'documents.parent_id');+ const list = byBundle.get(parentId) ?? [];list.push(child);- byBundle.set(child.parentId, list);+ byBundle.set(parentId, list);}return bundles.map((bundle) => {const own = byBundle.get(bundle.id) ?? [];diff --git a/packages/database/src/models/utils/rows.test.ts b/packages/database/src/models/utils/rows.test.tsnew file mode 100644index 00000000000..2ba02f19e63--- /dev/null+++ b/packages/database/src/models/utils/rows.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import { countOf, firstRow, nonNull } from './rows';++describe('nonNull', () => {+ it('returns present values, including falsy ones', () => {+ expect(nonNull('a', 'x')).toBe('a');+ expect(nonNull(0, 'x')).toBe(0);+ expect(nonNull('', 'x')).toBe('');+ expect(nonNull(false, 'x')).toBe(false);+ });++ it('throws with the context when the value is null or undefined', () => {+ expect(() => nonNull(null, 'messages.parent_id')).toThrow(+ 'Expected a value for messages.parent_id, got null',+ );+ expect(() => nonNull(undefined, 'messages.parent_id')).toThrow(+ 'Expected a value for messages.parent_id, got undefined',+ );+ });+});++describe('firstRow', () => {+ it('returns the first row', () => {+ expect(firstRow([{ id: 1 }, { id: 2 }], 'rows')).toEqual({ id: 1 });+ });++ it('throws with the context when there is no row', () => {+ expect(() => firstRow([], 'the agent count')).toThrow(+ 'Expected a value for the first row of the agent count, got undefined',+ );+ });+});++describe('countOf', () => {+ it('reads the count of the single row', () => {+ expect(countOf([{ count: 3 }], 'rows')).toBe(3);+ expect(countOf([{ count: 0 }], 'rows')).toBe(0);+ });++ it('converts a text count(*) to a number', () => {+ expect(countOf([{ count: '42' }], 'rows')).toBe(42);+ });++ it('throws instead of returning 0 when the count row is missing', () => {+ expect(() => countOf([], 'workspace memberships')).toThrow(+ 'Expected a value for the first row of workspace memberships, got undefined',+ );+ });+});diff --git a/packages/database/src/models/utils/rows.ts b/packages/database/src/models/utils/rows.tsnew file mode 100644index 00000000000..a1958009b0e--- /dev/null+++ b/packages/database/src/models/utils/rows.ts@@ -0,0 +1,29 @@+/**+ * Accessors for values the schema or the SQL guarantees but drizzle's inferred+ * types still mark as possibly missing: the single row of an ungrouped+ * `count()`, a NOT NULL value read through a nullable column type, or a column+ * the WHERE clause already filters to non-NULL.+ *+ * They throw instead of falling back to `0`, `null`, or `[]`, so a broken+ * guarantee surfaces as an error rather than a silently wrong answer.+ */++/** Returns `value`, or throws when the guarantee named by `context` does not hold. */+export const nonNull = <T>(value: T | null | undefined, context: string): T => {+ if (value === null || value === undefined) {+ throw new Error(`Expected a value for ${context}, got ${String(value)}`);+ }+ return value;+};++/** Returns the row a query must yield, or throws when it is missing. */+export const firstRow = <T>(rows: readonly T[], context: string): T =>+ nonNull(rows[0], `the first row of ${context}`);++/**+ * Reads the `count` column of an ungrouped `count()` query, which always+ * returns exactly one row. Accepts `count(*)` read as text (`sql<number>`+ * without a cast arrives as a string from node-postgres).+ */+export const countOf = (rows: readonly { count: number | string }[], context: string): number =>+ Number(firstRow(rows, context).count);diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 2839fee71fd..2a92d1e3f93 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -397,9 +397,7 @@ export class VerifyRunModel {plan,planConfirmedAt: new Date(),scenario: target.scenario ?? source.scenario,- /* v8 ignore start -- unreachable: verify_runs.source is NOT NULL */- source: source.source ?? target.source,- /* v8 ignore stop */+ source: source.source,// The survivor takes over the source's identity, so it takes over its// pipeline status too. An ingested round carries none and the report// settles it, which is what nulls the draft's own `planned` here. A LIVEdiff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.tsindex 32c789f6857..0da9de0bec3 100644--- a/packages/database/src/models/work/queries.ts+++ b/packages/database/src/models/work/queries.ts@@ -18,6 +18,7 @@ import { documents } from '../../schemas/file';import { tasks } from '../../schemas/task';import { topics } from '../../schemas/topic';import { works, workVersions } from '../../schemas/work';+import { nonNull } from '../utils/rows';import { type WorkContext, workOwnership } from './context';import { getTotalCostByWorkIds } from './cost';import {@@ -106,11 +107,14 @@ export const listByRootOperations = async (.sort((a, b) => b.version.createdAt.getTime() - a.version.createdAt.getTime());for (const item of items) {- const rootOperationId = item.version.rootOperationId;- /* v8 ignore next -- unreachable: every adapter filters rows by inArray(rootOperationId, rootOperationIds) */- if (!rootOperationId || !(rootOperationId in result)) continue;- if (result[rootOperationId].length >= limit) continue;- result[rootOperationId].push(item);+ // Every adapter filters rows by inArray(rootOperationId, rootOperationIds),+ // and `result` holds a bucket for each of those ids.+ const bucket = nonNull(+ result[nonNull(item.version.rootOperationId, 'work_versions.root_operation_id')],+ 'the work summary bucket of a requested root operation',+ );+ if (bucket.length >= limit) continue;+ bucket.push(item);}return result;@@ -161,9 +165,9 @@ export const listSummariesByRootOperations = async (const anchorByWorkId = new Map<string, string>();for (const row of eventRows) {- /* v8 ignore next -- unreachable: the query filters on inArray(rootOperationId, rootOperationIds) */- if (!row.rootOperationId) continue;- if (!anchorByWorkId.has(row.workId)) anchorByWorkId.set(row.workId, row.rootOperationId);+ // The query filters on inArray(rootOperationId, rootOperationIds).+ const rootOperationId = nonNull(row.rootOperationId, 'work_versions.root_operation_id');+ if (!anchorByWorkId.has(row.workId)) anchorByWorkId.set(row.workId, rootOperationId);}if (anchorByWorkId.size === 0) return result;diff --git a/packages/database/src/models/workspace.ts b/packages/database/src/models/workspace.tsindex 1e4ba5aa3eb..57c26897467 100644--- a/packages/database/src/models/workspace.ts+++ b/packages/database/src/models/workspace.ts@@ -14,6 +14,7 @@ import {} from '../schemas/workspace';import type { LobeChatDatabase } from '../type';import { AGENT_TRANSFER_PENDING_OWNER_DELETE, AgentTransferJobModel } from './agentTransferJob';+import { countOf } from './utils/rows';import { DEFAULT_TEAM_IDENTIFIER, deriveTeamIdentifier } from './workspaceTeam';export const getActiveWorkspaceMembershipRole = async (@@ -218,9 +219,7 @@ export class WorkspaceModel {.select({ count: count() }).from(workspaceMembers).where(and(eq(workspaceMembers.userId, this.userId), isNull(workspaceMembers.deletedAt)));- /* v8 ignore start -- unreachable: an ungrouped count() always returns one row */- return result[0]?.count ?? 0;- /* v8 ignore stop */+ return countOf(result, 'the workspace membership count');};listUserWorkspaces = async () => {diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex f7cff1c2469..1ef7a5b1d0e 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -572,7 +572,8 @@ export default {'builtins.lobe-canvas.title': 'Canvas','builtins.builtin-dashboard.approve.dryRunWidget': 'Approve dry run','builtins.builtin-dashboard.approve.requestPublish': 'Approve publishing',- 'builtins.builtin-dashboard.approveRemember.dryRunWidget': "Approve dry run, and don't ask again for the same access",+ 'builtins.builtin-dashboard.approveRemember.dryRunWidget':+ "Approve dry run, and don't ask again for the same access",'builtins.builtin-dashboard.apiName.addWidgetToDashboard': 'Add widget to dashboard','builtins.builtin-dashboard.apiName.createDashboard': 'Create dashboard','builtins.builtin-dashboard.apiName.createWidgetDraft': 'Create widget draft',