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.

✨ feat(linear): sync Linear comments into task activity (#22087)

Rdmclin29fd5130c9079
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.ts
index b0164128e70..79b1d3cf9c0 100644
--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts
@@ -778,6 +778,41 @@ describe('linearRouter', () => {
expect(latest).toMatchObject({ error: 'reconnect', id: second.id, status: 'error' });
});
+ it('passes the comment choice of an import and a rule run on to the sync', async () => {
+ const connection = await connect({ userId });
+ mocks.getToken.mockResolvedValue('token');
+ mocks.runSync.mockResolvedValue({ ok: true });
+ mocks.importIssues.mockResolvedValue(syncResult);
+ mocks.syncByFilter.mockResolvedValue(syncResult);
+
+ const imported = await caller({ userId }).startImport({
+ connectionId: connection.id,
+ issueIds: ['issue-1'],
+ projectId,
+ syncComments: true,
+ });
+ await new LinearSyncJobService(serverDB, userId).run(imported.id);
+ expect(mocks.importIssues).toHaveBeenCalledWith('token', ['issue-1'], {
+ syncComments: true,
+ targetProjectId: projectId,
+ });
+
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId,
+ stateTypes: ['backlog'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+ const run = await caller({ userId }).startRuleSync({ ruleId: rule.id, syncComments: true });
+ await new LinearSyncJobService(serverDB, userId).run(run.id);
+ expect(mocks.syncByFilter).toHaveBeenCalledWith(
+ 'token',
+ expect.objectContaining({ teamId: 'team-1' }),
+ expect.objectContaining({ syncComments: true }),
+ );
+ });
+
it("lists only the project's own rules, and drops them with the project", async () => {
const connection = await connect({ userId });
await serverDB
diff --git a/apps/server/src/routers/lambda/linear.ts b/apps/server/src/routers/lambda/linear.ts
index 5a4c89824a6..65136c6f014 100644
--- a/apps/server/src/routers/lambda/linear.ts
+++ b/apps/server/src/routers/lambda/linear.ts
@@ -153,6 +153,8 @@ export const linearRouter = router({
projectInput.extend({
connectionId: z.string().uuid(),
issueIds: z.array(z.string().min(1)).min(1).max(MAX_IMPORT_ISSUES),
+ /** Also copy each issue's Linear comments onto its task. */
+ syncComments: z.boolean().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
@@ -165,6 +167,7 @@ export const linearRouter = router({
issueIds: [...new Set(input.issueIds)],
kind: 'issues',
projectId: input.projectId,
+ syncComments: input.syncComments || undefined,
});
return { id };
}),
@@ -241,7 +244,13 @@ export const linearRouter = router({
* still going is returned instead of starting a second one.
*/
startRuleSync: linearTaskWriteProcedure
- .input(z.object({ ruleId: z.string().uuid() }))
+ .input(
+ z.object({
+ ruleId: z.string().uuid(),
+ /** Also copy each issue's Linear comments onto its task. */
+ syncComments: z.boolean().optional(),
+ }),
+ )
.mutation(async ({ ctx, input }) => {
const rule = await requireSyncRule(ctx, input.ruleId);
// The rule is in the caller's scope, and so is the connection it was
@@ -261,6 +270,7 @@ export const linearRouter = router({
kind: 'rule',
projectId: rule.projectId,
ruleId: rule.id,
+ syncComments: input.syncComments || undefined,
},
);
return { id };
diff --git a/apps/server/src/services/linear/__tests__/issueComments.test.ts b/apps/server/src/services/linear/__tests__/issueComments.test.ts
new file mode 100644
index 00000000000..cd211ede1f6
--- /dev/null
+++ b/apps/server/src/services/linear/__tests__/issueComments.test.ts
@@ -0,0 +1,111 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { linearCommentAuthor, linearCommentToContent } from '../issueComments';
+import { type LinearIssueComment, listLinearIssueComments } from '../issues';
+
+vi.mock('@/envs/linear', () => ({
+ linearEnv: { ENABLED_LINEAR: true, LINEAR_CLIENT_ID: 'client', LINEAR_CLIENT_SECRET: 'secret' },
+}));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));
+
+const comment = (overrides: Partial<LinearIssueComment> = {}): LinearIssueComment => ({
+ body: '首付款 20%',
+ createdAt: '2026-01-02T03:04:05.000Z',
+ id: 'c1',
+ issueId: 'issue-1',
+ url: 'https://linear.app/acme/issue/PM-40#comment-c1',
+ user: { displayName: 'JianXu', name: 'Jian Xu' },
+ ...overrides,
+});
+
+describe('linearCommentToContent', () => {
+ it('credits the Linear author and links back to the comment', () => {
+ expect(linearCommentToContent(comment())).toBe(
+ '> **JianXu** on [Linear](https://linear.app/acme/issue/PM-40#comment-c1)\n\n首付款 20%',
+ );
+ });
+
+ it('marks a reply and keeps a name from becoming markdown', () => {
+ expect(
+ linearCommentToContent(
+ comment({ body: ' ok ', parentId: 'c0', user: { displayName: 'a_b*', name: 'x' } }),
+ ),
+ ).toBe(
+ '> **a\\_b\\*** replied on [Linear](https://linear.app/acme/issue/PM-40#comment-c1)\n\nok',
+ );
+ });
+
+ it('keeps only the credit line for an empty body', () => {
+ expect(linearCommentToContent(comment({ body: ' ' }))).toBe(
+ '> **JianXu** on [Linear](https://linear.app/acme/issue/PM-40#comment-c1)',
+ );
+ });
+});
+
+describe('linearCommentAuthor', () => {
+ it('falls back from a member to an outside user, an integration, then Linear', () => {
+ expect(linearCommentAuthor(comment({ user: { displayName: '', name: 'Jian Xu' } }))).toBe(
+ 'Jian Xu',
+ );
+ expect(linearCommentAuthor(comment({ externalUser: { name: 'Customer' }, user: null }))).toBe(
+ 'Customer',
+ );
+ expect(
+ linearCommentAuthor(
+ comment({ botActor: { name: 'GitHub', userDisplayName: 'octocat' }, user: null }),
+ ),
+ ).toBe('octocat');
+ expect(linearCommentAuthor(comment({ botActor: { name: 'GitHub' }, user: null }))).toBe(
+ 'GitHub',
+ );
+ expect(linearCommentAuthor(comment({ user: null }))).toBe('Linear');
+ });
+});
+
+describe('listLinearIssueComments', () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ fetchMock.mockReset();
+ });
+
+ const page = (nodes: LinearIssueComment[], endCursor?: string) =>
+ new Response(
+ JSON.stringify({
+ data: { comments: { nodes, pageInfo: { endCursor, hasNextPage: !!endCursor } } },
+ }),
+ { headers: { 'content-type': 'application/json' }, status: 200 },
+ );
+
+ const variables = (call: number) =>
+ JSON.parse((fetchMock.mock.calls[call][1] as RequestInit).body as string).variables;
+
+ it('reads every page for each batch of issues and returns them oldest first', async () => {
+ const issueIds = Array.from({ length: 51 }, (_, index) => `issue-${index}`);
+ fetchMock
+ .mockResolvedValueOnce(page([comment({ createdAt: '2026-03-01T00:00:00Z', id: 'c3' })], 'n'))
+ .mockResolvedValueOnce(page([comment({ createdAt: '2026-01-01T00:00:00Z', id: 'c1' })]))
+ .mockResolvedValueOnce(page([comment({ createdAt: '2026-02-01T00:00:00Z', id: 'c2' })]));
+
+ const comments = await listLinearIssueComments('token', [...issueIds, 'issue-0']);
+
+ expect(comments.map((item) => item.id)).toEqual(['c1', 'c2', 'c3']);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(variables(0).filter.issue.id.in).toHaveLength(50);
+ expect(variables(0).after).toBeUndefined();
+ expect(variables(1).after).toBe('n');
+ expect(variables(1).filter.issue.id.in).toHaveLength(50);
+ expect(variables(2).filter.issue.id.in).toEqual(['issue-50']);
+ });
+
+ it('asks Linear nothing for no issues', async () => {
+ expect(await listLinearIssueComments('token', [])).toEqual([]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
index 51175677b2b..12117a0ad89 100644
--- a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
+++ b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
@@ -9,19 +9,26 @@ import { TaskModel } from '@/database/models/task';
import { TaskExternalLinkModel } from '@/database/models/taskExternalLink';
import { tasks, users } from '@/database/schemas';
+import { LinearApiError } from '../client';
import type * as IssuesModule from '../issues';
-import type { LinearIssue } from '../issues';
-import { LinearIssueSyncService, MAX_TASKS_CREATED_PER_SYNC } from '../issueSync';
+import type { LinearIssue, LinearIssueComment } from '../issues';
+import {
+ LinearIssueSyncService,
+ MAX_COMMENT_CATCH_UPS_PER_SYNC,
+ MAX_TASKS_CREATED_PER_SYNC,
+} from '../issueSync';
const linear = vi.hoisted(() => ({
getLinearIssuesByIds: vi.fn(),
getLinearProjectTeamIds: vi.fn(),
+ listLinearIssueComments: vi.fn(),
listLinearIssues: vi.fn(),
}));
vi.mock('../issues', async (importOriginal) => ({
...(await importOriginal<typeof IssuesModule>()),
getLinearIssuesByIds: linear.getLinearIssuesByIds,
getLinearProjectTeamIds: linear.getLinearProjectTeamIds,
+ listLinearIssueComments: linear.listLinearIssueComments,
listLinearIssues: linear.listLinearIssues,
}));
@@ -553,3 +560,274 @@ describe('LinearIssueSyncService (real PostgreSQL)', () => {
expect((await linkedTask('1'))?.name).toBe('Renamed twice');
});
});
+
+describe('LinearIssueSyncService comments (real PostgreSQL)', () => {
+ const comment = (
+ overrides: Partial<LinearIssueComment> & { id: string; issueId: string },
+ ): LinearIssueComment => ({
+ body: `Comment ${overrides.id}`,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ url: `https://linear.app/acme/issue/ENG-1#comment-${overrides.id}`,
+ user: { displayName: 'JianXu', name: 'Jian Xu' },
+ ...overrides,
+ });
+
+ /** Serve these comments for whichever issues are asked about. */
+ const serveComments = (comments: LinearIssueComment[]) =>
+ linear.listLinearIssueComments.mockImplementation(async (_token: string, ids: string[]) =>
+ comments.filter((item) => ids.includes(item.issueId!)),
+ );
+
+ const commentsOf = async (externalId: string) => {
+ const task = await linkedTask(externalId);
+ return task ? new TaskModel(db, userId).getComments(task.id) : [];
+ };
+
+ const states = [...filter.stateTypes];
+
+ it('copies an imported issue’s comments onto its task, credited and in Linear’s time', async () => {
+ serve([issue({ id: '1' })]);
+ serveComments([
+ comment({ createdAt: '2026-02-01T00:00:00.000Z', id: 'c2', issueId: '1', parentId: 'c1' }),
+ comment({ createdAt: '2026-01-01T00:00:00.000Z', id: 'c1', issueId: '1' }),
+ ]);
+
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1'], {
+ syncComments: true,
+ });
+
+ expect(result).toMatchObject({ commentsImported: 2, created: 1 });
+ const comments = await commentsOf('1');
+ // Written in the order Linear returned them, each at its Linear time.
+ expect(comments.map((item) => item.createdAt.toISOString())).toEqual([
+ '2026-01-01T00:00:00.000Z',
+ '2026-02-01T00:00:00.000Z',
+ ]);
+ expect(comments[0]).toMatchObject({
+ authorUserId: userId,
+ content:
+ '> **JianXu** on [Linear](https://linear.app/acme/issue/ENG-1#comment-c1)\n\nComment c1',
+ });
+ expect(comments[1].content).toContain('**JianXu** replied on');
+ });
+
+ it('adds only new comments when synced again, even after the link is refreshed', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1' })]);
+ serveComments([comment({ id: 'c1', issueId: '1' })]);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: states }, { syncComments: true });
+
+ // Linear changed the issue too, so the link's display metadata is rewritten.
+ serve([issue({ id: '1', title: 'Renamed', updatedAt: '2026-10-02T00:00:00.000Z' })]);
+ serveComments([comment({ id: 'c1', issueId: '1' }), comment({ id: 'c2', issueId: '1' })]);
+ const second = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+ expect(second).toMatchObject({ commentsImported: 1, updated: 1 });
+
+ const third = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+ expect(third.commentsImported).toBeUndefined();
+ expect((await commentsOf('1')).map((item) => item.content)).toEqual([
+ expect.stringContaining('Comment c1'),
+ expect.stringContaining('Comment c2'),
+ ]);
+ });
+
+ it('fills in comments of tasks imported without them', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1' }), issue({ id: '2' })]);
+ serveComments([comment({ id: 'c1', issueId: '1' }), comment({ id: 'c2', issueId: '2' })]);
+
+ const first = await service.syncByFilter(TOKEN, { ...filter, stateTypes: states });
+ expect(first.commentsImported).toBeUndefined();
+ expect(linear.listLinearIssueComments).not.toHaveBeenCalled();
+ expect(await commentsOf('1')).toHaveLength(0);
+
+ const again = await service.importIssues(TOKEN, ['1', '2'], { syncComments: true });
+
+ expect(again).toMatchObject({ commentsImported: 2, created: 0 });
+ expect(await commentsOf('1')).toHaveLength(1);
+ expect(await commentsOf('2')).toHaveLength(1);
+ });
+
+ it('copies the last comments of an issue that left the filter as it closes the task', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1' })]);
+ serveComments([]);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: states }, { syncComments: true });
+
+ // Commented on, then completed: the open-states filter no longer lists it.
+ const done = issue({ id: '1', state: { name: 'Done', type: 'completed' } });
+ linear.listLinearIssues.mockImplementation(async () => ({ hasMore: false, issues: [] }));
+ linear.getLinearIssuesByIds.mockImplementation(async () => [done]);
+ serveComments([comment({ id: 'c-final', issueId: '1' })]);
+
+ const result = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+
+ expect(result).toMatchObject({ closed: 1, commentsImported: 1 });
+ expect((await linkedTask('1'))?.status).toBe('completed');
+ expect((await commentsOf('1')).map((item) => item.content)).toEqual([
+ expect.stringContaining('Comment c-final'),
+ ]);
+ });
+
+ it('leaves the comments of an open issue the filter no longer lists to its own rule', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1' })]);
+ serveComments([]);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: states }, { syncComments: true });
+
+ // Moved to a project another rule covers: still open, no longer listed.
+ linear.listLinearIssues.mockImplementation(async () => ({ hasMore: false, issues: [] }));
+ linear.getLinearIssuesByIds.mockImplementation(async () => [issue({ id: '1' })]);
+ serveComments([comment({ id: 'c-elsewhere', issueId: '1' })]);
+ linear.listLinearIssueComments.mockClear();
+
+ const result = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+
+ expect(result.commentsImported).toBeUndefined();
+ expect(linear.listLinearIssueComments).not.toHaveBeenCalled();
+ expect(await commentsOf('1')).toHaveLength(0);
+ expect((await linkedTask('1'))?.status).not.toBe('completed');
+ });
+
+ it('catches up the comments of a closed task the filter no longer reaches, once', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ // Imported as completed, without comments, before comments could be synced.
+ const done = issue({ id: '1', state: { name: 'Done', type: 'completed' } });
+ serve([done]);
+ await service.importIssues(TOKEN, ['1']);
+ expect((await linkedTask('1'))?.status).toBe('completed');
+
+ // A rule over open states only never lists it again.
+ linear.listLinearIssues.mockImplementation(async () => ({ hasMore: false, issues: [] }));
+ serveComments([comment({ id: 'c1', issueId: '1' })]);
+ const result = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+
+ expect(result).toMatchObject({ closed: 0, commentsImported: 1 });
+ expect(await commentsOf('1')).toHaveLength(1);
+
+ linear.listLinearIssueComments.mockClear();
+ const again = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+ expect(again.commentsImported).toBeUndefined();
+ expect(linear.listLinearIssueComments).not.toHaveBeenCalled();
+ });
+
+ it('catches up a bounded number of closed tasks per run, the rest on the next', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ const total = MAX_COMMENT_CATCH_UPS_PER_SYNC + 1;
+ const done = Array.from({ length: total }, (_, index) =>
+ issue({ id: `${index + 1}`, state: { name: 'Done', type: 'completed' } }),
+ );
+ serve(done);
+ const ids = done.map((item) => item.id);
+ for (let start = 0; start < ids.length; start += MAX_TASKS_CREATED_PER_SYNC) {
+ await service.importIssues(TOKEN, ids.slice(start, start + MAX_TASKS_CREATED_PER_SYNC));
+ }
+
+ linear.listLinearIssues.mockImplementation(async () => ({ hasMore: false, issues: [] }));
+ serveComments(done.map((item) => comment({ id: `c${item.id}`, issueId: item.id })));
+ const readIds = () =>
+ linear.listLinearIssueComments.mock.calls.flatMap(([, issueIds]) => issueIds as string[]);
+
+ const first = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+ expect(first.commentsImported).toBe(MAX_COMMENT_CATCH_UPS_PER_SYNC);
+ expect(readIds()).toHaveLength(MAX_COMMENT_CATCH_UPS_PER_SYNC);
+
+ linear.listLinearIssueComments.mockClear();
+ const second = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+ expect(second.commentsImported).toBe(1);
+ expect(readIds()).toHaveLength(1);
+ });
+
+ it('retries a closed task whose comments could not be read', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1', state: { name: 'Done', type: 'completed' } })]);
+ linear.listLinearIssueComments.mockRejectedValue(new LinearApiError('rate limited', 429));
+ await service.importIssues(TOKEN, ['1'], { syncComments: true });
+ expect(await commentsOf('1')).toHaveLength(0);
+
+ linear.listLinearIssues.mockImplementation(async () => ({ hasMore: false, issues: [] }));
+ serveComments([comment({ id: 'c1', issueId: '1' })]);
+ const result = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+
+ expect(result.commentsImported).toBe(1);
+ expect(await commentsOf('1')).toHaveLength(1);
+ });
+
+ it('leaves out issues it did not import and tasks the caller cannot see', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1' })]);
+ await service.importIssues(TOKEN, ['1']);
+ const task = await linkedTask('1');
+ await db
+ .update(tasks)
+ .set({ deletedAt: new Date(), isDeleted: true })
+ .where(eq(tasks.id, task!.id));
+
+ serve([issue({ id: '1' }), issue({ id: '2', state: { name: 'Done', type: 'completed' } })]);
+ serveComments([comment({ id: 'c1', issueId: '1' }), comment({ id: 'c2', issueId: '2' })]);
+ const result = await service.syncByFilter(
+ TOKEN,
+ { ...filter, stateTypes: states },
+ { syncComments: true },
+ );
+
+ expect(result.commentsImported).toBeUndefined();
+ expect(linear.listLinearIssueComments).not.toHaveBeenCalled();
+ });
+
+ it('keeps the run when comments cannot be read, and fails it on a revoked token', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ serve([issue({ id: '1' })]);
+ linear.listLinearIssueComments.mockRejectedValue(new LinearApiError('rate limited', 429));
+
+ const result = await service.importIssues(TOKEN, ['1'], { syncComments: true });
+
+ expect(result).toMatchObject({
+ created: 1,
+ skipped: [{ identifier: 'ENG-1', reason: 'commentsFailed' }],
+ skippedCount: 1,
+ });
+ expect(result.commentsImported).toBeUndefined();
+
+ linear.listLinearIssueComments.mockRejectedValue(new LinearApiError('revoked', 401));
+ await expect(service.importIssues(TOKEN, ['1'], { syncComments: true })).rejects.toThrow(
+ 'revoked',
+ );
+ });
+});
diff --git a/apps/server/src/services/linear/__tests__/syncJob.test.ts b/apps/server/src/services/linear/__tests__/syncJob.test.ts
index 6054a2c30e6..39c8d31a006 100644
--- a/apps/server/src/services/linear/__tests__/syncJob.test.ts
+++ b/apps/server/src/services/linear/__tests__/syncJob.test.ts
@@ -114,6 +114,21 @@ describe('mergeLinearSyncResults', () => {
),
).toMatchObject({ closed: 3, created: 100, skippedCount: 1, unchanged: 100 });
});
+
+ it('adds up comments every round copied, resumed or not', () => {
+ expect(
+ mergeLinearSyncResults(result({ commentsImported: 4 }), result({ commentsImported: 1 }), {
+ resumed: false,
+ }).commentsImported,
+ ).toBe(5);
+ expect(
+ mergeLinearSyncResults(result({ commentsImported: 4 }), result({}), { resumed: true })
+ .commentsImported,
+ ).toBe(4);
+ expect(
+ mergeLinearSyncResults(result({}), result({}), { resumed: true }).commentsImported,
+ ).toBeUndefined();
+ });
});
describe('withinRoundCap', () => {
diff --git a/apps/server/src/services/linear/issueComments.ts b/apps/server/src/services/linear/issueComments.ts
new file mode 100644
index 00000000000..d061c56bef4
--- /dev/null
+++ b/apps/server/src/services/linear/issueComments.ts
@@ -0,0 +1,26 @@
+import type { LinearIssueComment } from './issues';
+
+/** Who wrote a Linear comment, as Linear shows it. */
+export const linearCommentAuthor = (comment: LinearIssueComment): string =>
+ comment.user?.displayName ||
+ comment.user?.name ||
+ comment.externalUser?.name ||
+ comment.botActor?.userDisplayName ||
+ comment.botActor?.name ||
+ 'Linear';
+
+/** Keeps a name from being read as markdown emphasis or a link. */
+const escapeMarkdown = (text: string) => text.replaceAll(/([*_[\]`\\])/g, '\\$1');
+
+/**
+ * A Linear comment as a task comment. The task comment is posted by the
+ * person who ran the sync, so the first line credits the Linear author and
+ * links back to the original.
+ */
+export const linearCommentToContent = (comment: LinearIssueComment): string => {
+ const author = `**${escapeMarkdown(linearCommentAuthor(comment))}**`;
+ const source = `[Linear](${comment.url})`;
+ const header = comment.parentId ? `> ${author} replied on ${source}` : `> ${author} on ${source}`;
+ const body = comment.body.trim();
+ return body ? `${header}\n\n${body}` : header;
+};
diff --git a/apps/server/src/services/linear/issueSync.ts b/apps/server/src/services/linear/issueSync.ts
index a8f6c522bc7..98933ddec9b 100644
--- a/apps/server/src/services/linear/issueSync.ts
+++ b/apps/server/src/services/linear/issueSync.ts
@@ -19,12 +19,16 @@ import {
import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '../task';
+import { LinearApiError } from './client';
+import { linearCommentToContent } from './issueComments';
import {
getLinearIssuesByIds,
getLinearProjectTeamIds,
LINEAR_PAGE_SIZE,
type LinearIssue,
+ type LinearIssueComment,
type LinearIssueFilter,
+ listLinearIssueComments,
listLinearIssues,
} from './issues';
@@ -37,6 +41,11 @@ export const MAX_ISSUES_PER_SYNC = 10_000;
* the sync again picks up where the previous run stopped.
*/
export const MAX_TASKS_CREATED_PER_SYNC = 100;
+/**
+ * Closed tasks one sync catches up comments for. Each is marked once synced,
+ * so a long history of legacy links is worked through over the next runs.
+ */
+export const MAX_COMMENT_CATCH_UPS_PER_SYNC = 100;
/** Tries at creating one task when concurrent creates keep taking its identifier. */
const MAX_CREATE_ATTEMPTS = 5;
/** Skipped entries kept in a result, so a stored rule result stays small. */
@@ -201,7 +210,7 @@ export class LinearIssueSyncService {
async importIssues(
accessToken: string,
issueIds: string[],
- options: { targetProjectId?: string | null } = {},
+ options: { syncComments?: boolean; targetProjectId?: string | null } = {},
): Promise<LinearSyncResult> {
const issues = await getLinearIssuesByIds(accessToken, issueIds);
const result = emptyResult();
@@ -223,6 +232,13 @@ export class LinearIssueSyncService {
{ createClosed: true, targetProjectId: options.targetProjectId },
result,
);
+ if (options.syncComments) {
+ await this.syncComments(
+ accessToken,
+ issues.map((issue) => issue.id),
+ result,
+ );
+ }
return result;
}
@@ -236,11 +252,19 @@ export class LinearIssueSyncService {
* one does not see the issues before the cursor. With `noCreate`, every
* matching issue is read and linked tasks are reconciled, but no task is
* created; an unimported issue only marks the result `truncated`.
+ *
+ * With `syncComments`, the comments of every issue read are copied onto its
+ * task, so running again also fills in tasks imported without them.
*/
async syncByFilter(
accessToken: string,
filter: LinearIssueFilter,
- options: { noCreate?: boolean; startAfter?: string; targetProjectId?: string | null } = {},
+ options: {
+ noCreate?: boolean;
+ startAfter?: string;
+ syncComments?: boolean;
+ targetProjectId?: string | null;
+ } = {},
): Promise<LinearFilterSyncResult> {
const result: LinearFilterSyncResult = emptyResult();
const issues: LinearIssue[] = [];
@@ -281,6 +305,13 @@ export class LinearIssueSyncService {
},
result,
);
+ if (options.syncComments) {
+ await this.syncComments(
+ accessToken,
+ issues.map((issue) => issue.id),
+ result,
+ );
+ }
if (result.truncated) {
// Resume where the first issue left for later is, so none is skipped;
// past every page read when the cap was not what stopped this run.
@@ -309,17 +340,41 @@ export class LinearIssueSyncService {
.flat()
.filter((link) => !seen.has(link.externalId));
if (unseen.length > 0) {
- const open = await this.taskModel.findByIds(unseen.map((link) => link.taskId));
- const openTaskIds = new Set(
- open.filter((task) => !CLOSED_TASK_STATUSES.has(task.status)).map((task) => task.id),
+ const visible = await this.taskModel.findByIds(unseen.map((link) => link.taskId));
+ const closedTaskIds = new Set(
+ visible.filter((task) => CLOSED_TASK_STATUSES.has(task.status)).map((task) => task.id),
+ );
+ const visibleTaskIds = new Set(visible.map((task) => task.id));
+ const toCheck = unseen.filter(
+ (link) => visibleTaskIds.has(link.taskId) && !closedTaskIds.has(link.taskId),
);
- const toCheck = unseen.filter((link) => openTaskIds.has(link.taskId));
+ // Issues Linear closed: this run closes their tasks.
+ const closing: string[] = [];
if (toCheck.length > 0) {
const fetched = await getLinearIssuesByIds(
accessToken,
toCheck.map((link) => link.externalId),
);
await this.syncIssues(fetched, { closeOnly: true }, result);
+ for (const issue of fetched) {
+ if (CLOSED_STATE_TYPES.has(issue.state.type)) closing.push(issue.id);
+ }
+ }
+ if (options.syncComments) {
+ // The filter no longer reaches these issues, so their comments are
+ // read here: those being closed now, and closed tasks whose comments
+ // were never synced (imported before, or a failed read) — once, so a
+ // long tail of closed issues is not reread on every run. An open
+ // issue the filter misses (moved to another rule's project, say) is
+ // left to the rule that lists it.
+ const catchUp = unseen
+ .filter((link) => closedTaskIds.has(link.taskId) && !link.metadata?.commentsSynced)
+ .slice(0, MAX_COMMENT_CATCH_UPS_PER_SYNC);
+ await this.syncComments(
+ accessToken,
+ [...closing, ...catchUp.map((link) => link.externalId)],
+ result,
+ );
}
}
@@ -560,6 +615,108 @@ export class LinearIssueSyncService {
return skippedRunning ? undefined : updated;
}
+ /**
+ * Copy the Linear comments of these issues onto their tasks, oldest first,
+ * skipping those copied before. Only tasks the caller can see get comments;
+ * an issue never imported (skipped, or left for a later run) gets none yet.
+ * Comments are read a batch of issues at a time. A revoked token fails the
+ * run like reading issues does. Any other read failure (Linear throttling,
+ * say) stops reading for this run, and a failed write skips only its task;
+ * either way the tasks are reported `commentsFailed` and the next run
+ * retries them, while the task writes of this run still count.
+ */
+ private async syncComments(
+ accessToken: string,
+ issueIds: string[],
+ result: LinearSyncResult,
+ ): Promise<void> {
+ if (issueIds.length === 0) return;
+ const links = [...(await this.visibleLinks(issueIds)).values()];
+
+ for (let start = 0; start < links.length; start += LINEAR_PAGE_SIZE) {
+ const batch = links.slice(start, start + LINEAR_PAGE_SIZE);
+ let comments: LinearIssueComment[];
+ try {
+ comments = await listLinearIssueComments(
+ accessToken,
+ batch.map((link) => link.externalId),
+ );
+ } catch (error) {
+ if (error instanceof LinearApiError && error.status === 401) throw error;
+ log('read comments failed: %O', error);
+ // Further reads would most likely fail the same way.
+ for (const link of links.slice(start)) {
+ skip(result, link.externalIdentifier, 'commentsFailed');
+ }
+ return;
+ }
+
+ const byIssue = new Map<string, LinearIssueComment[]>();
+ for (const comment of comments) {
+ if (!comment.issueId) continue;
+ const list = byIssue.get(comment.issueId) ?? [];
+ list.push(comment);
+ byIssue.set(comment.issueId, list);
+ }
+
+ for (const link of batch) {
+ const issueComments = byIssue.get(link.externalId) ?? [];
+ const known = new Set(link.metadata?.syncedCommentIds ?? []);
+ const hasNew = issueComments.some((comment) => !known.has(comment.id));
+ if (!hasNew && link.metadata?.commentsSynced) continue;
+ try {
+ const added = await this.appendComments(link, issueComments);
+ if (added > 0) result.commentsImported = (result.commentsImported ?? 0) + added;
+ } catch (error) {
+ log('sync comments of %s failed: %O', link.externalIdentifier, error);
+ skip(result, link.externalIdentifier, 'commentsFailed');
+ }
+ }
+ }
+ }
+
+ /**
+ * Add the comments not copied yet and record them on the link in one
+ * transaction, under the task's row lock: a run cut off part-way never
+ * leaves a copied comment unrecorded, and two runs never copy the same one.
+ */
+ private async appendComments(
+ link: TaskExternalLinkWithTask,
+ comments: LinearIssueComment[],
+ ): Promise<number> {
+ return this.db.transaction(async (tx) => {
+ const tasks = new TaskModel(tx, this.userId, this.workspaceId);
+ if (!(await tasks.lockForUpdate(link.taskId))) return 0;
+ const linkModel = new TaskExternalLinkModel(tx, this.userId, this.workspaceId);
+ const [current] = await linkModel.findByExternalIds('linear', [link.externalId]);
+ if (!current || current.taskId !== link.taskId) return 0;
+
+ const known = new Set(current.metadata?.syncedCommentIds ?? []);
+ const fresh = comments.filter((comment) => !known.has(comment.id));
+ // Straight to the model: a bulk copy of history notifies no one, unlike
+ // a comment posted in LobeHub.
+ await tasks.addComments(
+ link.taskId,
+ fresh.map((comment) => {
+ // Linear's time, so the task's activity reads in the order it happened.
+ const createdAt = new Date(comment.createdAt);
+ return {
+ authorUserId: this.userId,
+ content: linearCommentToContent(comment),
+ createdAt,
+ updatedAt: createdAt,
+ userId: this.userId,
+ };
+ }),
+ );
+ await linkModel.recordSyncedComments(
+ current.id,
+ fresh.map((comment) => comment.id),
+ );
+ return fresh.length;
+ });
+ }
+
/** Links in this scope whose task the caller can still see. */
private async visibleLinks(externalIds: string[]) {
const links = await this.linkModel.findByExternalIds('linear', [...new Set(externalIds)]);
diff --git a/apps/server/src/services/linear/issues.ts b/apps/server/src/services/linear/issues.ts
index e0d7e6f1d63..f344335b324 100644
--- a/apps/server/src/services/linear/issues.ts
+++ b/apps/server/src/services/linear/issues.ts
@@ -186,3 +186,57 @@ export const getLinearIssuesByIds = async (
}
return issues;
};
+
+/** A comment on an issue, with what a sync copies onto the task. */
+export interface LinearIssueComment {
+ body: string;
+ /** An integration that posted it, possibly on someone's behalf. */
+ botActor?: { name?: string | null; userDisplayName?: string | null } | null;
+ createdAt: string;
+ /** Someone outside the organization, e.g. through a support integration. */
+ externalUser?: { name: string } | null;
+ id: string;
+ issueId?: string | null;
+ /** Set on a reply; the id of the comment it answers. */
+ parentId?: string | null;
+ url: string;
+ user?: { displayName: string; name: string } | null;
+}
+
+/**
+ * Every comment on the given issues, replies included, oldest first. Unknown or
+ * inaccessible issues have none.
+ */
+export const listLinearIssueComments = async (
+ accessToken: string,
+ issueIds: string[],
+): Promise<LinearIssueComment[]> => {
+ const comments: LinearIssueComment[] = [];
+ const ids = [...new Set(issueIds)];
+ for (let start = 0; start < ids.length; start += LINEAR_PAGE_SIZE) {
+ const batch = ids.slice(start, start + LINEAR_PAGE_SIZE);
+ let after: string | undefined;
+ do {
+ const data = await linearGraphql<{ comments: Connection<LinearIssueComment> }>(
+ accessToken,
+ `query LobeIssueComments($first: Int!, $after: String, $filter: CommentFilter) {
+ comments(first: $first, after: $after, filter: $filter, orderBy: createdAt) {
+ nodes {
+ id body url createdAt issueId parentId
+ user { displayName name }
+ externalUser { name }
+ botActor { name userDisplayName }
+ }
+ pageInfo { hasNextPage endCursor }
+ }
+ }`,
+ { after, filter: { issue: { id: { in: batch } } }, first: LINEAR_PAGE_SIZE },
+ );
+ comments.push(...data.comments.nodes);
+ after = data.comments.pageInfo.hasNextPage
+ ? (data.comments.pageInfo.endCursor ?? undefined)
+ : undefined;
+ } while (after);
+ }
+ return comments.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
+};
diff --git a/apps/server/src/services/linear/syncJob.ts b/apps/server/src/services/linear/syncJob.ts
index 5e7f28223ba..db73e150b87 100644
--- a/apps/server/src/services/linear/syncJob.ts
+++ b/apps/server/src/services/linear/syncJob.ts
@@ -51,8 +51,10 @@ export const mergeLinearSyncResults = (
{ resumed }: { resumed: boolean },
): LinearSyncResult => {
if (!previous) return latest;
+ const commentsImported = (previous.commentsImported ?? 0) + (latest.commentsImported ?? 0);
const written = {
closed: previous.closed + latest.closed,
+ ...(commentsImported ? { commentsImported } : {}),
created: previous.created + latest.created,
updated: previous.updated + latest.updated,
};
@@ -260,7 +262,10 @@ export class LinearSyncJobService {
if (!project) throw new LinearSyncJobError('unavailable');
const sync = new LinearIssueSyncService(this.db, this.userId, this.workspaceId);
- const options = { targetProjectId: metadata.projectId };
+ const options = {
+ syncComments: metadata.syncComments,
+ targetProjectId: metadata.projectId,
+ };
if (metadata.kind === 'issues') {
const token = await getLinearAccessToken(this.db, metadata.connectionId);
diff --git a/locales/en-US/integration.json b/locales/en-US/integration.json
index 776f05b2aa9..4ab83fa63b8 100644
--- a/locales/en-US/integration.json
+++ b/locales/en-US/integration.json
@@ -94,6 +94,7 @@
"linear.sync.job.runningIssues": "Syncing {{count}} issues…",
"linear.sync.job.runningRule": "Syncing everything the rule matches…",
"linear.sync.job.skipReason.closed": "Closed in Linear and never imported",
+ "linear.sync.job.skipReason.commentsFailed": "Task synced, but its comments could not be; the next sync retries them",
"linear.sync.job.skipReason.failed": "Could not be written; the next sync retries it",
"linear.sync.job.skipReason.missing": "No longer in Linear, or not visible to this connection",
"linear.sync.job.skipReason.running": "Task is running, so it was not closed",
@@ -120,6 +121,11 @@
"linear.sync.modal.saveRule": "Save as rule and sync all",
"linear.sync.modal.saveRuleHint": "Sync every issue matching these filters now, and keep the filters to sync again later",
"linear.sync.modal.title": "Import issues from {{account}}",
+ "linear.sync.options.importTitle": "Import options",
+ "linear.sync.options.syncComments": "Sync comments",
+ "linear.sync.options.syncCommentsDesc": "Copy each issue's Linear comments into the task's activity, keeping the author and time",
+ "linear.sync.options.syncCommentsRuleDesc": "Tasks already synced also get the comments they are missing",
+ "linear.sync.options.syncTitle": "Sync options",
"linear.sync.project.connect": "Connect Linear",
"linear.sync.project.description": "Turn Linear issues into tasks of this project, one by one or through a saved team or project rule. Syncing is one way: nothing in Linear is changed.",
"linear.sync.project.entry": "Sync from Linear",
@@ -127,6 +133,7 @@
"linear.sync.project.title": "Sync from Linear",
"linear.sync.projectHint": "To sync issues into a project, open the project and go to Settings → Advanced.",
"linear.sync.result.closed": "{{count}} closed",
+ "linear.sync.result.commentsImported": "{{count}} comments added",
"linear.sync.result.created": "{{count}} created",
"linear.sync.result.keptLocalEdits": "{{count}} kept local edits",
"linear.sync.result.skipped": "{{count}} skipped",
diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.json
index b05e0239fb6..3e1c908d6b7 100644
--- a/locales/zh-CN/integration.json
+++ b/locales/zh-CN/integration.json
@@ -94,6 +94,7 @@
"linear.sync.job.runningIssues": "正在同步 {{count}} 个 Issue…",
"linear.sync.job.runningRule": "正在同步规则匹配的全部 Issue…",
"linear.sync.job.skipReason.closed": "在 Linear 中已关闭,未导入",
+ "linear.sync.job.skipReason.commentsFailed": "任务已同步,但评论未能同步,下次同步会重试",
"linear.sync.job.skipReason.failed": "写入失败,下次同步会重试",
"linear.sync.job.skipReason.missing": "Linear 中已不存在,或当前连接无权访问",
"linear.sync.job.skipReason.running": "任务正在运行,未关闭",
@@ -120,6 +121,11 @@
"linear.sync.modal.saveRule": "保存为规则并全部同步",
"linear.sync.modal.saveRuleHint": "立即同步符合当前筛选的所有 Issue,并保存筛选条件以便之后再次同步",
"linear.sync.modal.title": "从 {{account}} 导入 Issue",
+ "linear.sync.options.importTitle": "导入选项",
+ "linear.sync.options.syncComments": "同步评论",
+ "linear.sync.options.syncCommentsDesc": "把 Issue 下的 Linear 评论导入到任务活动,保留原作者和时间",
+ "linear.sync.options.syncCommentsRuleDesc": "已同步的任务也会补上缺少的评论",
+ "linear.sync.options.syncTitle": "同步选项",
"linear.sync.project.connect": "连接 Linear",
"linear.sync.project.description": "把 Linear Issue 同步为本项目的任务,可以逐个导入,也可以按团队或 Linear 项目保存规则。同步是单向的,不会修改 Linear。",
"linear.sync.project.entry": "从 Linear 同步",
@@ -127,6 +133,7 @@
"linear.sync.project.title": "从 Linear 同步",
"linear.sync.projectHint": "要把 Issue 同步到项目,请打开项目,进入「设置 → 高级设置」。",
"linear.sync.result.closed": "关闭 {{count}} 个",
+ "linear.sync.result.commentsImported": "新增评论 {{count}} 条",
"linear.sync.result.created": "新建 {{count}} 个",
"linear.sync.result.keptLocalEdits": "{{count}} 个保留本地修改",
"linear.sync.result.skipped": "跳过 {{count}} 个",
diff --git a/packages/database/src/models/__tests__/task.addComments.test.ts b/packages/database/src/models/__tests__/task.addComments.test.ts
new file mode 100644
index 00000000000..af9cac9deba
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.addComments.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment node
+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';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-add-comments-user';
+const otherUserId = 'task-add-comments-other';
+const workspaceId = 'task-add-comments-ws';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('TaskModel.addComments', () => {
+ it('adds every row to the task with its visibility, in one call', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Imported', visibility: 'private' });
+ const base = Date.parse('2026-01-01T00:00:00.000Z');
+ const rows = Array.from({ length: 501 }, (_, index) => {
+ const createdAt = new Date(base + index * 1000);
+ return {
+ authorUserId: userId,
+ content: `Comment ${index}`,
+ createdAt,
+ updatedAt: createdAt,
+ userId,
+ };
+ });
+
+ const added = await model.addComments(task.id, rows);
+
+ expect(added).toHaveLength(501);
+ const stored = await model.getComments(task.id);
+ expect(stored).toHaveLength(501);
+ expect(stored[0]).toMatchObject({
+ content: 'Comment 0',
+ taskId: task.id,
+ visibility: 'private',
+ });
+ expect(stored.at(-1)?.content).toBe('Comment 500');
+ });
+
+ it('stamps the workspace and adds nothing for no rows', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId })
+ .onConflictDoNothing();
+ const model = new TaskModel(serverDB, userId, workspaceId);
+ const task = await model.create({ instruction: 'Shared' });
+
+ expect(await model.addComments(task.id, [])).toEqual([]);
+ const [comment] = await model.addComments(task.id, [
+ { authorUserId: userId, content: 'Hello', userId },
+ ]);
+ expect(comment).toMatchObject({ taskId: task.id, workspaceId });
+ });
+
+ it('refuses a task outside the caller scope', async () => {
+ const task = await new TaskModel(serverDB, userId).create({ instruction: 'Mine' });
+
+ await expect(
+ new TaskModel(serverDB, otherUserId).addComments(task.id, [
+ { authorUserId: otherUserId, content: 'Sneaky', userId: otherUserId },
+ ]),
+ ).rejects.toThrow('Task not found');
+ expect(await new TaskModel(serverDB, userId).getComments(task.id)).toHaveLength(0);
+ });
+});
diff --git a/packages/database/src/models/__tests__/task.surface.test.ts b/packages/database/src/models/__tests__/task.surface.test.ts
index 5bb8cf4f206..220dc49f8d2 100644
--- a/packages/database/src/models/__tests__/task.surface.test.ts
+++ b/packages/database/src/models/__tests__/task.surface.test.ts
@@ -47,6 +47,7 @@ describe('TaskModel public surface', () => {
'addActivities',
'addActivity',
'addComment',
+ 'addComments',
'addDependency',
'areAllDependenciesCompleted',
'areAllSubtasksCompleted',
diff --git a/packages/database/src/models/__tests__/taskExternalLink.test.ts b/packages/database/src/models/__tests__/taskExternalLink.test.ts
index 942571d5016..7d52a5b63a1 100644
--- a/packages/database/src/models/__tests__/taskExternalLink.test.ts
+++ b/packages/database/src/models/__tests__/taskExternalLink.test.ts
@@ -70,4 +70,63 @@ describe('TaskExternalLinkModel', () => {
).toEqual([]);
expect(await shared.findByContainer('linear', 'team-1')).toHaveLength(1);
});
+
+ it('records synced comments and keeps them when display metadata is replaced', async () => {
+ const model = new TaskExternalLinkModel(db, userId);
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ const created = await model.create({
+ ...link(task.id),
+ metadata: { assigneeName: 'Ada', stateName: 'Todo' },
+ });
+
+ await model.recordSyncedComments(created.id, ['c1', 'c2']);
+ await model.recordSyncedComments(created.id, ['c3']);
+ // A display refresh built from a read taken before the comments were recorded.
+ await model.update(created.id, { metadata: { stateName: 'Done' } });
+
+ const [current] = await model.findByExternalIds('linear', ['issue-1']);
+ expect(current.metadata).toEqual({
+ commentsSynced: true,
+ stateName: 'Done',
+ syncedCommentIds: ['c1', 'c2', 'c3'],
+ });
+ });
+
+ it('marks an issue without comments as synced', async () => {
+ const model = new TaskExternalLinkModel(db, userId);
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ const created = await model.create({ ...link(task.id), metadata: { stateName: 'Todo' } });
+
+ await model.recordSyncedComments(created.id, []);
+
+ const [current] = await model.findByExternalIds('linear', ['issue-1']);
+ expect(current.metadata).toEqual({
+ commentsSynced: true,
+ stateName: 'Todo',
+ syncedCommentIds: [],
+ });
+ });
+
+ it('replaces display metadata of a link without synced comments as is', async () => {
+ const model = new TaskExternalLinkModel(db, userId);
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ const created = await model.create({ ...link(task.id), metadata: { assigneeName: 'Ada' } });
+
+ await model.update(created.id, { metadata: { stateName: 'Done' } });
+
+ const [current] = await model.findByExternalIds('linear', ['issue-1']);
+ expect(current.metadata).toEqual({ stateName: 'Done' });
+ });
+
+ it('does not record comment ids on a link outside the scope', async () => {
+ const task = await new TaskModel(db, userId).create({ instruction: 'one' });
+ const created = await new TaskExternalLinkModel(db, userId).create(link(task.id));
+
+ await new TaskExternalLinkModel(db, otherUserId).recordSyncedComments(created.id, ['c1']);
+
+ const [current] = await new TaskExternalLinkModel(db, userId).findByExternalIds('linear', [
+ 'issue-1',
+ ]);
+ expect(current.metadata).toEqual({});
+ });
});
diff --git a/packages/database/src/models/task/comments.ts b/packages/database/src/models/task/comments.ts
index 2d4edb93b26..5e233e5cb56 100644
--- a/packages/database/src/models/task/comments.ts
+++ b/packages/database/src/models/task/comments.ts
@@ -19,6 +19,36 @@ export const addComment = async (
return comment;
};
+/** Rows per insert: well under Postgres' bind-parameter limit. */
+const COMMENT_INSERT_CHUNK = 500;
+
+/**
+ * Add many comments to one task: its visibility is read once and the rows go
+ * in as batched inserts, so a long imported history is a few round trips.
+ */
+export const addComments = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ rows: Omit<NewTaskComment, 'id' | 'taskId'>[],
+): Promise<TaskCommentItem[]> => {
+ if (rows.length === 0) return [];
+ const visibility = await getTaskVisibility(ctx, taskId);
+ const added: TaskCommentItem[] = [];
+ for (let start = 0; start < rows.length; start += COMMENT_INSERT_CHUNK) {
+ added.push(
+ ...(await ctx.db
+ .insert(taskComments)
+ .values(
+ rows
+ .slice(start, start + COMMENT_INSERT_CHUNK)
+ .map((row) => ({ ...row, taskId, visibility, workspaceId: ctx.workspaceId ?? null })),
+ )
+ .returning()),
+ );
+ }
+ return added;
+};
+
export const findCommentById = async (
ctx: TaskModelContext,
id: string,
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index f304d14446e..cc9fe5a0887 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -590,6 +590,13 @@ export class TaskModel {
return comments.addComment(this.ctx, data);
}
+ async addComments(
+ taskId: string,
+ rows: Omit<NewTaskComment, 'id' | 'taskId'>[],
+ ): Promise<TaskCommentItem[]> {
+ return comments.addComments(this.ctx, taskId, rows);
+ }
+
async findCommentById(id: string): Promise<TaskCommentItem | undefined> {
return comments.findCommentById(this.ctx, id);
}
diff --git a/packages/database/src/models/taskExternalLink.ts b/packages/database/src/models/taskExternalLink.ts
index 279e5574f67..d45e00f8545 100644
--- a/packages/database/src/models/taskExternalLink.ts
+++ b/packages/database/src/models/taskExternalLink.ts
@@ -1,5 +1,5 @@
import type { TaskExternalProvider } from '@lobechat/types';
-import { and, eq, inArray, isNull } from 'drizzle-orm';
+import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
import type { NewTaskExternalLink, TaskExternalLinkItem } from '../schemas';
import { taskExternalLinks, tasks } from '../schemas';
@@ -87,9 +87,36 @@ export class TaskExternalLinkModel {
>
>,
): Promise<void> {
+ const { metadata, ...rest } = data;
await this.db
.update(taskExternalLinks)
- .set({ ...data, lastSyncedAt: new Date(), updatedAt: new Date() })
+ .set({
+ ...rest,
+ // Display metadata is replaced, but the comment bookkeeping a sync
+ // recorded is kept: read and written in the row update itself, so a
+ // refresh working from an older read never drops what was recorded since.
+ ...(metadata
+ ? {
+ metadata: sql`jsonb_strip_nulls(jsonb_build_object('commentsSynced', ${taskExternalLinks.metadata} -> 'commentsSynced', 'syncedCommentIds', ${taskExternalLinks.metadata} -> 'syncedCommentIds')) || ${JSON.stringify(metadata)}::jsonb`,
+ }
+ : {}),
+ lastSyncedAt: new Date(),
+ updatedAt: new Date(),
+ })
+ .where(and(this.scope(), eq(taskExternalLinks.id, id)));
+ }
+
+ /**
+ * Record that the issue's comments were synced, adding the ids of those
+ * copied onto the link's task (possibly none) so they are not copied again.
+ */
+ async recordSyncedComments(id: string, commentIds: string[]): Promise<void> {
+ await this.db
+ .update(taskExternalLinks)
+ .set({
+ metadata: sql`jsonb_set(jsonb_set(${taskExternalLinks.metadata}, '{syncedCommentIds}', coalesce(${taskExternalLinks.metadata} -> 'syncedCommentIds', '[]'::jsonb) || ${JSON.stringify(commentIds)}::jsonb), '{commentsSynced}', 'true'::jsonb)`,
+ updatedAt: new Date(),
+ })
.where(and(this.scope(), eq(taskExternalLinks.id, id)));
}
diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.ts
index d49d72fab02..5ad701e7cf1 100644
--- a/packages/locales/src/default/integration.ts
+++ b/packages/locales/src/default/integration.ts
@@ -119,6 +119,8 @@ export default {
'linear.sync.job.runningIssues': 'Syncing {{count}} issues…',
'linear.sync.job.runningRule': 'Syncing everything the rule matches…',
'linear.sync.job.skipReason.closed': 'Closed in Linear and never imported',
+ 'linear.sync.job.skipReason.commentsFailed':
+ 'Task synced, but its comments could not be; the next sync retries them',
'linear.sync.job.skipReason.failed': 'Could not be written; the next sync retries it',
'linear.sync.job.skipReason.missing': 'No longer in Linear, or not visible to this connection',
'linear.sync.job.skipReason.running': 'Task is running, so it was not closed',
@@ -146,6 +148,13 @@ export default {
'linear.sync.modal.saveRuleHint':
'Sync every issue matching these filters now, and keep the filters to sync again later',
'linear.sync.modal.title': 'Import issues from {{account}}',
+ 'linear.sync.options.importTitle': 'Import options',
+ 'linear.sync.options.syncComments': 'Sync comments',
+ 'linear.sync.options.syncCommentsDesc':
+ "Copy each issue's Linear comments into the task's activity, keeping the author and time",
+ 'linear.sync.options.syncCommentsRuleDesc':
+ 'Tasks already synced also get the comments they are missing',
+ 'linear.sync.options.syncTitle': 'Sync options',
'linear.sync.project.connect': 'Connect Linear',
'linear.sync.project.description':
'Turn Linear issues into tasks of this project, one by one or through a saved team or project rule. Syncing is one way: nothing in Linear is changed.',
@@ -155,6 +164,7 @@ export default {
'linear.sync.projectHint':
'To sync issues into a project, open the project and go to Settings → Advanced.',
'linear.sync.result.closed': '{{count}} closed',
+ 'linear.sync.result.commentsImported': '{{count}} comments added',
'linear.sync.result.created': '{{count}} created',
'linear.sync.result.keptLocalEdits': '{{count}} kept local edits',
'linear.sync.result.skipped': '{{count}} skipped',
diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.ts
index 79c14111e07..8ecc36c695c 100644
--- a/packages/types/src/linear.ts
+++ b/packages/types/src/linear.ts
@@ -68,10 +68,21 @@ export type TaskExternalProvider = 'linear';
/** Facts about the linked Linear issue kept on the link row, for display only. */
export interface LinearIssueLinkMetadata {
assigneeName?: string;
+ /**
+ * The issue's comments were read and copied at least once. A closed task
+ * whose issue left a rule's filter is caught up only until this is set.
+ * Sync bookkeeping, not display: a display refresh keeps it.
+ */
+ commentsSynced?: boolean;
labels?: string[];
projectName?: string;
stateName?: string;
stateType?: LinearIssueStateType;
+ /**
+ * Linear comments already copied onto the task, so syncing again adds only
+ * new ones. Sync bookkeeping, not display: a display refresh keeps it.
+ */
+ syncedCommentIds?: string[];
teamKey?: string;
}
@@ -118,12 +129,16 @@ export type LinearSyncSkipReason =
| 'closed'
/** Writing the task failed; the next sync retries it. */
| 'failed'
+ /** The task was synced, but its Linear comments were not; the next sync retries them. */
+ | 'commentsFailed'
/** Picked for import, but Linear no longer returns it (deleted, or not visible). */
| 'missing';
export interface LinearSyncResult {
/** Tasks closed because their issue was completed or canceled in Linear. */
closed: number;
+ /** Linear comments copied onto tasks as task comments. Absent in older results. */
+ commentsImported?: number;
created: number;
/** Tasks edited in LobeHub, so their name, instruction and priority were kept. */
keptLocalEdits: number;
@@ -190,6 +205,8 @@ export interface LinearSyncJobMetadata {
rounds?: number;
/** The saved rule being run (`kind: 'rule'`). */
ruleId?: string;
+ /** Copy each issue's Linear comments onto its task as task comments. */
+ syncComments?: boolean;
}
export interface LinearSyncJobView {
diff --git a/src/features/Projects/LinearSync/ImportIssuesContent.tsx b/src/features/Projects/LinearSync/ImportIssuesContent.tsx
index ccafe2efde7..6c7031ef54b 100644
--- a/src/features/Projects/LinearSync/ImportIssuesContent.tsx
+++ b/src/features/Projects/LinearSync/ImportIssuesContent.tsx
@@ -10,6 +10,7 @@ import useSWR from 'swr';
import { linearKeys } from '@/features/Integrations/Linear/swrKeys';
import { linearService } from '@/services/linear';
+import ImportOptions from './ImportOptions';
import IssueList from './IssueList';
import RunStep from './RunStep';
import ScopeStep from './ScopeStep';
@@ -36,6 +37,8 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
const [step, setStep] = useState<Step>('scope');
const [filter, setFilter] = useState<LinearImportFilter>(initialImportFilter);
const [selected, setSelected] = useState<Set<string>>(() => new Set());
+ // Comments carry much of an issue's context, so they come along unless unchecked.
+ const [syncComments, setSyncComments] = useState(true);
const [starting, setStarting] = useState<'import' | 'rule' | null>(null);
const [jobId, setJobId] = useState<string>();
// Shown as the running title until the job loads, so a single import never reads as a rule sync.
@@ -98,6 +101,7 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
connectionId: connection.id,
issueIds: [...selected],
projectId,
+ syncComments,
}),
);
@@ -117,7 +121,7 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
ruleId = rule.id;
setSavedRuleId(rule.id);
}
- return linearService.startRuleSync(ruleId);
+ return linearService.startRuleSync(ruleId, { syncComments });
});
const leaveRunning = () => {
@@ -227,6 +231,11 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
}}
onSelectionChange={changeSelection}
/>
+ <ImportOptions
+ disabled={starting !== null}
+ syncComments={syncComments}
+ onSyncCommentsChange={setSyncComments}
+ />
</Flexbox>
) : null}
diff --git a/src/features/Projects/LinearSync/ImportOptions.tsx b/src/features/Projects/LinearSync/ImportOptions.tsx
new file mode 100644
index 00000000000..375ef518d18
--- /dev/null
+++ b/src/features/Projects/LinearSync/ImportOptions.tsx
@@ -0,0 +1,62 @@
+'use client';
+
+import { Checkbox, Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = stylex.create({
+ group: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderRadius: cssVar.borderRadiusLG,
+ paddingBlock: 12,
+ paddingInline: 12,
+ },
+ option: {
+ cursor: 'pointer',
+ },
+});
+
+interface ImportOptionsProps {
+ disabled?: boolean;
+ onSyncCommentsChange: (checked: boolean) => void;
+ syncComments: boolean;
+}
+
+/** What an import brings along besides the issues themselves. */
+const ImportOptions = memo<ImportOptionsProps>(
+ ({ disabled, onSyncCommentsChange, syncComments }) => {
+ const { t } = useTranslation('integration');
+
+ return (
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('linear.sync.options.importTitle')}
+ </Text>
+ <div {...stylex.props(styles.group)}>
+ <label {...stylex.props(styles.option)}>
+ <Flexbox horizontal align={'flex-start'} gap={8}>
+ <Checkbox
+ checked={syncComments}
+ disabled={disabled}
+ style={{ marginBlockStart: 2 }}
+ onChange={onSyncCommentsChange}
+ />
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text>{t('linear.sync.options.syncComments')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('linear.sync.options.syncCommentsDesc')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ </label>
+ </div>
+ </Flexbox>
+ );
+ },
+);
+
+ImportOptions.displayName = 'LinearImportOptions';
+
+export default ImportOptions;
diff --git a/src/features/Projects/LinearSync/SyncRules.tsx b/src/features/Projects/LinearSync/SyncRules.tsx
index 7831f708eb1..4b7215ab836 100644
--- a/src/features/Projects/LinearSync/SyncRules.tsx
+++ b/src/features/Projects/LinearSync/SyncRules.tsx
@@ -1,7 +1,16 @@
'use client';
import type { LinearConnectionView, LinearSyncJobView, LinearSyncRuleView } from '@lobechat/types';
-import { ActionIcon, Button, confirmModal, Flexbox, Icon, Text, toast } from '@lobehub/ui';
+import {
+ ActionIcon,
+ confirmModal,
+ type DropdownItem,
+ Flexbox,
+ Icon,
+ SplitButton,
+ Text,
+ toast,
+} from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { RefreshCwIcon, Trash2Icon } from 'lucide-react';
@@ -60,6 +69,27 @@ const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, proje
const isViewer = useIsWorkspaceViewer();
const viewerHint = isViewer ? t('linear.sync.viewerDisabled') : undefined;
const [starting, setStarting] = useState<string | null>(null);
+ // Tucked into each rule's sync menu; applies to the next run of any rule, and
+ // re-running with it on fills in the comments already-synced tasks lack.
+ const [syncComments, setSyncComments] = useState(true);
+ const optionItems: DropdownItem[] = [
+ {
+ children: [
+ {
+ checked: syncComments,
+ closeOnClick: false,
+ desc: t('linear.sync.options.syncCommentsRuleDesc'),
+ key: 'syncComments',
+ label: t('linear.sync.options.syncComments'),
+ onCheckedChange: setSyncComments,
+ type: 'checkbox',
+ },
+ ],
+ key: 'options',
+ label: t('linear.sync.options.syncTitle'),
+ type: 'group',
+ },
+ ];
const runningRuleIds = new Set(
jobs.filter(isActiveLinearSyncJob).flatMap((job) => (job.ruleId ? [job.ruleId] : [])),
);
@@ -83,7 +113,7 @@ const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, proje
const runRule = async (rule: LinearSyncRuleView) => {
setStarting(rule.id);
try {
- await linearService.startRuleSync(rule.id);
+ await linearService.startRuleSync(rule.id, { syncComments });
onJobStarted();
} catch (error) {
toast.error(linearSyncErrorMessage(error, t));
@@ -144,20 +174,24 @@ const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, proje
].join(' · ')}
</Text>
</Flexbox>
- <Button
+ <SplitButton
disabled={isViewer || disconnected}
- icon={<Icon icon={RefreshCwIcon} />}
loading={starting === rule.id || runningRuleIds.has(rule.id)}
size={'small'}
- title={
- viewerHint ?? (disconnected ? t('linear.sync.rules.disconnected') : undefined)
- }
- onClick={() => runRule(rule)}
>
- {runningRuleIds.has(rule.id)
- ? t('linear.sync.rules.running')
- : t('linear.sync.rules.run')}
- </Button>
+ <SplitButton.Main
+ icon={<Icon icon={RefreshCwIcon} />}
+ title={
+ viewerHint ?? (disconnected ? t('linear.sync.rules.disconnected') : undefined)
+ }
+ onClick={() => runRule(rule)}
+ >
+ {runningRuleIds.has(rule.id)
+ ? t('linear.sync.rules.running')
+ : t('linear.sync.rules.run')}
+ </SplitButton.Main>
+ <SplitButton.Menu items={optionItems} placement={'bottomRight'} />
+ </SplitButton>
<ActionIcon
disabled={isViewer || runningRuleIds.has(rule.id)}
icon={Trash2Icon}
diff --git a/src/features/Projects/LinearSync/utils.test.ts b/src/features/Projects/LinearSync/utils.test.ts
index 328fa06c216..442ea9562e3 100644
--- a/src/features/Projects/LinearSync/utils.test.ts
+++ b/src/features/Projects/LinearSync/utils.test.ts
@@ -42,6 +42,15 @@ describe('formatLinearSyncResult', () => {
);
});
+ it('counts comments copied from Linear', () => {
+ expect(formatLinearSyncResult(result({ commentsImported: 3, updated: 1 }), t)).toBe(
+ 'linear.sync.result.updated:1 · linear.sync.result.commentsImported:3',
+ );
+ expect(formatLinearSyncResult(result({ commentsImported: 2 }), t)).toBe(
+ 'linear.sync.result.commentsImported:2',
+ );
+ });
+
it('counts skipped issues past the stored list', () => {
expect(
formatLinearSyncResult(
diff --git a/src/features/Projects/LinearSync/utils.ts b/src/features/Projects/LinearSync/utils.ts
index 30eb22ca7e7..0cbc0169bb6 100644
--- a/src/features/Projects/LinearSync/utils.ts
+++ b/src/features/Projects/LinearSync/utils.ts
@@ -24,6 +24,8 @@ export const formatLinearSyncResult = (
result.created && t('linear.sync.result.created', { count: result.created }),
result.updated && t('linear.sync.result.updated', { count: result.updated }),
result.closed && t('linear.sync.result.closed', { count: result.closed }),
+ result.commentsImported &&
+ t('linear.sync.result.commentsImported', { count: result.commentsImported }),
result.keptLocalEdits &&
t('linear.sync.result.keptLocalEdits', { count: result.keptLocalEdits }),
skipped && t('linear.sync.result.skipped', { count: skipped }),
diff --git a/src/services/linear.ts b/src/services/linear.ts
index e86d2ddaca3..13f180aab94 100644
--- a/src/services/linear.ts
+++ b/src/services/linear.ts
@@ -28,8 +28,12 @@ class LinearService {
lambdaClient.linear.listIssues.query(params);
/** Starts a background import; returns the job id. */
- startImport = async (params: { connectionId: string; issueIds: string[]; projectId: string }) =>
- lambdaClient.linear.startImport.mutate(params);
+ startImport = async (params: {
+ connectionId: string;
+ issueIds: string[];
+ projectId: string;
+ syncComments?: boolean;
+ }) => lambdaClient.linear.startImport.mutate(params);
cancelSync = async (projectId: string, jobId: string) =>
lambdaClient.linear.cancelSync.mutate({ jobId, projectId });
@@ -50,7 +54,8 @@ class LinearService {
deleteSyncRule = async (ruleId: string) => lambdaClient.linear.deleteSyncRule.mutate({ ruleId });
/** Starts a background run of a saved rule; returns the job id. */
- startRuleSync = async (ruleId: string) => lambdaClient.linear.startRuleSync.mutate({ ruleId });
+ startRuleSync = async (ruleId: string, options: { syncComments?: boolean } = {}) =>
+ lambdaClient.linear.startRuleSync.mutate({ ruleId, ...options });
}
export const linearService = new LinearService();