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/work (#21847)

Arvin Xua29710f84e85
diff --git a/packages/database/src/models/work/__tests__/shellCommandParsing.coverage.test.ts b/packages/database/src/models/work/__tests__/shellCommandParsing.coverage.test.ts
new file mode 100644
index 00000000000..7b544876021
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/shellCommandParsing.coverage.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseShellCommandSegments } from '../shellCommandParsing';
+
+describe('parseShellCommandSegments · heredoc operators', () => {
+ it('keeps a `<<<` here-string literal instead of reading it as a heredoc', () => {
+ expect(parseShellCommandSegments(`cat <<<"inline body"\ngh pr list`)).toEqual([
+ ['cat', '<<<inline body'],
+ ['gh', 'pr', 'list'],
+ ]);
+ });
+
+ it('strips leading tabs before matching a `<<-` delimiter', () => {
+ expect(
+ parseShellCommandSegments(`cat <<-EOF > notes.md\n\tit's prose\n\tEOF\ngh pr view 1`),
+ ).toEqual([
+ ['cat', '>', 'notes.md'],
+ ['gh', 'pr', 'view', '1'],
+ ]);
+ });
+
+ it('reads a quoted delimiter after spaces and drops its body', () => {
+ expect(
+ parseShellCommandSegments(`cat << 'EOF' > body.md\npanel's copy\nEOF\ngh pr create`),
+ ).toEqual([
+ ['cat', '>', 'body.md'],
+ ['gh', 'pr', 'create'],
+ ]);
+ });
+
+ it('runs a heredoc body without its delimiter to the end of input', () => {
+ expect(parseShellCommandSegments(`cat <<EOF\nfirst line\nit's unterminated`)).toEqual([
+ ['cat'],
+ ]);
+ });
+
+ it('treats `<<` without a delimiter word as literal text', () => {
+ expect(parseShellCommandSegments('echo << ;')).toEqual([['echo', '<<']]);
+ });
+
+ it('treats a quoted delimiter whose closing quote does not follow the word as literal', () => {
+ expect(parseShellCommandSegments(`cat <<'EOF tail'`)).toEqual([['cat', '<<EOF tail']]);
+ });
+});
+
+describe('parseShellCommandSegments · quoting and escapes', () => {
+ it('returns null when a double quote ends on a dangling backslash', () => {
+ expect(parseShellCommandSegments('echo "unterminated \\')).toBeNull();
+ });
+
+ it('keeps a trailing unquoted backslash as an empty escape', () => {
+ expect(parseShellCommandSegments('echo done\\')).toEqual([['echo', 'done']]);
+ });
+});
+
+describe('parseShellCommandSegments · control operators', () => {
+ it('drops empty segments between leading, repeated and trailing operators', () => {
+ expect(parseShellCommandSegments('; git push && && gh pr list ;')).toEqual([
+ ['git', 'push'],
+ ['gh', 'pr', 'list'],
+ ]);
+ });
+});
+
+describe('parseShellCommandSegments · shell `-c` wrappers', () => {
+ it('skips non-command flags before `-c` and expands the payload', () => {
+ expect(parseShellCommandSegments(`bash -l -c 'gh pr view 7'`)).toEqual([
+ ['gh', 'pr', 'view', '7'],
+ ]);
+ });
+
+ it('drops only the wrapper segment when its payload has unterminated quoting', () => {
+ expect(parseShellCommandSegments(`bash -c "it's broken" && gh pr list`)).toEqual([
+ ['gh', 'pr', 'list'],
+ ]);
+ });
+
+ it('keeps a wrapper that carries flags but no command string', () => {
+ expect(parseShellCommandSegments('zsh -lc')).toEqual([['zsh', '-lc']]);
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/toolResultParsing.coverage.test.ts b/packages/database/src/models/work/__tests__/toolResultParsing.coverage.test.ts
new file mode 100644
index 00000000000..0af0d101e0f
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/toolResultParsing.coverage.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeLinearToolResult } from '../linearToolResult';
+import { sanitizeExternalUrl } from '../toolResultParsing';
+
+describe('sanitizeExternalUrl', () => {
+ it('skips a whitespace-only url', () => {
+ expect(sanitizeExternalUrl(' ')).toBeUndefined();
+ });
+});
+
+describe('normalizeLinearToolResult · field fallbacks', () => {
+ it('falls through a non-string description to content and keeps a null state', () => {
+ const operation = normalizeLinearToolResult({
+ data: {
+ content: 'Issue body',
+ description: 42,
+ id: 'issue-uuid-1',
+ identifier: 'LOB-1',
+ state: null,
+ title: 'Numeric description',
+ },
+ toolName: 'save_issue',
+ });
+
+ expect(operation?.params).toMatchObject({
+ content: 'Issue body',
+ description: 'Issue body',
+ identifier: 'LOB-1',
+ resourceId: 'issue-uuid-1',
+ resourceType: 'linear_issue',
+ status: null,
+ });
+ expect(operation?.params.patchFields).toEqual(
+ expect.arrayContaining(['content', 'description', 'status', 'title']),
+ );
+ });
+
+ it('clears the status when a nested state object carries no name or type', () => {
+ const operation = normalizeLinearToolResult({
+ data: { id: 'issue-uuid-2', identifier: 'LOB-2', state: {} },
+ toolName: 'save_issue',
+ });
+
+ expect(operation?.params.status).toBeNull();
+ expect(operation?.params.patchFields).toContain('status');
+ });
+
+ it('leaves the identifier unset when a document url has no document segment', () => {
+ const operation = normalizeLinearToolResult({
+ data: { id: 'doc-uuid-1', title: 'Spec', url: 'https://linear.app/lobehub/view/all' },
+ toolName: 'update_document',
+ });
+
+ expect(operation?.params).toMatchObject({
+ changeType: 'updated',
+ identifier: null,
+ resourceId: 'doc-uuid-1',
+ resourceType: 'linear_document',
+ url: 'https://linear.app/lobehub/view/all',
+ });
+ expect(operation?.params.patchFields).not.toContain('identifier');
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/work.coverage.test.ts b/packages/database/src/models/work/__tests__/work.coverage.test.ts
new file mode 100644
index 00000000000..161238dad07
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/work.coverage.test.ts
@@ -0,0 +1,329 @@
+// @vitest-environment node
+import type { RegisterCanvasWorkParams, RegisterExternalWorkParams } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agentDocuments, agents, documents, topics, users, workVersions } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { WorkModel } from '..';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'work-cov-user';
+const otherUserId = 'work-cov-other';
+const topicId = 'work-cov-topic';
+const agentId = 'work-cov-agent';
+
+const externalParams = (
+ overrides: Partial<RegisterExternalWorkParams> = {},
+): RegisterExternalWorkParams => ({
+ changeType: 'created',
+ resourceId: 'LOB-cov-1',
+ resourceType: 'linear_issue',
+ title: 'Coverage issue',
+ toolIdentifier: 'linear',
+ toolName: 'save_issue',
+ ...overrides,
+});
+
+const canvasParams = (
+ overrides: Partial<RegisterCanvasWorkParams> = {},
+): RegisterCanvasWorkParams => ({
+ canvasId: 'cvs_work_cov',
+ metadata: {
+ entry: 'index.html',
+ fileCount: 1,
+ manifestKey: 'canvas/work-cov/manifests/a.json',
+ runtimeMajor: 1,
+ totalSize: 128,
+ },
+ title: 'Coverage canvas',
+ toolCallId: 'call-canvas-cov',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ ...overrides,
+});
+
+const insertDocument = async (owner = userId) => {
+ const [doc] = await serverDB
+ .insert(documents)
+ .values({
+ content: 'Body',
+ fileType: 'text/markdown',
+ source: 'work-coverage.md',
+ sourceType: 'api',
+ title: 'Coverage doc',
+ totalCharCount: 4,
+ totalLineCount: 1,
+ userId: owner,
+ })
+ .returning();
+ return doc;
+};
+
+const model = () => new WorkModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values({ id: topicId, userId });
+ await serverDB.insert(agents).values({ id: agentId, title: 'Coverage agent', userId });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('WorkModel coverage · canvas', () => {
+ it('stores a null description when the canvas registration omits one', async () => {
+ const work = await model().registerCanvas(canvasParams());
+
+ expect(work.description).toBeNull();
+ expect(await model().listCanvases({})).toEqual([expect.objectContaining({ id: work.id })]);
+ });
+
+ it('finds only the caller’s referenced manifest keys', async () => {
+ await model().registerCanvas(canvasParams());
+
+ expect(await model().findReferencedCanvasManifestKeys([])).toEqual([]);
+ expect(
+ await model().findReferencedCanvasManifestKeys([
+ 'canvas/work-cov/manifests/a.json',
+ 'canvas/work-cov/manifests/missing.json',
+ ]),
+ ).toEqual(['canvas/work-cov/manifests/a.json']);
+ expect(
+ await new WorkModel(serverDB, otherUserId).findReferencedCanvasManifestKeys([
+ 'canvas/work-cov/manifests/a.json',
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe('WorkModel coverage · cost', () => {
+ it('sums versions without a root operation as independent operations', async () => {
+ const work = await model().registerExternal(
+ externalParams({ cumulativeCost: 0.5, toolCallId: 'call-cost-1' }),
+ );
+ await model().registerExternal(
+ externalParams({ cumulativeCost: 0.25, toolCallId: 'call-cost-2' }),
+ );
+
+ const page = await model().listByWorkspace({});
+
+ expect(page.items).toEqual([expect.objectContaining({ id: work!.id, totalCost: 0.75 })]);
+ });
+});
+
+describe('WorkModel coverage · document', () => {
+ it('returns null for a document the caller cannot resolve', async () => {
+ expect(
+ await model().registerDocument({
+ changeType: 'created',
+ documentId: 'docs_missing',
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'createDocument',
+ }),
+ ).toBeNull();
+ });
+
+ it('stores null version metadata without an agent document binding', async () => {
+ const doc = await insertDocument();
+
+ const work = await model().registerDocument({
+ changeType: 'created',
+ documentId: doc.id,
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'createDocument',
+ });
+
+ const [version] = await serverDB
+ .select({ metadata: workVersions.metadata })
+ .from(workVersions)
+ .where(eq(workVersions.workId, work!.id));
+ expect(version.metadata).toBeNull();
+ });
+
+ it('accepts a binding without agentId but rejects one bound to another document', async () => {
+ const doc = await insertDocument();
+ const otherDoc = await insertDocument();
+ const [binding] = await serverDB
+ .insert(agentDocuments)
+ .values({ agentId, documentId: doc.id, userId })
+ .returning();
+
+ const bound = await model().registerDocument({
+ agentDocumentId: binding.id,
+ changeType: 'created',
+ documentId: doc.id,
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'createDocument',
+ });
+ expect(bound).toMatchObject({ resourceId: doc.id, resourceType: 'document' });
+
+ expect(
+ await model().registerDocument({
+ agentDocumentId: binding.id,
+ changeType: 'created',
+ documentId: otherDoc.id,
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'createDocument',
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('WorkModel coverage · file and task', () => {
+ it('stores null identifier and url for a path without a basename and no file url', async () => {
+ const work = await model().registerFile({
+ filePath: '/',
+ metadata: {
+ fileId: 'file-cov',
+ filePath: '/',
+ fileSize: 0,
+ linesAdded: 0,
+ linesDeleted: 0,
+ mimeType: 'application/octet-stream',
+ },
+ title: 'root',
+ toolCallId: 'op:file-cov',
+ toolIdentifier: 'lobe-cloud-sandbox',
+ toolName: 'writeFile',
+ topicId,
+ userId,
+ });
+
+ expect(work).toMatchObject({ description: '/', identifier: null, url: null });
+ });
+
+ it('returns null when a task registration names no task', async () => {
+ expect(
+ await model().registerTask({
+ changeType: 'created',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('WorkModel coverage · facade', () => {
+ it('ignores a skill tool result from an unknown provider', async () => {
+ expect(
+ await model().handleSkillToolResult({
+ data: { id: 'x' },
+ provider: 'notion',
+ toolName: 'save_page',
+ }),
+ ).toBeNull();
+ });
+
+ it('registers a shell gh result under the producing tool identifier', async () => {
+ const work = await model().registerShellGithubResult({
+ data: {
+ command: `gh issue create --repo lobehub/lobehub --title 'Shell issue'`,
+ exitCode: 0,
+ output: 'https://github.com/lobehub/lobehub/issues/4242',
+ },
+ toolIdentifier: 'codex',
+ toolName: 'command_execution',
+ });
+
+ expect(work).toMatchObject({
+ resourceId: 'lobehub/lobehub#4242',
+ resourceType: 'github_issue',
+ title: 'Shell issue',
+ toolIdentifier: 'codex',
+ });
+ });
+
+ it('returns null for a shell result that ran no gh write', async () => {
+ expect(
+ await model().registerShellGithubResult({
+ data: { command: 'ls -la', exitCode: 0, output: '' },
+ toolIdentifier: 'codex',
+ toolName: 'command_execution',
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('WorkModel coverage · queries', () => {
+ it('caps each root operation’s version events at the limit', async () => {
+ await model().registerExternal(
+ externalParams({ resourceId: 'LOB-cap-1', rootOperationId: 'op-cap', toolCallId: 'c1' }),
+ );
+ const latest = await model().registerExternal(
+ externalParams({ resourceId: 'LOB-cap-2', rootOperationId: 'op-cap', toolCallId: 'c2' }),
+ );
+
+ const map = await model().listByRootOperations({
+ limit: 1,
+ rootOperationIds: ['op-cap', 'op-cap-empty'],
+ });
+
+ expect(map['op-cap']).toEqual([expect.objectContaining({ id: latest!.id })]);
+ expect(map['op-cap-empty']).toEqual([]);
+ });
+
+ it('returns no summaries for a null root operation list', async () => {
+ expect(await model().listSummariesByRootOperations({ rootOperationIds: null })).toEqual({});
+ });
+
+ it('caps each root operation’s summaries at the limit', async () => {
+ await model().registerExternal(
+ externalParams({ resourceId: 'LOB-sum-1', rootOperationId: 'op-sum', toolCallId: 's1' }),
+ );
+ await model().registerExternal(
+ externalParams({ resourceId: 'LOB-sum-2', rootOperationId: 'op-sum', toolCallId: 's2' }),
+ );
+
+ // A second requested id widens the anchor scan to two rows, so both Works
+ // anchor on op-sum and the per-operation cap has to drop one.
+ const map = await model().listSummariesByRootOperations({
+ limit: 1,
+ rootOperationIds: ['op-sum', 'op-sum-empty'],
+ });
+
+ expect(map['op-sum']).toHaveLength(1);
+ expect(map['op-sum-empty']).toEqual([]);
+ });
+
+ it('lists a Work once per conversation even when it has several versions there', async () => {
+ const work = await model().registerExternal(externalParams({ toolCallId: 'conv-1', topicId }));
+ await model().registerExternal(
+ externalParams({ title: 'Edited', toolCallId: 'conv-2', topicId }),
+ );
+
+ const items = await model().listByConversation({ topicId });
+
+ expect(items.map((item) => item.id)).toEqual([work!.id]);
+ });
+
+ it('stops the conversation list at the limit', async () => {
+ await model().registerExternal(
+ externalParams({ resourceId: 'LOB-conv-a', toolCallId: 'conv-a', topicId }),
+ );
+ const latest = await model().registerExternal(
+ externalParams({ resourceId: 'LOB-conv-b', toolCallId: 'conv-b', topicId }),
+ );
+
+ const items = await model().listByConversation({ limit: 1, topicId });
+
+ expect(items.map((item) => item.id)).toEqual([latest!.id]);
+ });
+
+ it.each([
+ ['without a separator', 'not-a-cursor'],
+ ['with an unparseable timestamp', 'yesterday|work-id'],
+ ['with an empty id', '2024-01-01T00:00:00.000Z|'],
+ ])('ignores a malformed workspace cursor %s', async (_label, cursor) => {
+ const work = await model().registerExternal(externalParams({ toolCallId: 'cursor-1' }));
+
+ const page = await model().listByWorkspace({ cursor });
+
+ expect(page.items.map((item) => item.id)).toEqual([work!.id]);
+ expect(page.nextCursor).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/writes.coverage.test.ts b/packages/database/src/models/work/__tests__/writes.coverage.test.ts
new file mode 100644
index 00000000000..b8c9da7de8f
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/writes.coverage.test.ts
@@ -0,0 +1,220 @@
+// @vitest-environment node
+import type { RegisterExternalWorkParams } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { documents, users, works, workspaces, workVersions } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { createProxyTestDB } from '../../__tests__/_proxyTestDB';
+import { WorkModel } from '..';
+import { registerWorkVersion } from '../writes';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'work-writes-cov-user';
+const otherUserId = 'work-writes-cov-other';
+const workspaceId = 'work-writes-cov-workspace';
+
+const externalParams = (
+ overrides: Partial<RegisterExternalWorkParams> = {},
+): RegisterExternalWorkParams => ({
+ changeType: 'created',
+ resourceId: 'LOB-writes-1',
+ resourceType: 'linear_issue',
+ title: 'Writes coverage issue',
+ toolIdentifier: 'linear',
+ toolName: 'save_issue',
+ ...overrides,
+});
+
+const identity = {
+ resourceId: 'LOB-writes-direct',
+ resourceType: 'linear_issue' as const,
+ type: 'external' as const,
+ userId,
+ visibility: 'private' as const,
+};
+
+const versionParams = {
+ changeType: 'created' as const,
+ toolCallId: 'call-writes-direct',
+ toolIdentifier: 'linear',
+ toolName: 'save_issue',
+};
+
+const display = {
+ content: null,
+ description: null,
+ identifier: 'LOB-writes-direct',
+ status: null,
+ title: 'Direct registration',
+ url: null,
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('registerWorkVersion · retry classification', () => {
+ it('retries a non-Error unique violation and stores null metadata when none is built', async () => {
+ const buildInput = vi
+ .fn()
+ .mockRejectedValueOnce({ code: '23505' })
+ .mockResolvedValue({ display });
+
+ const work = await registerWorkVersion(
+ { db: serverDB, userId },
+ identity,
+ versionParams,
+ buildInput,
+ );
+
+ expect(buildInput).toHaveBeenCalledTimes(2);
+ const versions = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work.id));
+ expect(versions).toHaveLength(1);
+ expect(versions[0]).toMatchObject({ metadata: null, title: 'Direct registration', version: 1 });
+ });
+
+ it('rethrows a non-Error failure that is not a unique violation without retrying', async () => {
+ const buildInput = vi.fn().mockRejectedValue('upstream exploded');
+
+ await expect(
+ registerWorkVersion({ db: serverDB, userId }, identity, versionParams, buildInput),
+ ).rejects.toBe('upstream exploded');
+
+ expect(buildInput).toHaveBeenCalledTimes(1);
+ // The failed transaction rolled back the freshly inserted identity row.
+ expect(
+ await serverDB.select().from(works).where(eq(works.resourceId, identity.resourceId)),
+ ).toEqual([]);
+ });
+});
+
+describe('registerWorkVersion · identity guards', () => {
+ it('appends a new version on every call when no toolCallId dedupes it', async () => {
+ const model = new WorkModel(serverDB, userId);
+
+ const first = await model.registerExternal(externalParams());
+ const second = await model.registerExternal(externalParams({ title: 'Renamed' }));
+
+ expect(second?.id).toBe(first?.id);
+ const versions = await serverDB
+ .select({ toolCallId: workVersions.toolCallId, version: workVersions.version })
+ .from(workVersions)
+ .where(eq(workVersions.workId, first!.id))
+ .orderBy(workVersions.version);
+ expect(versions).toEqual([
+ { toolCallId: null, version: 1 },
+ { toolCallId: null, version: 2 },
+ ]);
+ });
+
+ it('refuses to adopt a teammate’s private Work for the same workspace resource', async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Writes coverage workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ const owner = new WorkModel(serverDB, userId, workspaceId);
+ const teammate = new WorkModel(serverDB, otherUserId, workspaceId);
+
+ const original = await owner.registerExternal(externalParams({ toolCallId: 'call-owner' }));
+
+ await expect(
+ teammate.registerExternal(externalParams({ title: 'Hijacked', toolCallId: 'call-mate' })),
+ ).rejects.toThrow('Failed to resolve external Work identity');
+
+ const [row] = await serverDB.select().from(works).where(eq(works.id, original!.id));
+ expect(row).toMatchObject({ title: 'Writes coverage issue', userId });
+ expect(
+ await serverDB.select().from(workVersions).where(eq(workVersions.workId, original!.id)),
+ ).toHaveLength(1);
+ });
+});
+
+describe('registerWorkVersion · rows that vanish mid-transaction', () => {
+ /**
+ * pg-proxy has no transaction support, so the transaction callback runs on a
+ * proxy over the real connection; the rewrite simulates a concurrent delete
+ * landing between the identity upsert and the statement under test.
+ */
+ const runTransactionOn = (proxyDB: LobeChatDatabase) =>
+ vi
+ .spyOn(serverDB, 'transaction')
+ .mockImplementation(((callback: (tx: LobeChatDatabase) => unknown) =>
+ callback(proxyDB)) as never);
+
+ it('throws when the Work row is gone by the time it is locked', async () => {
+ runTransactionOn(
+ createProxyTestDB(serverDB, (query, result) =>
+ /for update/i.test(query) ? [] : result.rows,
+ ),
+ );
+
+ await expect(
+ new WorkModel(serverDB, userId).registerExternal(externalParams({ toolCallId: 'call-lock' })),
+ ).rejects.toThrow(/^Work .+ no longer exists$/);
+ });
+
+ it('throws when the current-projection update matches no row', async () => {
+ runTransactionOn(
+ createProxyTestDB(serverDB, (query, result) =>
+ /^update "works"/i.test(query) ? [] : result.rows,
+ ),
+ );
+
+ await expect(
+ new WorkModel(serverDB, userId).registerExternal(
+ externalParams({ toolCallId: 'call-update' }),
+ ),
+ ).rejects.toThrow(/^Work .+ no longer exists$/);
+ });
+});
+
+describe('delete and visibility writes', () => {
+ it('leaves Works alone when the document is not visible to the caller', async () => {
+ const [doc] = await serverDB
+ .insert(documents)
+ .values({
+ content: 'Body',
+ fileType: 'text/markdown',
+ source: 'writes-coverage.md',
+ sourceType: 'api',
+ title: 'Writes coverage doc',
+ totalCharCount: 4,
+ totalLineCount: 1,
+ userId,
+ })
+ .returning();
+ const model = new WorkModel(serverDB, userId);
+ const work = await model.registerDocument({
+ changeType: 'created',
+ documentId: doc.id,
+ toolIdentifier: 'lobe-agent-documents',
+ toolName: 'createDocument',
+ });
+
+ await new WorkModel(serverDB, otherUserId).deleteDocumentWork({ documentId: doc.id });
+
+ expect(await serverDB.select().from(works).where(eq(works.id, work!.id))).toHaveLength(1);
+ });
+
+ it('skips the update entirely for an empty task id list', async () => {
+ const updateSpy = vi.spyOn(serverDB, 'update');
+
+ await new WorkModel(serverDB, userId).setTaskWorksVisibility([], 'private');
+
+ expect(updateSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.ts
index 7aa05588025..5f249c451dc 100644
--- a/packages/database/src/models/work/githubToolResult.ts
+++ b/packages/database/src/models/work/githubToolResult.ts
@@ -90,6 +90,7 @@ const numberFromRecord = (record: Record<string, unknown>, keys: string[]) => {
/** Join MCP-style content parts (`{ content: [{ text }] }`) back into one string. */
const textFromContentParts = (value: unknown): string | null => {
+ /* v8 ignore next -- unreachable: both callers pass a value already checked with Array.isArray */
if (!Array.isArray(value)) return null;
const joined = value
diff --git a/packages/database/src/models/work/linearToolResult.ts b/packages/database/src/models/work/linearToolResult.ts
index 5fbaa2d6459..24a83133449 100644
--- a/packages/database/src/models/work/linearToolResult.ts
+++ b/packages/database/src/models/work/linearToolResult.ts
@@ -105,8 +105,10 @@ const unwrapData = (data: unknown, keys: string[]) => {
return nestedRecord(record, keys);
};
+/* v8 ignore start -- unreachable `false` fallback: the only caller passes the record id, already non-empty */
const isIssueIdentifier = (value: string | null) =>
value ? LINEAR_ISSUE_IDENTIFIER_PATTERN.test(value) : false;
+/* v8 ignore stop */
const urlSegmentAfter = (url: string | null, segmentName: string) => {
if (!url) return null;
diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.ts
index fcc6a5ad753..32c789f6857 100644
--- a/packages/database/src/models/work/queries.ts
+++ b/packages/database/src/models/work/queries.ts
@@ -67,6 +67,7 @@ export const listByRootOperation = async (
rootOperationIds: [params.rootOperationId],
});
+ /* v8 ignore next -- unreachable: listByRootOperations pre-seeds an entry for every requested id */
return map[params.rootOperationId] ?? [];
};
@@ -106,6 +107,7 @@ export const listByRootOperations = async (
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);
@@ -159,6 +161,7 @@ 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);
}
@@ -198,6 +201,7 @@ export const listSummariesByRootOperations = async (
for (const summary of summaries) {
const rootOperationId = anchorByWorkId.get(summary.id);
+ /* v8 ignore next -- unreachable: rows are filtered to anchorByWorkId keys, whose values are requested ids */
if (!rootOperationId || !(rootOperationId in result)) continue;
if (result[rootOperationId].length >= limit) continue;
result[rootOperationId].push(summary);