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): cover models added to canary after the coverage baseline (#21859)

Arvin Xue31ea5a4981e
diff --git a/packages/database/src/models/__tests__/generationBatch.test.ts b/packages/database/src/models/__tests__/generationBatch.test.ts
index ed4e072ab10..b9f5edd198b 100644
--- a/packages/database/src/models/__tests__/generationBatch.test.ts
+++ b/packages/database/src/models/__tests__/generationBatch.test.ts
@@ -412,7 +412,7 @@ describe('GenerationBatchModel', () => {
});
it('should transform config imageUrls through FileService', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -431,7 +431,7 @@ describe('GenerationBatchModel', () => {
});
it('should transform single config imageUrl through FileService', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -451,7 +451,7 @@ describe('GenerationBatchModel', () => {
});
it('should transform both imageUrl and imageUrls when both are present', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -476,7 +476,7 @@ describe('GenerationBatchModel', () => {
});
it('should transform config endImageUrl through FileService', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -497,7 +497,7 @@ describe('GenerationBatchModel', () => {
});
it('should transform config with both imageUrl and endImageUrl through FileService', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -524,7 +524,7 @@ describe('GenerationBatchModel', () => {
});
it('should handle config without imageUrls', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -783,7 +783,7 @@ describe('GenerationBatchModel', () => {
describe('External service integration', () => {
it('should call FileService with correct parameters', async () => {
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
@@ -818,7 +818,7 @@ describe('GenerationBatchModel', () => {
it('should handle FileService errors gracefully', async () => {
mockGetFullFileUrl.mockRejectedValue(new Error('FileService error'));
- const [createdBatch] = await serverDB
+ await serverDB
.insert(generationBatches)
.values({
...testBatch,
diff --git a/packages/database/src/models/__tests__/messages/message.cursor-query.noRoundStart.test.ts b/packages/database/src/models/__tests__/messages/message.cursor-query.noRoundStart.test.ts
new file mode 100644
index 00000000000..eab4e0c87e5
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.cursor-query.noRoundStart.test.ts
@@ -0,0 +1,78 @@
+// MessageModel.queryTopicMessagesByCursor when no round start exists at all:
+// the oversized-round lookup finds no user message to extend to, so the page
+// falls back to the oldest fetched row.
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messages, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'cursor-no-round-start-test';
+const messageModel = new MessageModel(serverDB, userId);
+
+/** `count` chained mainline rows, oldest first, none of them a round start. */
+const seedWithoutRoundStart = async (topicId: string, count: number, steerUser = false) => {
+ await serverDB.insert(topics).values({ id: topicId, userId });
+ const ids = Array.from({ length: count }, (_, i) => `${topicId}-m${i + 1}`);
+ await serverDB.insert(messages).values(
+ ids.map((id, i) => ({
+ content: `m${i + 1}`,
+ createdAt: new Date(2023, 0, 1, 0, i),
+ id,
+ // A steered user message continues a turn instead of starting one.
+ metadata: steerUser && i === 0 ? { steer: true } : undefined,
+ parentId: i === 0 ? null : ids[i - 1],
+ role: steerUser && i === 0 ? 'user' : 'assistant',
+ topicId,
+ userId,
+ })),
+ );
+ return ids;
+};
+
+beforeEach(async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.delete(users).where(eq(users.id, userId));
+ await trx.insert(users).values([{ id: userId }]);
+ });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+describe('MessageModel.queryTopicMessagesByCursor without a round start', () => {
+ it('falls back to the oldest fetched row when the budget is exceeded', async () => {
+ const topicId = 't-cursor-no-round-start';
+ const ids = await seedWithoutRoundStart(topicId, 6);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ countBudget: 3,
+ roundLimit: 1000,
+ topicId,
+ });
+
+ // countBudget + 1 rows are fetched; the oldest of them bounds the page.
+ expect(page.messages.map((m) => m.id)).toEqual(ids.slice(2));
+ expect(page.hasMore).toBe(true);
+ expect(page.nextCursor).toEqual({ createdAt: expect.any(String), id: ids[2] });
+ });
+
+ it('does not treat a steered user message as a round start', async () => {
+ const topicId = 't-cursor-no-round-start-steer';
+ const ids = await seedWithoutRoundStart(topicId, 5, true);
+
+ const page = await messageModel.queryTopicMessagesByCursor({
+ countBudget: 2,
+ roundLimit: 1000,
+ topicId,
+ });
+
+ expect(page.messages.map((m) => m.id)).toEqual(ids.slice(2));
+ expect(page.hasMore).toBe(true);
+ });
+});
diff --git a/packages/database/src/models/__tests__/taskExternalLink.coverage.test.ts b/packages/database/src/models/__tests__/taskExternalLink.coverage.test.ts
new file mode 100644
index 00000000000..1fde23d435b
--- /dev/null
+++ b/packages/database/src/models/__tests__/taskExternalLink.coverage.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+import { TaskExternalLinkModel } from '../taskExternalLink';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-ext-link-cov-user';
+const otherUserId = 'task-ext-link-cov-other';
+const workspaceId = 'task-ext-link-cov-ws';
+
+const link = (taskId: string, externalId = 'issue-cov-1') => ({
+ externalContainerId: 'team-cov',
+ externalId,
+ externalIdentifier: 'ENG-1',
+ externalUrl: 'https://linear.app/acme/issue/ENG-1',
+ provider: 'linear' as const,
+ syncedHash: 'hash-1',
+ taskId,
+});
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ // Tasks and links cascade with their owner and workspace.
+ await db.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('TaskExternalLinkModel coverage', () => {
+ it('returns no links for an empty id list without querying', async () => {
+ const model = new TaskExternalLinkModel(db, userId);
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ await model.create(link(task.id));
+
+ expect(await model.findByExternalIds('linear', [])).toEqual([]);
+ });
+
+ it('finds the link of a task only inside its own scope', async () => {
+ const personal = new TaskExternalLinkModel(db, userId);
+ const shared = new TaskExternalLinkModel(db, userId, workspaceId);
+ const personalTask = await new TaskModel(db, userId).create({ instruction: 'mine' });
+ const sharedTask = await new TaskModel(db, userId, workspaceId).create({
+ instruction: 'ours',
+ });
+ const mine = await personal.create(link(personalTask.id));
+ const ours = await shared.create(link(sharedTask.id));
+
+ expect(await personal.findByTaskId(personalTask.id)).toMatchObject({
+ id: mine.id,
+ workspaceId: null,
+ });
+ expect(await shared.findByTaskId(sharedTask.id)).toMatchObject({ id: ours.id, workspaceId });
+ // The personal scope never sees a workspace link, and the reverse.
+ expect(await personal.findByTaskId(sharedTask.id)).toBeNull();
+ expect(await shared.findByTaskId(personalTask.id)).toBeNull();
+ expect(
+ await new TaskExternalLinkModel(db, otherUserId).findByTaskId(personalTask.id),
+ ).toBeNull();
+ });
+
+ it('updates a link in scope and stamps the sync time', async () => {
+ const model = new TaskExternalLinkModel(db, userId);
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ const lastSyncedAt = new Date('2026-01-01T00:00:00.000Z');
+ const created = await model.create({ ...link(task.id), lastSyncedAt });
+ const externalUpdatedAt = new Date('2026-01-02T03:04:05.000Z');
+
+ await model.update(created.id, {
+ externalIdentifier: 'ENG-2',
+ externalUpdatedAt,
+ syncedHash: 'hash-2',
+ });
+
+ const updated = await model.findByTaskId(task.id);
+ expect(updated).toMatchObject({
+ externalIdentifier: 'ENG-2',
+ externalUpdatedAt,
+ id: created.id,
+ syncedHash: 'hash-2',
+ });
+ expect(updated!.lastSyncedAt.getTime()).toBeGreaterThan(lastSyncedAt.getTime());
+ });
+
+ it('leaves a link outside the caller scope untouched on update', async () => {
+ const personal = new TaskExternalLinkModel(db, userId);
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ const created = await personal.create(link(task.id));
+
+ await new TaskExternalLinkModel(db, otherUserId).update(created.id, { syncedHash: 'other' });
+ await new TaskExternalLinkModel(db, userId, workspaceId).update(created.id, {
+ syncedHash: 'ws',
+ });
+
+ expect(await personal.findByTaskId(task.id)).toMatchObject({
+ lastSyncedAt: created.lastSyncedAt,
+ syncedHash: 'hash-1',
+ });
+ });
+});
diff --git a/packages/database/src/models/linear/__tests__/connection.coverage.test.ts b/packages/database/src/models/linear/__tests__/connection.coverage.test.ts
index 38343771575..f0a0a125cda 100644
--- a/packages/database/src/models/linear/__tests__/connection.coverage.test.ts
+++ b/packages/database/src/models/linear/__tests__/connection.coverage.test.ts
@@ -75,4 +75,53 @@ describe('LinearConnectionModel coverage', () => {
const decrypted = await LinearConnectionModel.findDecryptedById(db, row.id);
expect(decrypted).toMatchObject({ credentials: null, id: row.id });
});
+
+ it('replaces the token and its expiry after a refresh', async () => {
+ const row = await LinearConnectionModel.upsert(
+ db,
+ { ...organization, credentials: { accessToken: 'old' }, userId },
+ gateKeeper,
+ );
+ const tokenExpiresAt = new Date('2026-06-01T00:00:00.000Z');
+
+ await LinearConnectionModel.updateCredentials(
+ db,
+ row.id,
+ { credentials: { accessToken: 'new' }, tokenExpiresAt },
+ gateKeeper,
+ );
+ expect(await LinearConnectionModel.findDecryptedById(db, row.id, gateKeeper)).toMatchObject({
+ credentials: { accessToken: 'new' },
+ tokenExpiresAt,
+ });
+
+ // Without an expiry the refreshed token never expires; no gate keeper stores plain JSON.
+ await LinearConnectionModel.updateCredentials(db, row.id, {
+ credentials: { accessToken: 'plain' },
+ });
+ expect(await LinearConnectionModel.findById(db, row.id)).toMatchObject({
+ credentials: '{"accessToken":"plain"}',
+ tokenExpiresAt: null,
+ });
+ });
+
+ it('keeps a revoked connection revoked when a refresh lands late', async () => {
+ const row = await LinearConnectionModel.upsert(
+ db,
+ { ...organization, credentials: { accessToken: 'a' }, userId },
+ gateKeeper,
+ );
+ await LinearConnectionModel.revoke(db, row.id);
+
+ await LinearConnectionModel.updateCredentials(
+ db,
+ row.id,
+ { credentials: { accessToken: 'late' } },
+ gateKeeper,
+ );
+
+ const decrypted = await LinearConnectionModel.findDecryptedById(db, row.id, gateKeeper);
+ expect(decrypted).toMatchObject({ credentials: null, id: row.id });
+ expect(decrypted?.revokedAt).toBeInstanceOf(Date);
+ });
});
diff --git a/packages/database/src/models/linear/__tests__/syncJob.coverage.test.ts b/packages/database/src/models/linear/__tests__/syncJob.coverage.test.ts
new file mode 100644
index 00000000000..f5b28c39049
--- /dev/null
+++ b/packages/database/src/models/linear/__tests__/syncJob.coverage.test.ts
@@ -0,0 +1,138 @@
+// @vitest-environment node
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { asyncTasks, users, workspaces } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { LinearSyncJobModel } from '../syncJob';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'linear-job-cov-user';
+const otherUserId = 'linear-job-cov-other';
+const workspaceId = 'linear-job-cov-ws';
+const projectId = 'linear-job-cov-project';
+
+const personal = { userId };
+const shared = { userId, workspaceId };
+
+const job = async (
+ overrides: Partial<typeof asyncTasks.$inferInsert> & { ruleId?: string } = {},
+) => {
+ const { ruleId, ...values } = overrides;
+ const [row] = await db
+ .insert(asyncTasks)
+ .values({
+ metadata: { connectionId: 'conn', kind: ruleId ? 'rule' : 'issues', projectId, ruleId },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.LinearIssueSync,
+ userId,
+ ...values,
+ })
+ .returning();
+ return row;
+};
+
+const statusOf = async (id: string) => {
+ const [row] = await db.select().from(asyncTasks).where(eq(asyncTasks.id, id));
+ return row;
+};
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ // Async tasks cascade with their owner and workspace.
+ await db.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('LinearSyncJobModel coverage', () => {
+ it('lists a project sync jobs newest first, scoped and limited', async () => {
+ const older = await job({ createdAt: new Date('2026-01-01T00:00:00.000Z') });
+ const newer = await job({ createdAt: new Date('2026-01-02T00:00:00.000Z') });
+ // Not a Linear sync, another project, and a workspace job: never listed for personal.
+ await job({ type: AsyncTaskType.Chunking });
+ await job({ metadata: { connectionId: 'conn', kind: 'issues', projectId: 'other' } });
+ const wsJob = await job({ workspaceId });
+
+ expect(
+ (await LinearSyncJobModel.listByProject(db, personal, projectId)).map((r) => r.id),
+ ).toEqual([newer.id, older.id]);
+ expect(
+ (await LinearSyncJobModel.listByProject(db, personal, projectId, 1)).map((r) => r.id),
+ ).toEqual([newer.id]);
+ expect(
+ (await LinearSyncJobModel.listByProject(db, shared, projectId)).map((r) => r.id),
+ ).toEqual([wsJob.id]);
+ expect(await LinearSyncJobModel.listByProject(db, { userId: otherUserId }, projectId)).toEqual(
+ [],
+ );
+ });
+
+ it('lets only one caller claim a queued job', async () => {
+ const queued = await job();
+
+ expect(await LinearSyncJobModel.claim(db, { userId: otherUserId }, queued.id)).toBeNull();
+ expect(await LinearSyncJobModel.claim(db, shared, queued.id)).toBeNull();
+
+ const claimed = await LinearSyncJobModel.claim(db, personal, queued.id);
+ expect(claimed).toMatchObject({ id: queued.id, status: AsyncTaskStatus.Processing });
+ expect(await LinearSyncJobModel.claim(db, personal, queued.id)).toBeNull();
+ });
+
+ it('claims a queued workspace job from the workspace scope', async () => {
+ const queued = await job({ workspaceId });
+
+ expect(await LinearSyncJobModel.claim(db, personal, queued.id)).toBeNull();
+ expect(await LinearSyncJobModel.claim(db, shared, queued.id)).toMatchObject({
+ id: queued.id,
+ status: AsyncTaskStatus.Processing,
+ });
+ });
+
+ it('touches only a running job in scope', async () => {
+ const stale = new Date('2026-01-01T00:00:00.000Z');
+ const running = await job({ status: AsyncTaskStatus.Processing, updatedAt: stale });
+ const finished = await job({ status: AsyncTaskStatus.Success, updatedAt: stale });
+ const wsRunning = await job({
+ status: AsyncTaskStatus.Processing,
+ updatedAt: stale,
+ workspaceId,
+ });
+
+ await LinearSyncJobModel.touch(db, personal, running.id);
+ await LinearSyncJobModel.touch(db, personal, finished.id);
+ await LinearSyncJobModel.touch(db, personal, wsRunning.id);
+ await LinearSyncJobModel.touch(db, { userId: otherUserId }, running.id);
+
+ expect((await statusOf(running.id)).updatedAt.getTime()).toBeGreaterThan(stale.getTime());
+ expect((await statusOf(finished.id)).updatedAt).toEqual(stale);
+ expect((await statusOf(wsRunning.id)).updatedAt).toEqual(stale);
+
+ await LinearSyncJobModel.touch(db, shared, wsRunning.id);
+ expect((await statusOf(wsRunning.id)).updatedAt.getTime()).toBeGreaterThan(stale.getTime());
+ });
+
+ it('finds the unfinished run of a rule', async () => {
+ const ruleId = 'linear-job-cov-rule';
+ await job({ ruleId, status: AsyncTaskStatus.Success });
+
+ expect(await LinearSyncJobModel.findActiveForRule(db, personal, projectId, ruleId)).toBeNull();
+
+ const active = await job({ ruleId, status: AsyncTaskStatus.Processing });
+ expect(
+ await LinearSyncJobModel.findActiveForRule(db, personal, projectId, ruleId),
+ ).toMatchObject({ id: active.id, metadata: { ruleId } });
+ expect(
+ await LinearSyncJobModel.findActiveForRule(db, personal, projectId, 'another-rule'),
+ ).toBeNull();
+ expect(await LinearSyncJobModel.findActiveForRule(db, shared, projectId, ruleId)).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/linear/__tests__/syncRule.coverage.test.ts b/packages/database/src/models/linear/__tests__/syncRule.coverage.test.ts
new file mode 100644
index 00000000000..52fd6a000e2
--- /dev/null
+++ b/packages/database/src/models/linear/__tests__/syncRule.coverage.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { projects, users, workspaces } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { LinearConnectionModel } from '../connection';
+import { LinearSyncRuleModel } from '../syncRule';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'linear-rule-cov-user';
+const otherUserId = 'linear-rule-cov-other';
+const workspaceId = 'linear-rule-cov-ws';
+const projectId = 'linear-rule-cov-project';
+const wsProjectId = 'linear-rule-cov-ws-project';
+
+const personal = { userId };
+const shared = { userId, workspaceId };
+
+const result = {
+ closed: 0,
+ created: 2,
+ keptLocalEdits: 0,
+ skipped: [],
+ truncated: false,
+ unchanged: 1,
+ updated: 0,
+};
+
+let connectionId: string;
+
+const rule = (overrides: Partial<Parameters<typeof LinearSyncRuleModel.create>[1]> = {}) =>
+ LinearSyncRuleModel.create(db, {
+ connectionId,
+ projectId,
+ stateTypes: ['backlog', 'started'],
+ teamId: 'team-cov',
+ teamName: 'Engineering',
+ userId,
+ ...overrides,
+ });
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await db.insert(projects).values([
+ { id: projectId, name: 'Personal', userId },
+ { id: wsProjectId, name: 'Shared', userId, workspaceId },
+ ]);
+ const connection = await LinearConnectionModel.upsert(db, {
+ actorExternalId: 'linear-rule-cov-actor',
+ actorName: 'Ada',
+ credentials: { accessToken: 'token' },
+ organizationId: 'linear-rule-cov-org',
+ organizationName: 'Acme',
+ organizationUrlKey: 'acme-rule-cov',
+ userId,
+ });
+ connectionId = connection.id;
+});
+
+afterEach(async () => {
+ // Projects, connections and rules cascade with their owner and workspace.
+ await db.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('LinearSyncRuleModel coverage', () => {
+ it('lists a project rules newest first, per scope', async () => {
+ const older = await rule({ createdAt: new Date('2026-01-01T00:00:00.000Z') });
+ const newer = await rule({ createdAt: new Date('2026-01-02T00:00:00.000Z') });
+ const wsRule = await rule({ projectId: wsProjectId, workspaceId });
+
+ expect(
+ (await LinearSyncRuleModel.listByProject(db, personal, projectId)).map((r) => r.id),
+ ).toEqual([newer.id, older.id]);
+ expect(
+ (await LinearSyncRuleModel.listByProject(db, shared, wsProjectId)).map((r) => r.id),
+ ).toEqual([wsRule.id]);
+ // A workspace scope never lists personal rules, and another user sees none.
+ expect(await LinearSyncRuleModel.listByProject(db, shared, projectId)).toEqual([]);
+ expect(await LinearSyncRuleModel.listByProject(db, { userId: otherUserId }, projectId)).toEqual(
+ [],
+ );
+ });
+
+ it('finds and locks a rule only inside its scope', async () => {
+ const created = await rule();
+ const missingId = '00000000-0000-4000-8000-000000000000';
+
+ expect(await LinearSyncRuleModel.findInScope(db, created.id, personal)).toMatchObject({
+ id: created.id,
+ });
+ expect(await LinearSyncRuleModel.findInScope(db, created.id, shared)).toBeNull();
+ expect(await LinearSyncRuleModel.findInScope(db, missingId, personal)).toBeNull();
+
+ const locked = await db.transaction((trx) =>
+ LinearSyncRuleModel.lockInScope(trx as unknown as LobeChatDatabase, created.id, personal),
+ );
+ expect(locked).toBe(true);
+ expect(
+ await db.transaction((trx) =>
+ LinearSyncRuleModel.lockInScope(trx as unknown as LobeChatDatabase, created.id, {
+ userId: otherUserId,
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it('records a run and exposes it through the view', async () => {
+ const created = await rule({ linearProjectId: 'lp-1', linearProjectName: 'Roadmap' });
+
+ expect(LinearSyncRuleModel.toView(created)).toMatchObject({
+ lastResult: null,
+ lastRunAt: null,
+ linearProjectId: 'lp-1',
+ linearProjectName: 'Roadmap',
+ });
+
+ // Another scope cannot record a run on this rule.
+ await LinearSyncRuleModel.recordRun(db, created.id, { userId: otherUserId }, result);
+ expect((await LinearSyncRuleModel.findInScope(db, created.id, personal))?.lastRunAt).toBeNull();
+
+ await LinearSyncRuleModel.recordRun(db, created.id, personal, result);
+ const row = await LinearSyncRuleModel.findInScope(db, created.id, personal);
+ const view = LinearSyncRuleModel.toView(row!);
+
+ expect(view).toEqual({
+ connectionId,
+ createdAt: row!.createdAt,
+ id: created.id,
+ lastResult: result,
+ lastRunAt: expect.any(Date),
+ linearProjectId: 'lp-1',
+ linearProjectName: 'Roadmap',
+ projectId,
+ stateTypes: ['backlog', 'started'],
+ teamId: 'team-cov',
+ teamName: 'Engineering',
+ });
+ });
+
+ it('deletes a rule only from its own scope', async () => {
+ const created = await rule();
+
+ await LinearSyncRuleModel.delete(db, created.id, shared);
+ expect(await LinearSyncRuleModel.findInScope(db, created.id, personal)).not.toBeNull();
+
+ await LinearSyncRuleModel.delete(db, created.id, personal);
+ expect(await LinearSyncRuleModel.findInScope(db, created.id, personal)).toBeNull();
+ });
+});