Skip to content

🤯 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.

✅ test(database): 100% coverage for models/topic (#21850)

Arvin Xu0860b4ab69d4
diff --git a/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts b/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts
new file mode 100644
index 00000000000..acf2031fb2f
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.runGuards.test.ts
@@ -0,0 +1,399 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentOperations, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+import { ABANDONED_OPERATION_TTL_MS } from '../../topic/runningOperation';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'topic-run-guards-user';
+const otherUserId = 'topic-run-guards-other';
+const topicId = 'topic-run-guards-topic';
+const otherTopicId = 'topic-run-guards-other-topic';
+const operationId = 'topic-run-guards-operation';
+
+const topicModel = new TopicModel(serverDB, userId);
+
+const readMetadata = async (id = topicId) => {
+ const row = await serverDB.query.topics.findFirst({ where: (t, { eq }) => eq(t.id, id) });
+ return row?.metadata;
+};
+
+const readStatus = async (id = topicId) => {
+ const row = await serverDB.query.topics.findFirst({ where: (t, { eq }) => eq(t.id, id) });
+ return row?.status;
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ // agent_operations.user_id has no FK, so the row would outlive its owner.
+ await serverDB.delete(agentOperations).where(inArray(agentOperations.id, [operationId]));
+ // Topics cascade with their owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('TopicModel running-operation guards', () => {
+ it('reports the corrected settle with the hetero message the late callback owns', async () => {
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: {
+ heteroCurrentMsgId: { msgId: 'msg-late', operationId: 'op-root' },
+ lastSettledOperationId: 'op-root',
+ },
+ status: 'unread',
+ userId,
+ });
+
+ const result = await topicModel.settleRunningOperation(topicId, 'op-root', 'active');
+
+ expect(result).toEqual({ assistantMessageId: 'msg-late', status: 'corrected' });
+ expect(await readStatus()).toBe('active');
+ });
+
+ it('refuses to append a child under a parent that does not own the topic', async () => {
+ const runningOperation = { assistantMessageId: 'msg-root', operationId: 'op-root' };
+ await serverDB.insert(topics).values({ id: topicId, metadata: { runningOperation }, userId });
+
+ const child = { assistantMessageId: 'msg-child', operationId: 'op-child' };
+
+ expect(await topicModel.appendRunningOperationChild(topicId, 'op-stale', child)).toBe(false);
+ expect(await topicModel.appendRunningOperationChild('missing-topic', 'op-root', child)).toBe(
+ false,
+ );
+ expect((await readMetadata())?.runningOperation).toEqual(runningOperation);
+ });
+
+ it('refuses to patch a topic with no marker or an operation it does not carry', async () => {
+ await serverDB.insert(topics).values([
+ { id: otherTopicId, metadata: {}, userId },
+ {
+ id: topicId,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg-root',
+ childOperations: [{ assistantMessageId: 'msg-child', operationId: 'op-child' }],
+ operationId: 'op-root',
+ },
+ },
+ userId,
+ },
+ ]);
+
+ expect(await topicModel.patchRunningOperation('missing-topic', 'op-root', {})).toBe(false);
+ expect(await topicModel.patchRunningOperation(otherTopicId, 'op-root', {})).toBe(false);
+ expect(await topicModel.patchRunningOperation(topicId, 'op-unknown', { scope: 'x' })).toBe(
+ false,
+ );
+ expect((await readMetadata())?.runningOperation?.childOperations).toEqual([
+ { assistantMessageId: 'msg-child', operationId: 'op-child' },
+ ]);
+ });
+
+ it('refuses to patch a non-root operation when the marker has no children', async () => {
+ const runningOperation = { assistantMessageId: 'msg-root', operationId: 'op-root' };
+ await serverDB.insert(topics).values({ id: topicId, metadata: { runningOperation }, userId });
+
+ expect(await topicModel.patchRunningOperation(topicId, 'op-child', { scope: 'x' })).toBe(false);
+ expect((await readMetadata())?.runningOperation).toEqual(runningOperation);
+ });
+
+ it('points the root operation and hetero anchor at a new assistant message', async () => {
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: {
+ runningOperation: { assistantMessageId: 'msg-old', operationId: 'op-root', scope: 'main' },
+ },
+ userId,
+ });
+
+ const updated = await topicModel.updateRunningOperationAssistantMessage(
+ topicId,
+ 'op-root',
+ 'msg-new',
+ );
+
+ expect(updated).toBe(true);
+ expect(await readMetadata()).toEqual({
+ heteroCurrentMsgId: { msgId: 'msg-new', operationId: 'op-root' },
+ runningOperation: { assistantMessageId: 'msg-new', operationId: 'op-root', scope: 'main' },
+ });
+ });
+
+ it('leaves the assistant message alone when the topic or operation is unknown', async () => {
+ await serverDB.insert(topics).values([
+ { id: otherTopicId, metadata: {}, userId },
+ {
+ id: topicId,
+ metadata: { runningOperation: { assistantMessageId: 'msg-root', operationId: 'op-root' } },
+ userId,
+ },
+ ]);
+
+ expect(
+ await topicModel.updateRunningOperationAssistantMessage('missing-topic', 'op-root', 'm'),
+ ).toBe(false);
+ expect(
+ await topicModel.updateRunningOperationAssistantMessage(otherTopicId, 'op-root', 'm'),
+ ).toBe(false);
+ // No children at all, so a non-root id can never match.
+ expect(await topicModel.updateRunningOperationAssistantMessage(topicId, 'op-child', 'm')).toBe(
+ false,
+ );
+ expect(await readMetadata()).toEqual({
+ runningOperation: { assistantMessageId: 'msg-root', operationId: 'op-root' },
+ });
+ });
+
+ it('takes the root operation off the topic and returns it', async () => {
+ const runningOperation = { assistantMessageId: 'msg-root', operationId: 'op-root' };
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: { boundDeviceId: 'device-1', runningOperation },
+ userId,
+ });
+
+ const taken = await topicModel.takeRunningOperation(topicId, 'op-root');
+
+ expect(taken).toEqual({ isRoot: true, operation: runningOperation });
+ expect(await readMetadata()).toEqual({ boundDeviceId: 'device-1', runningOperation: null });
+ });
+
+ it('takes nothing from a missing topic or one without a marker', async () => {
+ await serverDB.insert(topics).values({ id: topicId, metadata: {}, userId });
+
+ expect(await topicModel.takeRunningOperation('missing-topic', 'op-root')).toBeUndefined();
+ expect(await topicModel.takeRunningOperation(topicId, 'op-root')).toBeUndefined();
+ });
+
+ it('does not touch another user’s topic', async () => {
+ const runningOperation = { assistantMessageId: 'msg-root', operationId: 'op-root' };
+ await serverDB
+ .insert(topics)
+ .values({ id: otherTopicId, metadata: { runningOperation }, userId: otherUserId });
+
+ expect(await topicModel.takeRunningOperation(otherTopicId, 'op-root')).toBeUndefined();
+ expect((await readMetadata(otherTopicId))?.runningOperation).toEqual(runningOperation);
+ });
+});
+
+describe('TopicModel task-callback reservation past a dead run', () => {
+ const runningOperation = {
+ assistantMessageId: 'msg-dead',
+ operationId,
+ startedAt: new Date().toISOString(),
+ };
+ const longAgo = new Date(Date.now() - ABANDONED_OPERATION_TTL_MS - 60_000);
+
+ const expectReserved = async () => {
+ expect(await topicModel.tryReserveTaskCallback(topicId, 'callback-msg')).toBe(true);
+ expect((await readMetadata())?.taskCallbackReservation?.messageId).toBe('callback-msg');
+ };
+
+ it('reserves a topic whose marker points at a finished operation', async () => {
+ await serverDB.insert(topics).values({ id: topicId, metadata: { runningOperation }, userId });
+ await serverDB
+ .insert(agentOperations)
+ .values({ id: operationId, status: 'done', topicId, userId });
+
+ await expectReserved();
+ });
+
+ it('reserves a topic whose operation still claims running past the abandoned TTL', async () => {
+ await serverDB.insert(topics).values({ id: topicId, metadata: { runningOperation }, userId });
+ await serverDB
+ .insert(agentOperations)
+ .values({ createdAt: longAgo, id: operationId, status: 'running', topicId, userId });
+
+ await expectReserved();
+ });
+
+ it('reserves a topic whose row-less marker was stamped before the abandoned TTL', async () => {
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: { runningOperation: { ...runningOperation, startedAt: longAgo.toISOString() } },
+ userId,
+ });
+
+ await expectReserved();
+ });
+
+ it('reserves a topic whose row-less marker carries no start stamp', async () => {
+ const { startedAt: _startedAt, ...unstamped } = runningOperation;
+ await serverDB
+ .insert(topics)
+ .values({ id: topicId, metadata: { runningOperation: unstamped }, userId });
+
+ await expectReserved();
+ });
+});
+
+describe('TopicModel task-callback guards', () => {
+ const repair = (
+ overrides: Partial<Parameters<TopicModel['repairAgentInterventionContinuation']>[0]>,
+ ) =>
+ topicModel.repairAgentInterventionContinuation({
+ active: true,
+ assistantMessageId: 'msg-continuation',
+ continuationOperationId: 'op-continuation',
+ reservationId: 'reservation-1',
+ sourceOperationId: 'op-source',
+ startedAt: '2026-10-01T00:00:00.000Z',
+ topicId,
+ ...overrides,
+ });
+
+ it('reports a conflict for a topic the caller cannot see', async () => {
+ await serverDB.insert(topics).values({ id: topicId, metadata: {}, userId: otherUserId });
+
+ expect(await repair({})).toBe('conflict');
+ expect(await readMetadata()).toEqual({});
+ });
+
+ it('keeps the continuation marker’s own fields when it already owns the topic', async () => {
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg-stale',
+ deviceId: 'device-1',
+ operationId: 'op-continuation',
+ },
+ },
+ userId,
+ });
+
+ expect(await repair({ scope: null, threadId: null })).toBe('repaired');
+ expect(await readMetadata()).toEqual({
+ runningOperation: {
+ assistantMessageId: 'msg-continuation',
+ deviceId: 'device-1',
+ heteroType: null,
+ operationId: 'op-continuation',
+ startedAt: '2026-10-01T00:00:00.000Z',
+ },
+ taskCallbackReservation: null,
+ });
+ });
+
+ it('releases its own reservation but keeps a foreign marker on conflict', async () => {
+ const runningOperation = { assistantMessageId: 'msg-other', operationId: 'op-other' };
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: {
+ runningOperation,
+ taskCallbackReservation: {
+ messageId: 'reservation-1',
+ reservedAt: new Date().toISOString(),
+ },
+ },
+ userId,
+ });
+
+ expect(await repair({})).toBe('conflict');
+ expect(await readMetadata()).toEqual({ runningOperation, taskCallbackReservation: null });
+ });
+
+ it('writes nothing on conflict when it holds no reservation', async () => {
+ const runningOperation = { assistantMessageId: 'msg-other', operationId: 'op-other' };
+ await serverDB.insert(topics).values({ id: topicId, metadata: { runningOperation }, userId });
+
+ expect(await repair({})).toBe('conflict');
+ expect(await readMetadata()).toEqual({ runningOperation });
+ });
+
+ it('clears the marker for a terminal repair on an idle topic without a reservation', async () => {
+ await serverDB.insert(topics).values({ id: topicId, metadata: {}, userId });
+
+ expect(await repair({ active: false })).toBe('terminal');
+ expect(await readMetadata()).toEqual({ runningOperation: null, taskCallbackReservation: null });
+ });
+
+ it('reports an absent reservation when there is nothing to release', async () => {
+ await serverDB.insert(topics).values({ id: topicId, metadata: {}, userId });
+
+ expect(await topicModel.releaseTaskCallbackReservation(topicId, 'reservation-1')).toBe(
+ 'absent',
+ );
+ expect(await topicModel.releaseTaskCallbackReservation('missing-topic', 'reservation-1')).toBe(
+ 'absent',
+ );
+ });
+});
+
+describe('TopicModel scheduled-run guards', () => {
+ const rateLimitRun = {
+ kind: 'resume_after_rate_limit',
+ runAt: '2026-10-01T00:00:00.000Z',
+ } as const;
+
+ it('reports a running topic as busy instead of cancelling its continuation', async () => {
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: { scheduledRun: rateLimitRun } as never,
+ status: 'running',
+ userId,
+ });
+
+ expect(await topicModel.cancelRateLimitContinuation(topicId)).toEqual({ status: 'busy' });
+ expect(await readStatus()).toBe('running');
+ expect((await readMetadata())?.scheduledRun).toEqual(rateLimitRun);
+ });
+
+ it('does not arm a schedule on another user’s topic', async () => {
+ await serverDB
+ .insert(topics)
+ .values({ id: otherTopicId, metadata: {}, status: 'active', userId: otherUserId });
+
+ await topicModel.armScheduledRun(otherTopicId, rateLimitRun as never);
+
+ expect(await readStatus(otherTopicId)).toBe('active');
+ expect(await readMetadata(otherTopicId)).toEqual({});
+ });
+
+ it('will not claim a scheduled topic that carries no scheduled run', async () => {
+ await serverDB
+ .insert(topics)
+ .values({ id: topicId, metadata: {}, status: 'scheduled', userId });
+
+ const claimed = await TopicModel.claimScheduledTopic(serverDB, topicId, {
+ claimedAt: '2026-10-01T00:00:00.000Z',
+ expiresAt: '2026-10-01T00:05:00.000Z',
+ id: 'claim-1',
+ });
+
+ expect(claimed).toBe(false);
+ expect(await readMetadata()).toEqual({});
+ });
+
+ it('leaves a topic that is no longer scheduled when clearing its run', async () => {
+ await serverDB.insert(topics).values({
+ id: topicId,
+ metadata: { scheduledRun: rateLimitRun } as never,
+ status: 'running',
+ userId,
+ });
+
+ await TopicModel.clearScheduledRun(serverDB, topicId);
+ await TopicModel.clearScheduledRun(serverDB, 'missing-topic');
+
+ expect(await readStatus()).toBe('running');
+ expect((await readMetadata())?.scheduledRun).toEqual(rateLimitRun);
+ });
+
+ it('does not repoint a scheduled topic whose run was already cleared', async () => {
+ await serverDB
+ .insert(topics)
+ .values({ id: topicId, metadata: {}, status: 'scheduled', userId });
+
+ await TopicModel.repointScheduledRunFailedMessage(serverDB, topicId, 'msg-failed', 'claim-1');
+
+ expect(await readMetadata()).toEqual({});
+ });
+});
diff --git a/packages/database/src/models/__tests__/topics/topic.scopeGuards.test.ts b/packages/database/src/models/__tests__/topics/topic.scopeGuards.test.ts
new file mode 100644
index 00000000000..8bb6cb427b7
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.scopeGuards.test.ts
@@ -0,0 +1,300 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agents,
+ chatGroups,
+ documents,
+ sessions,
+ topicDocuments,
+ topics,
+ users,
+ workspaces,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+import { createTopicModelContext } from '../../topic/context';
+import { createProxyTestDB } from '../_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'topic-scope-guards-user';
+const teammateId = 'topic-scope-guards-teammate';
+const workspaceId = 'topic-scope-guards-workspace';
+const agentId = 'topic-scope-guards-agent';
+const sessionId = 'topic-scope-guards-session';
+const groupId = 'topic-scope-guards-group';
+
+const topicModel = new TopicModel(serverDB, userId);
+const deletedAt = new Date('2026-10-01T00:00:00.000Z');
+
+/** Every query comes back without rows — the shape an aggregate never returns on its own. */
+const noRowsDB = () => createProxyTestDB(serverDB, () => []);
+
+const liveTopicIds = async (ids: string[]) => {
+ const rows = await serverDB
+ .select({ deletedAt: topics.deletedAt, id: topics.id })
+ .from(topics)
+ .where(inArray(topics.id, ids));
+ return rows
+ .filter((row) => row.deletedAt === null)
+ .map((row) => row.id)
+ .sort();
+};
+
+beforeEach(async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(users).values([{ id: userId }, { id: teammateId }]);
+ await tx.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Topic Scope Guards',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await tx.insert(agents).values({ id: agentId, userId });
+ await tx.insert(sessions).values({ id: sessionId, userId });
+ await tx.insert(chatGroups).values({ id: groupId, userId });
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ // Topics, agents, sessions, groups and documents cascade with their owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId, teammateId]));
+});
+
+describe('TopicModel lookup guards', () => {
+ it('scopes a keyword search to a group before any agent or container', async () => {
+ await serverDB.insert(topics).values([
+ { agentId, groupId, id: 'kw-group', userId },
+ { agentId, id: 'kw-agent', userId },
+ ]);
+ const ctx = createTopicModelContext({ db: serverDB, includeShareVisitor: false, userId });
+
+ const rows = await serverDB
+ .select({ id: topics.id })
+ .from(topics)
+ .where(ctx.matchKeywordScope({ agentId, groupId }));
+
+ expect(rows.map((row) => row.id)).toEqual(['kw-group']);
+ });
+
+ it('answers empty id lists and blank keywords without a query', async () => {
+ await serverDB.insert(topics).values({ id: 'empty-guard', senderId: 'visitor-1', userId });
+
+ expect(await topicModel.findShareVisitorTopicIds([])).toEqual([]);
+ expect(await topicModel.findByIds([])).toEqual([]);
+ expect(await topicModel.queryByKeyword(' ')).toEqual([]);
+ });
+
+ it('finds the topic an agent shares with a document for one trigger only', async () => {
+ await serverDB.insert(documents).values({
+ fileType: 'custom/document',
+ id: 'doc-scope-guards',
+ source: 'doc-scope-guards',
+ sourceType: 'api',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId,
+ });
+ await serverDB
+ .insert(topics)
+ .values({ agentId, id: 'doc-topic', trigger: 'document-chat', userId });
+ await serverDB
+ .insert(topicDocuments)
+ .values({ documentId: 'doc-scope-guards', topicId: 'doc-topic', userId });
+
+ const params = { agentId, documentId: 'doc-scope-guards', trigger: 'document-chat' };
+
+ expect((await topicModel.findByAgentAndDocumentTrigger(params))?.id).toBe('doc-topic');
+ expect(
+ await topicModel.findByAgentAndDocumentTrigger({ ...params, trigger: 'other' }),
+ ).toBeUndefined();
+ expect(
+ await new TopicModel(serverDB, teammateId).findByAgentAndDocumentTrigger(params),
+ ).toBeUndefined();
+ });
+
+ it('counts only the topics in the requested container', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'count-session', sessionId, userId },
+ { id: 'count-group', groupId, userId },
+ { id: 'count-loose', userId },
+ ]);
+
+ expect(await topicModel.count({ containerId: sessionId })).toBe(1);
+ expect(await topicModel.count({ containerId: groupId })).toBe(1);
+ });
+
+ it('skips a cron topic whose job id is not a usable string', async () => {
+ await serverDB.insert(topics).values([
+ {
+ agentId,
+ id: 'cron-valid',
+ metadata: { cronJobId: 'job-1' } as never,
+ trigger: 'cron',
+ userId,
+ },
+ // `->> 'cronJobId'` renders the number as '0', so SQL keeps the row and
+ // only the in-memory guard drops it.
+ { agentId, id: 'cron-numeric', metadata: { cronJobId: 0 } as never, trigger: 'cron', userId },
+ ]);
+
+ const groups = await topicModel.getCronTopicsGroupedByCronJob(agentId);
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0].cronJobId).toBe('job-1');
+ expect(groups[0].topics.map((topic) => topic.id)).toEqual(['cron-valid']);
+ });
+
+ it('adopts legacy rows of the agent’s old session in the agent list', async () => {
+ await serverDB.insert(topics).values([
+ { agentId, id: 'list-agent', userId },
+ { id: 'list-legacy', sessionId, userId },
+ { id: 'list-unrelated', userId },
+ ]);
+
+ const result = await topicModel.query({ agentId, legacySessionId: sessionId });
+
+ expect(result.items.map((topic) => topic.id).sort()).toEqual(['list-agent', 'list-legacy']);
+ });
+});
+
+describe('TopicModel memory-extractor date windows', () => {
+ beforeEach(async () => {
+ await serverDB.insert(topics).values([
+ { createdAt: new Date('2026-01-01'), id: 'mem-jan', userId },
+ { createdAt: new Date('2026-02-01'), id: 'mem-feb', userId },
+ { createdAt: new Date('2026-03-01'), id: 'mem-mar', userId },
+ ]);
+ });
+
+ const window = { endDate: new Date('2026-02-15'), startDate: new Date('2026-01-15') };
+
+ it('lists only topics created inside the window', async () => {
+ const rows = await topicModel.listTopicsForMemoryExtractor(window);
+
+ expect(rows.map((row) => row.id)).toEqual(['mem-feb']);
+ });
+
+ it('counts only topics created inside the window', async () => {
+ expect(await topicModel.countTopicsForMemoryExtractor(window)).toBe(1);
+ });
+
+ it('counts zero when the driver returns no aggregate row', async () => {
+ expect(await new TopicModel(noRowsDB(), userId).countTopicsForMemoryExtractor()).toBe(0);
+ });
+});
+
+describe('TopicModel share-visitor roll-up', () => {
+ it('reports zero visitors when the driver returns no aggregate row', async () => {
+ const result = await new TopicModel(noRowsDB(), userId).countShareVisitors({ agentId });
+
+ expect(result).toEqual({ topicCount: 0, visitorCount: 0 });
+ });
+});
+
+describe('TopicModel trash scoping', () => {
+ const memberModel = new TopicModel(serverDB, userId, workspaceId);
+ const restrict = { deletedAt, restrictToCreator: true };
+
+ it('trashes only the caller’s own workspace topics by id when restricted to creator', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'ws-mine', userId, workspaceId },
+ { id: 'ws-teammate', userId: teammateId, workspaceId },
+ ]);
+
+ const trashed = await memberModel.softDelete(['ws-mine', 'ws-teammate'], restrict);
+
+ expect(trashed.map((topic) => topic.id)).toEqual(['ws-mine']);
+ expect(await liveTopicIds(['ws-mine', 'ws-teammate'])).toEqual(['ws-teammate']);
+ });
+
+ it('trashes only the caller’s own topics of a session or group when restricted', async () => {
+ await serverDB.insert(topics).values([
+ { id: 'ws-session-mine', sessionId, userId, workspaceId },
+ { id: 'ws-session-teammate', sessionId, userId: teammateId, workspaceId },
+ { groupId, id: 'ws-group-mine', userId, workspaceId },
+ { groupId, id: 'ws-group-teammate', userId: teammateId, workspaceId },
+ ]);
+
+ const bySession = await memberModel.softDeleteBySessionId(sessionId, restrict);
+ const byGroup = await memberModel.softDeleteByGroupId(groupId, restrict);
+
+ expect(bySession.map((topic) => topic.id)).toEqual(['ws-session-mine']);
+ expect(byGroup.map((topic) => topic.id)).toEqual(['ws-group-mine']);
+ expect(
+ await liveTopicIds([
+ 'ws-session-mine',
+ 'ws-session-teammate',
+ 'ws-group-mine',
+ 'ws-group-teammate',
+ ]),
+ ).toEqual(['ws-group-teammate', 'ws-session-teammate']);
+ });
+
+ it('trashes an agent’s topics plus its legacy session rows across the workspace', async () => {
+ await serverDB.insert(topics).values([
+ { agentId, id: 'agent-teammate', userId: teammateId, workspaceId },
+ { id: 'agent-legacy', sessionId, userId, workspaceId },
+ { id: 'agent-unrelated', userId, workspaceId },
+ ]);
+
+ const trashed = await memberModel.softDeleteByAgentId(agentId, {
+ deletedAt,
+ legacySessionId: sessionId,
+ });
+
+ expect(trashed.map((topic) => topic.id).sort()).toEqual(['agent-legacy', 'agent-teammate']);
+ expect(await liveTopicIds(['agent-unrelated'])).toEqual(['agent-unrelated']);
+ });
+
+ it('trashes only the caller’s own topics under an agent parent when restricted', async () => {
+ await serverDB.insert(topics).values([
+ { agentId, id: 'parent-mine', userId, workspaceId },
+ { agentId, id: 'parent-teammate', userId: teammateId, workspaceId },
+ ]);
+
+ const trashed = await memberModel.softDeleteByParents({ agentIds: [agentId] }, restrict);
+
+ expect(trashed.map((topic) => topic.id)).toEqual(['parent-mine']);
+ expect(await liveTopicIds(['parent-mine', 'parent-teammate'])).toEqual(['parent-teammate']);
+ });
+});
+
+describe('TopicModel model-pin guards', () => {
+ it('returns nothing for a topic the caller cannot see', async () => {
+ await serverDB.insert(topics).values({ id: 'pin-foreign', model: 'old', userId: teammateId });
+
+ expect(
+ await topicModel.updateModelPin('pin-foreign', { model: 'new', provider: 'openai' }),
+ ).toEqual([]);
+ const row = await serverDB.query.topics.findFirst({
+ where: (t, { eq }) => eq(t.id, 'pin-foreign'),
+ });
+ expect(row?.model).toBe('old');
+ });
+
+ it('pins hetero effort and speed with the new model and drops the old reasoning pin', async () => {
+ await serverDB.insert(topics).values({
+ id: 'pin-hetero',
+ metadata: { boundDeviceId: 'device-1', reasoningConfig: { effort: 'high' } as never },
+ userId,
+ });
+
+ const [updated] = await topicModel.updateModelPin('pin-hetero', {
+ metadata: { heteroEffort: 'low' as never, heteroSpeed: 'fast' },
+ model: 'new-model',
+ provider: 'openai',
+ });
+
+ expect(updated.model).toBe('new-model');
+ expect(updated.metadata).toEqual({
+ boundDeviceId: 'device-1',
+ heteroEffort: 'low',
+ heteroSpeed: 'fast',
+ });
+ });
+});
diff --git a/packages/database/src/models/topic/find.ts b/packages/database/src/models/topic/find.ts
index 51e25a31a4b..f7355e3fd74 100644
--- a/packages/database/src/models/topic/find.ts
+++ b/packages/database/src/models/topic/find.ts
@@ -177,6 +177,7 @@ 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]] : [])));
};
@@ -430,7 +431,9 @@ export const queryRecent = async (ctx: TopicModelContext, limit: number = 12) =>
return result.map((item) => ({
...item,
type: item.groupId ? ('group' as const) : ('agent' as const),
+ /* v8 ignore start -- unreachable: the `new Date(…)` arm; `mapWith(topics.updatedAt)` decodes the timestamptz cell into a Date, whichever driver returns it */
updatedAt: item.updatedAt instanceof Date ? item.updatedAt : new Date(item.updatedAt),
+ /* v8 ignore stop */
}));
};
diff --git a/packages/database/src/models/topic/runningOperation.ts b/packages/database/src/models/topic/runningOperation.ts
index 41bfb82aa8f..0e28bce8a67 100644
--- a/packages/database/src/models/topic/runningOperation.ts
+++ b/packages/database/src/models/topic/runningOperation.ts
@@ -437,6 +437,8 @@ 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;
};
diff --git a/packages/database/src/models/topic/taskCallback.ts b/packages/database/src/models/topic/taskCallback.ts
index 3cc4f4827c1..6748a627953 100644
--- a/packages/database/src/models/topic/taskCallback.ts
+++ b/packages/database/src/models/topic/taskCallback.ts
@@ -188,7 +188,9 @@ export const repairAgentInterventionContinuation = async (
metadata: {
...existing.metadata,
runningOperation,
+ /* v8 ignore start -- unreachable: the `{}` arm; a live reservation this caller does not own already returned 'conflict' above */
...(ownsReservation || !hasLiveReservation ? { taskCallbackReservation: null } : {}),
+ /* v8 ignore stop */
},
updatedAt: new Date(),
})