🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(linear): rule sync keeps going in the background until every issue is in (#22050)
Rdmclin2a8c383abbb5d
diff --git a/apps/server/src/routers/async/linear.ts b/apps/server/src/routers/async/linear.tsindex e92810dcf21..d5d41d382d4 100644--- a/apps/server/src/routers/async/linear.ts+++ b/apps/server/src/routers/async/linear.ts@@ -1,6 +1,7 @@import { z } from 'zod';import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';+import { continueLinearRuleSyncJob } from '@/server/services/linear/startSyncJob';import { LinearSyncJobService } from '@/server/services/linear/syncJob';/** Background Linear issue syncs, queued by the lambda `linear` router. */@@ -8,7 +9,11 @@ export const linearRouter = router({runSync: asyncAuthedProcedure.input(z.object({ taskId: z.string().uuid(), workspaceId: z.string().optional() })).mutation(async ({ ctx, input }) => {- await new LinearSyncJobService(ctx.serverDB, ctx.userId, input.workspaceId).run(input.taskId);+ const { workspaceId } = input;+ // A rule run that hits its per-round cap is handed back here for the next round.+ await new LinearSyncJobService(ctx.serverDB, ctx.userId, workspaceId, (taskId, metadata) =>+ continueLinearRuleSyncJob(ctx.serverDB, ctx.userId, workspaceId, taskId, metadata),+ ).run(input.taskId);return { ok: true };}),});diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.tsindex 846e9a5de5b..b0164128e70 100644--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts@@ -4,7 +4,7 @@ import { TRPCClientError } from '@trpc/client';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { LinearConnectionModel } from '@/database/models/linear';+import { LinearConnectionModel, LinearSyncRuleModel } from '@/database/models/linear';import {asyncTasks,linearConnections,@@ -14,7 +14,8 @@ import {workspaceMembers,workspaces,} from '@/database/schemas';-import { LinearSyncJobService } from '@/server/services/linear/syncJob';+import { continueLinearRuleSyncJob } from '@/server/services/linear/startSyncJob';+import { LINEAR_SYNC_MAX_ROUNDS, LinearSyncJobService } from '@/server/services/linear/syncJob';import { linearRouter } from '../linear';@@ -60,6 +61,7 @@ vi.mock('@/server/services/linear/issueSync', () => ({LinearIssueSyncService: vi.fn().mockImplementation(function () {return { importIssues: mocks.importIssues, syncByFilter: mocks.syncByFilter };}),+ MAX_SKIPPED_ENTRIES: 100,}));// The background half runs in the async router; here only the hand-off is seen.vi.mock('@/server/routers/async', () => ({@@ -257,6 +259,309 @@ describe('linearRouter', () => {expect(saved.lastRunAt).toBeInstanceOf(Date);});+ describe('when a rule matches more issues than one round creates', () => {+ const round = (+ created: number,+ truncated: boolean,+ resumeAfter?: string,+ ): typeof syncResult & Record<string, unknown> => ({+ ...syncResult,+ created,+ resumeAfter,+ skipped: [{ identifier: `ENG-${created}`, reason: 'closed' as const }],+ skippedCount: 1,+ truncated,+ unchanged: 7,+ updated: 1,+ });++ const startRule = async () => {+ const connection = await connect({ userId });+ mocks.getToken.mockResolvedValue('token');+ mocks.runSync.mockResolvedValue({ ok: true });+ const rule = await caller({ userId }).createSyncRule({+ connectionId: connection.id,+ projectId,+ stateTypes: ['unstarted'],+ teamId: 'team-1',+ teamName: 'Engineering',+ });+ const { id } = await caller({ userId }).startRuleSync({ ruleId: rule.id });+ return { id, rule };+ };++ /** The service as the async router builds it, able to queue the next round. */+ const routerService = () =>+ new LinearSyncJobService(serverDB, userId, undefined, (taskId, metadata) =>+ continueLinearRuleSyncJob(serverDB, userId, undefined, taskId, metadata),+ );++ const settle = async () => {+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setImmediate(resolve));+ };++ /** Play the async router: run each hand-off until no new one is queued. */+ const drainHandOffs = async () => {+ const service = routerService();+ for (let handled = 0; handled < mocks.runSync.mock.calls.length; handled++) {+ await service.run(mocks.runSync.mock.calls[handled][0].taskId);+ await settle();+ }+ };++ const startAfterOfCalls = () =>+ mocks.syncByFilter.mock.calls.map(([, , options]) => options.startAfter);++ it('keeps going in the background as one run, reading on from where each round stopped', async () => {+ mocks.syncByFilter+ .mockResolvedValueOnce(round(100, true, '100'))+ .mockResolvedValueOnce(round(100, true, '200'))+ .mockResolvedValueOnce(round(42, false))+ // The closing sweep from the start finds nothing new.+ .mockResolvedValueOnce(round(0, false));+ const { id, rule } = await startRule();++ await routerService().run(id);+ await settle();++ // Queued again by itself, with the total so far; a click on Sync joins it.+ expect(mocks.runSync).toHaveBeenCalledTimes(2);+ expect(mocks.runSync).toHaveBeenLastCalledWith({ taskId: id, workspaceId: undefined });+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: null, id, result: { created: 100, truncated: true }, status: 'pending' },+ ]);+ expect(await caller({ userId }).startRuleSync({ ruleId: rule.id })).toEqual({ id });++ await drainHandOffs();++ // Each round resumes at the cursor the previous one returned, then one+ // pass from the start picks up stragglers and closes what Linear closed.+ expect(startAfterOfCalls()).toEqual([undefined, '100', '200', undefined]);+ const jobs = await caller({ userId }).listSyncJobs({ projectId });+ expect(jobs).toHaveLength(1);+ expect(jobs[0]).toMatchObject({+ error: null,+ id,+ // Writes add up; what the final full pass looked at stands for the run.+ result: { created: 242, skippedCount: 1, truncated: false, unchanged: 7, updated: 4 },+ status: 'success',+ });+ expect(jobs[0].result).not.toHaveProperty('resumeAfter');+ const [saved] = await caller({ userId }).listSyncRules({ projectId });+ expect(saved.lastResult).toMatchObject({ created: 242, truncated: false });+ });++ it('stops when a round neither creates nor moves on, and asks to run again', async () => {+ mocks.syncByFilter+ .mockResolvedValueOnce(round(100, true, '100'))+ .mockResolvedValueOnce(round(0, true, '100'));+ const { id } = await startRule();++ await drainHandOffs();++ expect(mocks.syncByFilter).toHaveBeenCalledTimes(2);+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { id, result: { created: 100, truncated: true }, status: 'success' },+ ]);+ });++ it(`stops creating after ${LINEAR_SYNC_MAX_ROUNDS} rounds, but still takes the closing pass`, async () => {+ let page = 0;+ mocks.syncByFilter.mockImplementation(async (_token, _filter, options) => {+ // The pass from the start finds more than one round can create.+ if (!options.startAfter && page > 0) return round(0, true, '100');+ page += 1;+ return round(100, true, String(page * 100));+ });+ const { id } = await startRule();++ await drainHandOffs();++ expect(mocks.syncByFilter).toHaveBeenCalledTimes(LINEAR_SYNC_MAX_ROUNDS + 1);+ expect(startAfterOfCalls().at(-1)).toBeUndefined();+ // Past the cap the closing pass creates nothing.+ expect(mocks.syncByFilter.mock.calls.at(-1)![2]).toMatchObject({ noCreate: true });+ expect(mocks.syncByFilter.mock.calls.at(-2)![2].noCreate).toBeUndefined();+ // Issues remain, so the run asks to be run again.+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ {+ id,+ result: { created: LINEAR_SYNC_MAX_ROUNDS * 100, truncated: true },+ status: 'success',+ },+ ]);+ });++ it('still runs the closing pass when the last allowed round reads to the end', async () => {+ let page = 0;+ mocks.syncByFilter.mockImplementation(async (_token, _filter, options) => {+ if (!options.startAfter && page > 0) return round(0, false);+ page += 1;+ return page < LINEAR_SYNC_MAX_ROUNDS+ ? round(100, true, String(page * 100))+ : round(100, false);+ });+ const { id } = await startRule();++ await drainHandOffs();++ expect(mocks.syncByFilter).toHaveBeenCalledTimes(LINEAR_SYNC_MAX_ROUNDS + 1);+ expect(startAfterOfCalls().at(-1)).toBeUndefined();+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ {+ id,+ result: { created: LINEAR_SYNC_MAX_ROUNDS * 100, truncated: false },+ status: 'success',+ },+ ]);+ });++ it("keeps the rule's last finished run until this one finishes", async () => {+ mocks.syncByFilter+ .mockResolvedValueOnce(round(100, true, '100'))+ .mockResolvedValueOnce(round(5, false))+ .mockResolvedValueOnce(round(0, false));+ const { id, rule } = await startRule();++ await routerService().run(id);+ await settle();+ const [during] = await caller({ userId }).listSyncRules({ projectId });+ expect(during).toMatchObject({ lastResult: null, lastRunAt: null });++ await drainHandOffs();+ const [after] = await caller({ userId }).listSyncRules({ projectId });+ expect(after).toMatchObject({+ id: rule.id,+ lastResult: { created: 105, truncated: false },+ });+ });++ it("does not record a stopped run as the rule's last run", async () => {+ mocks.syncByFilter.mockResolvedValue(round(100, true, '100'));+ const { id } = await startRule();+ await routerService().run(id);+ await settle();+ await caller({ userId }).cancelSync({ jobId: id, projectId });++ const [rule] = await caller({ userId }).listSyncRules({ projectId });+ expect(rule).toMatchObject({ lastResult: null, lastRunAt: null });+ });++ it('marks the run failed, not successful, when the rule record cannot be written', async () => {+ mocks.syncByFilter.mockResolvedValue(round(5, false));+ const { id } = await startRule();+ const recordRun = vi+ .spyOn(LinearSyncRuleModel, 'recordRun')+ .mockRejectedValueOnce(new Error('connection reset'));++ await routerService().run(id);+ recordRun.mockRestore();++ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: 'failed', id, status: 'error' },+ ]);+ const [rule] = await caller({ userId }).listSyncRules({ projectId });+ expect(rule).toMatchObject({ lastResult: null, lastRunAt: null });+ });++ it('fails the run when the next round cannot be handed off', async () => {+ mocks.syncByFilter.mockResolvedValue(round(100, true, '100'));+ const { id } = await startRule();+ mocks.runSync.mockRejectedValue(+ new TRPCClientError('Invalid JWT token', {+ result: {+ error: {+ code: -32_001,+ data: { code: 'UNAUTHORIZED', httpStatus: 401 },+ message: 'Invalid JWT token',+ },+ },+ } as any),+ );++ await routerService().run(id);+ for (let i = 0; i < 50; i++) await new Promise((resolve) => setImmediate(resolve));++ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: 'failed', id, status: 'error' },+ ]);+ });++ it('can be stopped between rounds, keeping what was created', async () => {+ mocks.syncByFilter.mockResolvedValue(round(100, true, '100'));+ const { id } = await startRule();+ await routerService().run(id);+ await settle();++ expect(await caller({ userId }).cancelSync({ jobId: id, projectId })).toEqual({+ canceled: true,+ });+ await drainHandOffs();++ expect(mocks.syncByFilter).toHaveBeenCalledTimes(1);+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: 'canceled', id, result: { created: 100 }, status: 'error' },+ ]);+ });++ it('stays active while the stopped round finishes, then ends without another', async () => {+ const { id, rule } = await startRule();+ let during: unknown;+ mocks.syncByFilter.mockImplementation(async () => {+ await caller({ userId }).cancelSync({ jobId: id, projectId });+ // The round is still writing: the run shows as stopping, and Sync+ // joins it instead of starting an overlapping run.+ during = (await caller({ userId }).listSyncJobs({ projectId }))[0];+ expect(await caller({ userId }).startRuleSync({ ruleId: rule.id })).toEqual({ id });+ return round(100, true, '100');+ });++ await drainHandOffs();++ expect(during).toMatchObject({ error: 'canceled', id, status: 'processing' });+ expect(mocks.syncByFilter).toHaveBeenCalledTimes(1);+ expect(mocks.runSync).toHaveBeenCalledTimes(1);+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: 'canceled', id, result: { created: 100 }, status: 'error' },+ ]);+ // Once it has ended, the rule starts a new run.+ expect((await caller({ userId }).startRuleSync({ ruleId: rule.id })).id).not.toBe(id);+ });++ it('does not offer to stop an import of picked issues', async () => {+ const connection = await connect({ userId });+ mocks.getToken.mockResolvedValue('token');+ mocks.runSync.mockResolvedValue({ ok: true });+ const { id } = await caller({ userId }).startImport({+ connectionId: connection.id,+ issueIds: ['issue-1'],+ projectId,+ });++ expect(await caller({ userId }).cancelSync({ jobId: id, projectId })).toEqual({+ canceled: false,+ });+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: null, id, kind: 'issues', status: 'pending' },+ ]);+ });++ it("does not stop another user's run", async () => {+ mocks.syncByFilter.mockResolvedValue(round(100, true, '100'));+ const { id } = await startRule();++ await expect(+ caller({ userId: otherUserId }).cancelSync({ jobId: id, projectId: otherProjectId }),+ ).resolves.toEqual({ canceled: false });+ await expect(+ caller({ userId: otherUserId }).cancelSync({ jobId: id, projectId }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([+ { error: null, id, status: 'pending' },+ ]);+ });+ });+it('queues one run when the same rule is started twice at once', async () => {const connection = await connect({ userId });mocks.getToken.mockResolvedValue('token');diff --git a/apps/server/src/routers/lambda/linear.ts b/apps/server/src/routers/lambda/linear.tsindex d9301e03837..5a4c89824a6 100644--- a/apps/server/src/routers/lambda/linear.ts+++ b/apps/server/src/routers/lambda/linear.ts@@ -170,6 +170,25 @@ export const linearRouter = router({}),/** The project's recent background syncs, newest first. */+ /**+ * Stop a background sync of this project. A round already running finishes+ * the tasks it is writing; no further round starts, and tasks already+ * written are kept.+ */+ cancelSync: linearTaskWriteProcedure+ .input(projectInput.extend({ jobId: z.string().uuid() }))+ .mutation(async ({ ctx, input }) => {+ await requireProject(ctx, input.projectId);+ await requireWritableScope(ctx);+ const canceled = await LinearSyncJobModel.cancel(+ ctx.serverDB,+ ctx.scope,+ input.projectId,+ input.jobId,+ );+ return { canceled };+ }),+listSyncJobs: linearProcedure.input(projectInput).query(async ({ ctx, input }) => {await requireProject(ctx, input.projectId);const rows = await LinearSyncJobModel.listByProject(ctx.serverDB, ctx.scope, input.projectId);diff --git a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts b/apps/server/src/services/linear/__tests__/issueSync.integration.test.tsindex b8f00f5cf25..42defe06f0d 100644--- a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts+++ b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts@@ -322,6 +322,83 @@ describe('LinearIssueSyncService (real PostgreSQL)', () => {expect(second).toMatchObject({ created: 60, truncated: false, unchanged: 100 });}, 60_000);+ it('resumes where it left off, without rereading earlier pages or losing a capped issue', async () => {+ const many = Array.from({ length: 200 }, (_, index) => issue({ id: `cur-${index}` }));+ const reads: (string | undefined)[] = [];+ linear.listLinearIssues.mockImplementation(+ async (_token: string, _filter: unknown, { after }: { after?: string } = {}) => {+ reads.push(after);+ const start = after ? Number(after) : 0;+ const end = start + 50;+ return {+ cursor: end < many.length ? String(end) : undefined,+ hasMore: end < many.length,+ issues: many.slice(start, end),+ };+ },+ );+ linear.getLinearIssuesByIds.mockImplementation(async (_token: string, ids: string[]) =>+ many.filter((item) => ids.includes(item.id)),+ );+ const service = new LinearIssueSyncService(db, userId);+ // 30 of the first page are already in, so the cap falls inside the third page.+ await service.importIssues(+ TOKEN,+ many.slice(0, 30).map((item) => item.id),+ );+ linear.getLinearIssuesByIds.mockClear();+ const options = { ...filter, stateTypes: [...filter.stateTypes] };++ const first = await service.syncByFilter(TOKEN, options);+ expect(first).toMatchObject({ created: 100, resumeAfter: '100', truncated: true });+ expect(reads).toEqual([undefined, '50', '100']);++ // From the third page: its 20 left-over issues are not skipped.+ reads.length = 0;+ const second = await service.syncByFilter(TOKEN, options, { startAfter: first.resumeAfter });+ expect(second).toMatchObject({ created: 70, truncated: false });+ expect(second.resumeAfter).toBeUndefined();+ expect(reads).toEqual(['100', '150']);+ // The closing pass waits for a run that reads from the start.+ expect(linear.getLinearIssuesByIds).not.toHaveBeenCalled();++ for (const item of many) expect(await linkedTask(item.id)).not.toBeNull();+ }, 60_000);++ it('reconciles every page without creating when told not to create', async () => {+ const many = Array.from({ length: 150 }, (_, index) => issue({ id: `nc-${index}` }));+ const reads: (string | undefined)[] = [];+ linear.listLinearIssues.mockImplementation(+ async (_token: string, _filter: unknown, { after }: { after?: string } = {}) => {+ reads.push(after);+ const start = after ? Number(after) : 0;+ const end = start + 50;+ return {+ cursor: end < many.length ? String(end) : undefined,+ hasMore: end < many.length,+ issues: many.slice(start, end),+ };+ },+ );+ linear.getLinearIssuesByIds.mockImplementation(async (_token: string, ids: string[]) =>+ many.filter((item) => ids.includes(item.id)),+ );+ const service = new LinearIssueSyncService(db, userId);+ await service.importIssues(TOKEN, ['nc-149']);+ many[149] = { ...many[149], title: 'Renamed in Linear' };++ const result = await service.syncByFilter(+ TOKEN,+ { ...filter, stateTypes: [...filter.stateTypes] },+ { noCreate: true },+ );++ expect(reads).toEqual([undefined, '50', '100']);+ expect(result).toMatchObject({ created: 0, truncated: true, updated: 1 });+ expect(await linkedTask('nc-0')).toBeNull();+ expect((await linkedTask('nc-149'))?.name).toBe('Renamed in Linear');+ }, 60_000);+it('keeps a LobeHub edit made after the batch was loaded', async () => {serve([issue({ id: '1' })]);const service = new LinearIssueSyncService(db, userId);diff --git a/apps/server/src/services/linear/__tests__/syncJob.test.ts b/apps/server/src/services/linear/__tests__/syncJob.test.tsindex d0c718afbab..6054a2c30e6 100644--- a/apps/server/src/services/linear/__tests__/syncJob.test.ts+++ b/apps/server/src/services/linear/__tests__/syncJob.test.ts@@ -3,7 +3,15 @@ import { describe, expect, it } from 'vitest';import type { LinearSyncJobRow } from '@/database/models/linear';-import { LINEAR_SYNC_STALE_MS, LINEAR_SYNC_UNCLAIMED_MS, toLinearSyncJobView } from '../syncJob';+import {+ LINEAR_SYNC_MAX_ROUNDS,+ LINEAR_SYNC_STALE_MS,+ LINEAR_SYNC_UNCLAIMED_MS,+ mergeLinearSyncResults,+ nextLinearSyncRound,+ toLinearSyncJobView,+ withinRoundCap,+} from '../syncJob';const now = Date.UTC(2026, 9, 27, 12);@@ -49,3 +57,79 @@ describe('toLinearSyncJobView', () => {expect(toLinearSyncJobView(row({ status: 'error' }), now)).toMatchObject({ error: 'failed' });});});++const result = (overrides: Record<string, unknown> = {}) => ({+ closed: 0,+ created: 0,+ keptLocalEdits: 0,+ skipped: [],+ skippedCount: 0,+ truncated: false,+ unchanged: 0,+ updated: 0,+ ...overrides,+});++describe('nextLinearSyncRound', () => {+ it('reads on from the cursor while rounds stop at the cap', () => {+ expect(+ nextLinearSyncRound(undefined, result({ created: 100, resumeAfter: 'a', truncated: true })),+ ).toEqual({ cursor: 'a' });+ // Nothing created, but the cursor moved past issues it could not import.+ expect(nextLinearSyncRound('a', result({ resumeAfter: 'b', truncated: true }))).toEqual({+ cursor: 'b',+ });+ });++ it('stops a round that would only repeat itself', () => {+ expect(nextLinearSyncRound('a', result({ resumeAfter: 'a', truncated: true }))).toBeUndefined();+ expect(nextLinearSyncRound(undefined, result({ truncated: true }))).toBeUndefined();+ });++ it('ends a resumed run with one pass from the start, and stops after it', () => {+ expect(nextLinearSyncRound('a', result({ created: 5 }))).toEqual({ sweep: true });+ expect(nextLinearSyncRound(undefined, result({ created: 5 }))).toBeUndefined();+ });+});++describe('mergeLinearSyncResults', () => {+ const skipped = (identifier: string) => ({ identifier, reason: 'closed' as const });++ it('adds up what a resumed round saw, since it covered new issues only', () => {+ const merged = mergeLinearSyncResults(+ result({ created: 100, skipped: [skipped('A')], skippedCount: 1, unchanged: 3 }),+ result({ created: 50, skipped: [skipped('B')], skippedCount: 2, unchanged: 4 }),+ { resumed: true },+ );+ expect(merged).toMatchObject({ created: 150, skippedCount: 3, unchanged: 7 });+ expect(merged.skipped).toEqual([skipped('A'), skipped('B')]);+ });++ it('takes what a pass from the start saw from it alone', () => {+ expect(+ mergeLinearSyncResults(+ result({ closed: 1, created: 100, skippedCount: 1, unchanged: 3 }),+ result({ closed: 2, created: 0, skippedCount: 1, unchanged: 100 }),+ { resumed: false },+ ),+ ).toMatchObject({ closed: 3, created: 100, skippedCount: 1, unchanged: 100 });+ });+});++describe('withinRoundCap', () => {+ const cap = LINEAR_SYNC_MAX_ROUNDS;++ it('lets rounds on below the cap', () => {+ expect(withinRoundCap({ cursor: 'a' }, cap - 1, true)).toEqual({ cursor: 'a' });+ });++ it('turns a capped resumed run into the closing pass', () => {+ expect(withinRoundCap({ cursor: 'a' }, cap, true)).toEqual({ sweep: true });+ expect(withinRoundCap({ sweep: true }, cap, true)).toEqual({ sweep: true });+ });++ it('ends a capped run whose last round already read from the start', () => {+ expect(withinRoundCap({ cursor: 'a' }, cap + 1, false)).toBeUndefined();+ expect(withinRoundCap(undefined, cap, true)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/linear/issueSync.ts b/apps/server/src/services/linear/issueSync.tsindex 8f4a78b777d..eec7ec9f2ee 100644--- a/apps/server/src/services/linear/issueSync.ts+++ b/apps/server/src/services/linear/issueSync.ts@@ -38,7 +38,7 @@ export const MAX_TASKS_CREATED_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. */-const MAX_SKIPPED_ENTRIES = 100;+export const MAX_SKIPPED_ENTRIES = 100;const CLOSED_STATE_TYPES = new Set<LinearIssueStateType>(['completed', 'canceled']);const CLOSED_TASK_STATUSES = new Set(['completed', 'canceled']);@@ -58,10 +58,23 @@ interface SyncOptions {closeOnly?: boolean;/** Import an issue that is already completed or canceled (as a closed task). */createClosed?: boolean;+ /** Collects issues left uncreated because the run reached its task cap. */+ deferred?: Set<string>;+ /** Update and close linked tasks, but create none (a run past its task cap). */+ noCreate?: boolean;/** LobeHub project new tasks land in. */targetProjectId?: string | null;}+/** A filtered sync's outcome, plus where a run that stopped at its cap resumes. */+export type LinearFilterSyncResult = LinearSyncResult & {+ /**+ * The Linear cursor to read from next, when `truncated`: the start of the+ * first page holding an issue this run left for later. Absent: from the start.+ */+ resumeAfter?: string;+};+export const linearIssueToTaskFields = (issue: LinearIssue): SyncedFields => {const source = `> Linear: [${issue.identifier}](${issue.url})`;const body = issue.description?.trim() || issue.title;@@ -215,41 +228,64 @@ export class LinearIssueSyncService {* Sync every issue matching a filter, then close the tasks of linked issues* in the same team that the filter no longer matches because Linear closed* them.+ *+ * With `startAfter`, reading resumes at that cursor (a continuing run), and+ * the closing pass is left to a run that reads from the start, since this+ * 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`.*/async syncByFilter(accessToken: string,filter: LinearIssueFilter,- options: { targetProjectId?: string | null } = {},- ): Promise<LinearSyncResult> {- const result = emptyResult();+ options: { noCreate?: boolean; startAfter?: string; targetProjectId?: string | null } = {},+ ): Promise<LinearFilterSyncResult> {+ const result: LinearFilterSyncResult = emptyResult();const issues: LinearIssue[] = [];+ const pages: { ids: string[]; startCursor?: string }[] = [];// Read until this run has as many not-yet-imported issues as it may create.// Already linked issues do not count, so the next run reaches further.let unlinked = 0;- let after: string | undefined;+ let after = options.startAfter;do {+ const startCursor = after;const page = await listLinearIssues(accessToken, filter, {after,first: Math.min(LINEAR_PAGE_SIZE, MAX_ISSUES_PER_SYNC - issues.length),});issues.push(...page.issues);+ pages.push({ ids: page.issues.map((issue) => issue.id), startCursor });after = page.cursor;const linked = await this.linkModel.findByExternalIds('linear',page.issues.map((issue) => issue.id),);unlinked += page.issues.length - linked.length;- } while (after && issues.length < MAX_ISSUES_PER_SYNC && unlinked < MAX_TASKS_CREATED_PER_SYNC);+ } while (+ after &&+ issues.length < MAX_ISSUES_PER_SYNC &&+ (options.noCreate || unlinked < MAX_TASKS_CREATED_PER_SYNC)+ );result.truncated = !!after;+ const deferred = new Set<string>();await this.syncIssues(issues,{createClosed: filter.stateTypes.some((type) => CLOSED_STATE_TYPES.has(type)),+ deferred,+ noCreate: options.noCreate,targetProjectId: options.targetProjectId,},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.+ const firstDeferred = pages.find((page) => page.ids.some((id) => deferred.has(id)));+ result.resumeAfter = firstDeferred ? firstDeferred.startCursor : after;+ }+ if (options.startAfter) return result;// Linked issues the filter missed: closed since, or moved out of the project.const seen = new Set(issues.map((issue) => issue.id));@@ -328,8 +364,9 @@ export class LinearIssueSyncService {skip(result, issue.identifier, 'closed');return;}- if (result.created >= MAX_TASKS_CREATED_PER_SYNC) {+ if (options.noCreate || result.created >= MAX_TASKS_CREATED_PER_SYNC) {result.truncated = true;+ options.deferred?.add(issue.id);return;}diff --git a/apps/server/src/services/linear/startSyncJob.ts b/apps/server/src/services/linear/startSyncJob.tsindex ed6d2c51c10..7b039940095 100644--- a/apps/server/src/services/linear/startSyncJob.ts+++ b/apps/server/src/services/linear/startSyncJob.ts@@ -67,6 +67,30 @@ export const startLinearRuleSyncJob = async (return taskId;};+/**+ * Queue the next round of a rule run that stopped at its per-round cap. The+ * same job goes back to pending with the total so far, so it stays the one run+ * of its rule (a click on Sync joins it) and is handed off again like a new one.+ */+export const continueLinearRuleSyncJob = async (+ db: LobeChatDatabase,+ userId: string,+ workspaceId: string | undefined,+ taskId: string,+ metadata: LinearSyncJobMetadata,+): Promise<boolean> => {+ // A run the user stopped during this round is not queued again.+ const queued = await LinearSyncJobModel.transition(+ db,+ { userId, workspaceId: workspaceId ?? null },+ taskId,+ [AsyncTaskStatus.Processing],+ { metadata, status: AsyncTaskStatus.Pending },+ );+ if (queued) await dispatchJob(db, userId, workspaceId, taskId);+ return queued;+};+const recordJob = (db: LobeChatDatabase,userId: string,@@ -85,11 +109,15 @@ const dispatchJob = async (workspaceId: string | undefined,taskId: string,) => {+ // Only a job still waiting to be claimed; one the user stopped stays stopped.const fail = () =>- new AsyncTaskModel(db, userId, workspaceId).update(taskId, {- error: { code: 'failed' satisfies LinearSyncJobErrorCode },- status: AsyncTaskStatus.Error,- });+ LinearSyncJobModel.transition(+ db,+ { userId, workspaceId: workspaceId ?? null },+ taskId,+ [AsyncTaskStatus.Pending],+ { error: { code: 'failed' satisfies LinearSyncJobErrorCode }, status: AsyncTaskStatus.Error },+ );// Kept alive past the response, so a rejected hand-off can still be retried// or reported; otherwise the job sits queued until the client gives up on it.diff --git a/apps/server/src/services/linear/syncJob.ts b/apps/server/src/services/linear/syncJob.tsindex 33f98f1d00c..5e7f28223ba 100644--- a/apps/server/src/services/linear/syncJob.ts+++ b/apps/server/src/services/linear/syncJob.ts@@ -7,14 +7,14 @@ import type {import { AsyncTaskStatus } from '@lobechat/types';import debug from 'debug';-import { AsyncTaskModel } from '@/database/models/asyncTask';import type { LinearSyncJobRow } from '@/database/models/linear';import { LinearSyncJobModel, LinearSyncRuleModel } from '@/database/models/linear';import { ProjectModel } from '@/database/models/project';import type { LobeChatDatabase } from '@/database/type';import { LinearApiError } from './client';-import { LinearIssueSyncService } from './issueSync';+import type { LinearFilterSyncResult } from './issueSync';+import { LinearIssueSyncService, MAX_SKIPPED_ENTRIES } from './issueSync';import { getLinearAccessToken, LinearReconnectRequiredError } from './token';const log = debug('lobe-server:linear:sync-job');@@ -31,6 +31,61 @@ export const LINEAR_SYNC_HEARTBEAT_MS = 60 * 1000;* expired on the way) is given up on much sooner than a running one.*/export const LINEAR_SYNC_UNCLAIMED_MS = 2 * 60 * 1000;+/**+ * Rounds one rule run takes before it stops and asks to be run again. Each+ * round creates at most `MAX_TASKS_CREATED_PER_SYNC` tasks, so this bounds a+ * run at about 5,000 new tasks.+ */+export const LINEAR_SYNC_MAX_ROUNDS = 50;++/**+ * The outcome of a run that took several rounds. What a round wrote happens+ * once and adds up. A round that resumed at a cursor saw only issues after the+ * earlier ones, so what it looked at (unchanged, kept edits, skipped) adds up+ * too; a round that read from the start saw everything again, so those counts+ * come from it alone.+ */+export const mergeLinearSyncResults = (+ previous: LinearSyncResult | undefined,+ latest: LinearSyncResult,+ { resumed }: { resumed: boolean },+): LinearSyncResult => {+ if (!previous) return latest;+ const written = {+ closed: previous.closed + latest.closed,+ created: previous.created + latest.created,+ updated: previous.updated + latest.updated,+ };+ if (!resumed) return { ...latest, ...written };+ return {+ ...latest,+ ...written,+ keptLocalEdits: previous.keptLocalEdits + latest.keptLocalEdits,+ skipped: [...previous.skipped, ...latest.skipped].slice(0, MAX_SKIPPED_ENTRIES),+ skippedCount:+ (previous.skippedCount ?? previous.skipped.length) ++ (latest.skippedCount ?? latest.skipped.length),+ unchanged: previous.unchanged + latest.unchanged,+ };+};++/**+ * Where a rule run goes after a round: on from a cursor while it keeps+ * finding issues, then once more from the start, which picks up issues Linear+ * moved ahead of the cursor meanwhile and closes tasks whose issue was closed.+ * `undefined`: the run is done.+ */+export const nextLinearSyncRound = (+ startAfter: string | undefined,+ round: LinearFilterSyncResult,+): { cursor?: string; sweep?: true } | undefined => {+ if (round.truncated) {+ const moved = round.resumeAfter !== undefined && round.resumeAfter !== startAfter;+ // A round that neither created nor moved on would only repeat itself.+ return round.created > 0 || moved ? { cursor: round.resumeAfter } : undefined;+ }+ return startAfter === undefined ? undefined : { sweep: true };+};export const toLinearSyncJobView = (row: LinearSyncJobRow,@@ -44,7 +99,15 @@ export const toLinearSyncJobView = (const error = (row.error as { code?: LinearSyncJobErrorCode } | null)?.code ?? null;return {createdAt: row.createdAt,- error: stale ? 'timeout' : row.status === AsyncTaskStatus.Error ? (error ?? 'failed') : null,+ // A running job may carry `canceled`: its stop was requested and its+ // current round is finishing.+ error: stale+ ? 'timeout'+ : row.status === AsyncTaskStatus.Error+ ? (error ?? 'failed')+ : error === 'canceled'+ ? 'canceled'+ : null,id: row.id,issueCount: metadata.issueIds?.length,kind: metadata.kind,@@ -56,6 +119,16 @@ export const toLinearSyncJobView = (};};+/**+ * Queues the next round of a rule run. Supplied by the async router, which+ * owns hand-offs; without it a run stops after one round and asks to be run+ * again.+ */+export type ContinueLinearSyncJob = (+ taskId: string,+ metadata: LinearSyncJobMetadata,+) => Promise<boolean>;+class LinearSyncJobError extends Error {constructor(readonly code: LinearSyncJobErrorCode) {super(code);@@ -70,15 +143,12 @@ class LinearSyncJobError extends Error {* runs. Linear is only read.*/export class LinearSyncJobService {- private readonly asyncTaskModel: AsyncTaskModel;-constructor(private readonly db: LobeChatDatabase,private readonly userId: string,private readonly workspaceId?: string,- ) {- this.asyncTaskModel = new AsyncTaskModel(db, userId, workspaceId);- }+ private readonly continueJob?: ContinueLinearSyncJob,+ ) {}/** Run a recorded job to completion (async router side). */async run(taskId: string): Promise<void> {@@ -94,21 +164,82 @@ export class LinearSyncJobService {log('heartbeat %s failed: %O', taskId, error),);}, LINEAR_SYNC_HEARTBEAT_MS);+ // Every write below applies only while the job is still running and no+ // stop was requested; a run stopped meanwhile ends as stopped.+ // A failed round fails the job, unless the user stopped it meanwhile:+ // then it ends as stopped.+ const fail = async (code: LinearSyncJobErrorCode) => {+ const duration = Date.now() - startedAt;+ const failed = await LinearSyncJobModel.transition(+ this.db,+ this.scope,+ taskId,+ [AsyncTaskStatus.Processing],+ { duration, error: { code }, status: AsyncTaskStatus.Error },+ );+ if (!failed)+ await LinearSyncJobModel.settleStopped(this.db, this.scope, taskId, { duration });+ };try {- const result = await this.execute(metadata);- await this.asyncTaskModel.update(taskId, {- duration: Date.now() - startedAt,- metadata: { ...metadata, result },- status: AsyncTaskStatus.Success,+ const round = await this.execute(metadata);+ const roundResult = withoutResumePoint(round);+ const rounds = (metadata.rounds ?? 0) + 1;+ const result = mergeLinearSyncResults(metadata.result, roundResult, {+ resumed: metadata.cursor !== undefined,+ });+ // A rule run that hit its per-round cap goes on by itself, so the user+ // does not have to press Sync once per hundred issues.+ const proposed =+ this.continueJob && metadata.kind === 'rule'+ ? nextLinearSyncRound(metadata.cursor, round)+ : undefined;+ const next = withinRoundCap(proposed, rounds, metadata.cursor !== undefined);+ const outcome = {+ ...metadata,+ cursor: undefined,+ reconcileOnly: undefined,+ result,+ rounds,+ };+ if (next) {+ log('sync %s continues (round %d, %d created so far)', taskId, rounds, result.created);+ const queued = await this.continueJob!(taskId, {+ ...metadata,+ cursor: next.cursor,+ // Past the cap, the closing pass creates nothing, so the cap holds.+ reconcileOnly: rounds >= LINEAR_SYNC_MAX_ROUNDS || undefined,+ result,+ rounds,+ });+ if (queued) return;+ }+ // The rule shows its last finished run; a round in between, or a run+ // stopped part-way, leaves the previous one in place. The job turns+ // successful together with that record, or neither changes and the+ // failure below marks the job failed.+ const succeeded = await this.db.transaction(async (tx) => {+ const done = await LinearSyncJobModel.transition(+ tx,+ this.scope,+ taskId,+ [AsyncTaskStatus.Processing],+ { duration: Date.now() - startedAt, metadata: outcome, status: AsyncTaskStatus.Success },+ );+ if (done && metadata.kind === 'rule' && metadata.ruleId) {+ await LinearSyncRuleModel.recordRun(tx, metadata.ruleId, this.scope, result);+ }+ return done;});+ if (!succeeded) {+ await LinearSyncJobModel.settleStopped(this.db, this.scope, taskId, {+ duration: Date.now() - startedAt,+ metadata: outcome,+ });+ }} catch (error) {const code = toErrorCode(error);log('sync %s failed (%s): %O', taskId, code, error);- await this.asyncTaskModel.update(taskId, {- duration: Date.now() - startedAt,- error: { code },- status: AsyncTaskStatus.Error,- });+ await fail(code);} finally {clearInterval(heartbeat);}@@ -118,7 +249,9 @@ export class LinearSyncJobService {return { userId: this.userId, workspaceId: this.workspaceId ?? null };}- private async execute(metadata: LinearSyncJobMetadata): Promise<LinearSyncResult> {+ private async execute(+ metadata: LinearSyncJobMetadata,+ ): Promise<LinearSyncResult | LinearFilterSyncResult> {const scope = this.scope;// The project may have been deleted or hidden since the job was queued.const project = await new ProjectModel(this.db, this.userId, this.workspaceId).findById(@@ -139,16 +272,38 @@ export class LinearSyncJobService {: null;if (!rule || rule.projectId !== metadata.projectId) throw new LinearSyncJobError('unavailable');const token = await getLinearAccessToken(this.db, rule.connectionId);- const result = await sync.syncByFilter(+ return sync.syncByFilter(token,{ linearProjectId: rule.linearProjectId, stateTypes: rule.stateTypes, teamId: rule.teamId },- options,+ { ...options, noCreate: metadata.reconcileOnly, startAfter: metadata.cursor },);- await LinearSyncRuleModel.recordRun(this.db, rule.id, scope, result);- return result;}}+/**+ * The next round, once the creating rounds may have used up the cap. The+ * closing pass from the start is not a creating round: a run that stops at the+ * cap after reading on from a cursor still takes it, so it never ends without+ * checking the issues it linked earlier. A round that read from the start has+ * already done that pass, so the run ends there, asking to be run again if+ * issues remain.+ */+export const withinRoundCap = (+ proposed: { cursor?: string; sweep?: true } | undefined,+ rounds: number,+ resumed: boolean,+): { cursor?: string; sweep?: true } | undefined => {+ if (!proposed || proposed.sweep || rounds < LINEAR_SYNC_MAX_ROUNDS) return proposed;+ return resumed ? { sweep: true } : undefined;+};++/** A round's outcome as stored and shown; the resume point travels in the job's `cursor`. */+const withoutResumePoint = (round: LinearFilterSyncResult): LinearSyncResult => {+ const result = { ...round };+ delete result.resumeAfter;+ return result;+};+const toErrorCode = (error: unknown): LinearSyncJobErrorCode => {if (error instanceof LinearSyncJobError) return error.code;if (diff --git a/locales/en-US/integration.json b/locales/en-US/integration.jsonindex 7c18d0f26eb..4906e1ebc3a 100644--- a/locales/en-US/integration.json+++ b/locales/en-US/integration.json@@ -81,11 +81,13 @@"linear.sync.job.close": "Done","linear.sync.job.continuesInBackground": "The sync continues in the background. You will be notified when it ends.","linear.sync.job.done": "Sync finished",+ "linear.sync.job.error.canceled": "Stopped; tasks created before then are kept","linear.sync.job.error.timeout": "The sync stopped making progress and was cut off. Start it again.","linear.sync.job.error.unavailable": "The project, rule or Linear connection is no longer available.","linear.sync.job.failed": "Sync failed","linear.sync.job.finished": "Linear sync finished: {{result}}","linear.sync.job.inProgress": "Syncing…",+ "linear.sync.job.inProgressCreated": "Syncing in the background · {{count}} created so far","linear.sync.job.keptLocalEdits": "{{count}} tasks were edited in LobeHub; your edits were kept.","linear.sync.job.leave": "Continue in background","linear.sync.job.listTitle": "Sync runs",@@ -97,6 +99,10 @@"linear.sync.job.skipReason.running": "Task is running, so it was not closed","linear.sync.job.skipReason.unavailable": "Task is in the trash or not visible to you","linear.sync.job.skippedTitle": "{{count}} skipped",+ "linear.sync.job.stop": "Stop",+ "linear.sync.job.stopFailed": "Could not stop the sync. Try again.",+ "linear.sync.job.stopped": "Sync stopped",+ "linear.sync.job.stopping": "Stopping once the current batch is written…","linear.sync.job.titleIssues": "Import {{count}} issues","linear.sync.job.titleRule": "Rule: {{rule}}","linear.sync.job.titleRuleDeleted": "Rule (deleted)",diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.jsonindex f4f7cf52870..1d217ed641e 100644--- a/locales/zh-CN/integration.json+++ b/locales/zh-CN/integration.json@@ -81,11 +81,13 @@"linear.sync.job.close": "完成","linear.sync.job.continuesInBackground": "同步会在后台继续,结束时会通知你。","linear.sync.job.done": "同步完成",+ "linear.sync.job.error.canceled": "已停止,之前创建的任务会保留","linear.sync.job.error.timeout": "同步长时间没有进展,已中断,请重新开始。","linear.sync.job.error.unavailable": "项目、规则或 Linear 连接已不可用。","linear.sync.job.failed": "同步失败","linear.sync.job.finished": "Linear 同步完成:{{result}}","linear.sync.job.inProgress": "同步中…",+ "linear.sync.job.inProgressCreated": "后台同步中 · 已新建 {{count}} 个","linear.sync.job.keptLocalEdits": "有 {{count}} 个任务在 LobeHub 中改过,已保留你的修改。","linear.sync.job.leave": "后台继续","linear.sync.job.listTitle": "同步记录",@@ -97,6 +99,10 @@"linear.sync.job.skipReason.running": "任务正在运行,未关闭","linear.sync.job.skipReason.unavailable": "任务在回收站或你无权查看","linear.sync.job.skippedTitle": "跳过 {{count}} 个",+ "linear.sync.job.stop": "停止",+ "linear.sync.job.stopFailed": "停止同步失败,请重试。",+ "linear.sync.job.stopped": "同步已停止",+ "linear.sync.job.stopping": "正在停止,当前这批写完后结束…","linear.sync.job.titleIssues": "导入 {{count}} 个 Issue","linear.sync.job.titleRule": "按规则同步:{{rule}}","linear.sync.job.titleRuleDeleted": "按规则同步(规则已删除)",diff --git a/packages/database/src/models/linear/syncJob.ts b/packages/database/src/models/linear/syncJob.tsindex ca797363dce..cf74fc96009 100644--- a/packages/database/src/models/linear/syncJob.ts+++ b/packages/database/src/models/linear/syncJob.ts@@ -1,6 +1,6 @@import type { LinearSyncJobMetadata } from '@lobechat/types';import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';-import { and, desc, eq, inArray, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';import { asyncTasks } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -84,6 +84,92 @@ export class LinearSyncJobModel {);};+ /**+ * Update a job only while it is still in one of `from` and no stop was+ * requested, so a write from a run stopped meanwhile cannot carry it on.+ * Returns whether the job was updated.+ */+ static transition = async (+ db: LobeChatDatabase,+ scope: LinearConnectionScope,+ taskId: string,+ from: AsyncTaskStatus[],+ set: Partial<+ Pick<typeof asyncTasks.$inferInsert, 'duration' | 'error' | 'metadata' | 'status'>+ >,+ ): Promise<boolean> => {+ const rows = await db+ .update(asyncTasks)+ .set({ ...set, updatedAt: new Date() })+ .where(+ and(+ jobCondition(scope, taskId),+ inArray(asyncTasks.status, from),+ isNull(asyncTasks.error),+ ),+ )+ .returning({ id: asyncTasks.id });+ return rows.length > 0;+ };++ /**+ * End a running job whose stop was requested, once its round has written+ * what it was writing. Keeps the outcome so far.+ */+ static settleStopped = async (+ db: LobeChatDatabase,+ scope: LinearConnectionScope,+ taskId: string,+ set: Partial<Pick<typeof asyncTasks.$inferInsert, 'duration' | 'metadata'>>,+ ): Promise<void> => {+ await db+ .update(asyncTasks)+ .set({ ...set, status: AsyncTaskStatus.Error, updatedAt: new Date() })+ .where(+ and(+ jobCondition(scope, taskId),+ eq(asyncTasks.status, AsyncTaskStatus.Processing),+ sql`${asyncTasks.error} ->> 'code' = 'canceled'`,+ ),+ );+ };++ /**+ * Stop a rule run of this project that has not finished. One still queued ends+ * at once. One running is marked as stopping and stays active, so the rule+ * cannot start again while its round still writes; that round finishes the+ * tasks it is writing, then the job ends without starting another. Returns+ * whether a job was stopped.+ */+ static cancel = async (+ db: LobeChatDatabase,+ scope: LinearConnectionScope,+ projectId: string,+ taskId: string,+ ): Promise<boolean> => {+ // One statement over both active states, so a round moving the job from+ // processing to pending at the same moment cannot slip past the stop.+ const rows = await db+ .update(asyncTasks)+ .set({+ error: { code: 'canceled' },+ status: sql`CASE WHEN ${asyncTasks.status} = ${AsyncTaskStatus.Pending} THEN ${AsyncTaskStatus.Error} ELSE ${asyncTasks.status} END`,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(asyncTasks.id, taskId),+ projectCondition(scope, projectId),+ inArray(asyncTasks.status, ACTIVE_STATUSES),+ isNull(asyncTasks.error),+ // An import of picked issues is a single round; it cannot be cut short.+ sql`${asyncTasks.metadata} ->> 'kind' = 'rule'`,+ ),+ )+ .returning({ id: asyncTasks.id });+ return rows.length > 0;+ };+/** A run of this rule that has not finished yet, if any. */static findActiveForRule = async (db: LobeChatDatabase,@@ -107,6 +193,16 @@ export class LinearSyncJobModel {};}+const jobCondition = (scope: LinearConnectionScope, taskId: string) =>+ and(+ eq(asyncTasks.id, taskId),+ eq(asyncTasks.type, AsyncTaskType.LinearIssueSync),+ buildWorkspaceWhere(+ { userId: scope.userId, workspaceId: scope.workspaceId ?? undefined },+ asyncTasks,+ ),+ );+const projectCondition = (scope: LinearConnectionScope, projectId: string) =>and(eq(asyncTasks.type, AsyncTaskType.LinearIssueSync),diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.tsindex edb58043cd1..4aaa5e2637d 100644--- a/packages/locales/src/default/integration.ts+++ b/packages/locales/src/default/integration.ts@@ -104,6 +104,7 @@ export default {'linear.sync.job.continuesInBackground':'The sync continues in the background. You will be notified when it ends.','linear.sync.job.done': 'Sync finished',+ 'linear.sync.job.error.canceled': 'Stopped; tasks created before then are kept','linear.sync.job.error.timeout':'The sync stopped making progress and was cut off. Start it again.','linear.sync.job.error.unavailable':@@ -111,6 +112,7 @@ export default {'linear.sync.job.failed': 'Sync failed','linear.sync.job.finished': 'Linear sync finished: {{result}}','linear.sync.job.inProgress': 'Syncing…',+ 'linear.sync.job.inProgressCreated': 'Syncing in the background · {{count}} created so far','linear.sync.job.keptLocalEdits': '{{count}} tasks were edited in LobeHub; your edits were kept.','linear.sync.job.leave': 'Continue in background','linear.sync.job.listTitle': 'Sync runs',@@ -122,6 +124,10 @@ export default {'linear.sync.job.skipReason.running': 'Task is running, so it was not closed','linear.sync.job.skipReason.unavailable': 'Task is in the trash or not visible to you','linear.sync.job.skippedTitle': '{{count}} skipped',+ 'linear.sync.job.stop': 'Stop',+ 'linear.sync.job.stopFailed': 'Could not stop the sync. Try again.',+ 'linear.sync.job.stopped': 'Sync stopped',+ 'linear.sync.job.stopping': 'Stopping once the current batch is written…','linear.sync.job.titleIssues': 'Import {{count}} issues','linear.sync.job.titleRule': 'Rule: {{rule}}','linear.sync.job.titleRuleDeleted': 'Rule (deleted)',diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.tsindex 32fcbd0b7f2..9d909038aad 100644--- a/packages/types/src/linear.ts+++ b/packages/types/src/linear.ts@@ -122,7 +122,10 @@ export interface LinearSyncResult {skipped: { identifier: string; reason: LinearSyncSkipReason }[];/** Every skipped issue, including those past the `skipped` list. Absent in older results. */skippedCount?: number;- /** More issues matched than one run imports; run again for the rest. */+ /**+ * More issues matched than one run imports. A rule run continues on its own+ * until this clears; it stays set only when the run stopped early.+ */truncated: boolean;unchanged: number;updated: number;@@ -151,16 +154,31 @@ export type LinearSyncJobErrorCode =| 'unavailable'/** No progress for too long; the run was likely cut off. */| 'timeout'+ /** The user stopped it; tasks written before then are kept. */+ | 'canceled'| 'failed';/** What a background sync was asked to do, kept on its `async_tasks` row. */export interface LinearSyncJobMetadata {connectionId: string;+ /**+ * Where the next round of a rule run resumes reading Linear, so a long run+ * does not reread what earlier rounds covered. Absent: read from the start.+ */+ cursor?: string;/** Picked issues (`kind: 'issues'`). */issueIds?: string[];kind: 'issues' | 'rule';projectId: string;+ /**+ * This round reconciles linked tasks but creates none: the closing pass of+ * a run that used up its creating rounds.+ */+ reconcileOnly?: boolean;+ /** The outcome so far; while a rule run continues, the total of its finished rounds. */result?: LinearSyncResult;+ /** Rounds a rule run has finished; each creates at most a fixed number of tasks. */+ rounds?: number;/** The saved rule being run (`kind: 'rule'`). */ruleId?: string;}diff --git a/src/features/Projects/LinearSync/RunStep.tsx b/src/features/Projects/LinearSync/RunStep.tsxindex 064e9a53909..718d816141f 100644--- a/src/features/Projects/LinearSync/RunStep.tsx+++ b/src/features/Projects/LinearSync/RunStep.tsx@@ -11,6 +11,7 @@ import {formatLinearSyncResult,isActiveLinearSyncJob,linearSyncJobErrorMessage,+ linearSyncJobProgress,linearSyncSkippedCount,} from './utils';@@ -105,19 +106,22 @@ const RunStep = memo<RunStepProps>(({ actions, job, pendingIssueCount }) => {title={issueCount? t('linear.sync.job.runningIssues', { count: issueCount })- : t('linear.sync.job.runningRule')+ : job?.result?.created+ ? linearSyncJobProgress(job, t)+ : t('linear.sync.job.runningRule')}/>);}if (job.status === 'error') {+ const stopped = job.error === 'canceled';return (<Resultextra={actions}- status={'error'}+ status={stopped ? 'info' : 'error'}subTitle={linearSyncJobErrorMessage(job.error, t)}- title={t('linear.sync.job.failed')}+ title={stopped ? t('linear.sync.job.stopped') : t('linear.sync.job.failed')}/>);}diff --git a/src/features/Projects/LinearSync/SyncJobs.tsx b/src/features/Projects/LinearSync/SyncJobs.tsxindex 12a87aace0c..f5a7bc3b216 100644--- a/src/features/Projects/LinearSync/SyncJobs.tsx+++ b/src/features/Projects/LinearSync/SyncJobs.tsx@@ -1,14 +1,21 @@'use client';import type { LinearSyncJobView, LinearSyncRuleView } from '@lobechat/types';-import { Flexbox, Icon, Spin, Text } from '@lobehub/ui';+import { Button, Flexbox, Icon, Spin, Text, toast } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { CircleAlertIcon, CircleCheckIcon } from 'lucide-react';-import { memo } from 'react';+import { CircleAlertIcon, CircleCheckIcon, CircleStopIcon } from 'lucide-react';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { formatLinearSyncResult, isActiveLinearSyncJob, linearSyncJobErrorMessage } from './utils';+import { linearService } from '@/services/linear';++import {+ formatLinearSyncResult,+ isActiveLinearSyncJob,+ linearSyncJobErrorMessage,+ linearSyncJobProgress,+} from './utils';const styles = stylex.create({list: {@@ -35,15 +42,36 @@ const styles = stylex.create({});interface SyncJobsProps {+ /** Viewers see the runs but cannot stop one. */+ canStop: boolean;jobs: LinearSyncJobView[];+ /** Called after a run was stopped, to reload the list. */+ onChanged: () => void;+ projectId: string;rules: LinearSyncRuleView[];}+const isStopped = (job: LinearSyncJobView) => job.status === 'error' && job.error === 'canceled';+/** The project's recent background syncs: running ones first in time, then their outcomes. */-const SyncJobs = memo<SyncJobsProps>(({ jobs, rules }) => {+const SyncJobs = memo<SyncJobsProps>(({ canStop, jobs, onChanged, projectId, rules }) => {const { t } = useTranslation('integration');+ const [stopping, setStopping] = useState<string | null>(null);if (jobs.length === 0) return null;+ // A rule run can go on for many rounds; let the user end it after any of them.+ const stop = async (job: LinearSyncJobView) => {+ setStopping(job.id);+ try {+ await linearService.cancelSync(projectId, job.id);+ onChanged();+ } catch {+ toast.error(t('linear.sync.job.stopFailed'));+ } finally {+ setStopping(null);+ }+ };+const titleOf = (job: LinearSyncJobView) => {if (job.kind === 'issues')return t('linear.sync.job.titleIssues', { count: job.issueCount ?? 0 });@@ -56,7 +84,13 @@ const SyncJobs = memo<SyncJobsProps>(({ jobs, rules }) => {};const detailOf = (job: LinearSyncJobView) => {- if (isActiveLinearSyncJob(job)) return t('linear.sync.job.inProgress');+ if (isActiveLinearSyncJob(job) && job.error === 'canceled') {+ return t('linear.sync.job.stopping');+ }+ if (isActiveLinearSyncJob(job)) return linearSyncJobProgress(job, t);+ if (isStopped(job) && job.result) {+ return `${linearSyncJobErrorMessage(job.error, t)} · ${formatLinearSyncResult(job.result, t)}`;+ }if (job.status === 'error') return linearSyncJobErrorMessage(job.error, t);return job.result ? formatLinearSyncResult(job.result, t) : '';};@@ -76,6 +110,8 @@ const SyncJobs = memo<SyncJobsProps>(({ jobs, rules }) => {<Flexbox align={'center'} {...stylex.props(styles.status)}>{isActiveLinearSyncJob(job) ? (<Spin size={'small'} />+ ) : isStopped(job) ? (+ <Icon color={cssVar.colorTextSecondary} icon={CircleStopIcon} size={16} />) : job.status === 'error' ? (<Icon color={cssVar.colorError} icon={CircleAlertIcon} size={16} />) : (@@ -84,10 +120,29 @@ const SyncJobs = memo<SyncJobsProps>(({ jobs, rules }) => {</Flexbox><Flexbox flex={1} gap={2} style={{ minWidth: 0 }}><Text ellipsis>{titleOf(job)}</Text>- <Text ellipsis fontSize={12} type={job.status === 'error' ? 'danger' : 'secondary'}>+ <Text+ ellipsis+ fontSize={12}+ type={job.status === 'error' && !isStopped(job) ? 'danger' : 'secondary'}+ >{detailOf(job)}</Text></Flexbox>+ {/* Only a rule run goes on round after round; an import of picked+ issues is one round that cannot be cut short. */}+ {canStop &&+ job.kind === 'rule' &&+ isActiveLinearSyncJob(job) &&+ job.error !== 'canceled' ? (+ <Button+ icon={<Icon icon={CircleStopIcon} />}+ loading={stopping === job.id}+ size={'small'}+ onClick={() => stop(job)}+ >+ {t('linear.sync.job.stop')}+ </Button>+ ) : null}<Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>{new Date(job.createdAt).toLocaleString()}</Text>diff --git a/src/features/Projects/LinearSync/useLinearSyncJobs.ts b/src/features/Projects/LinearSync/useLinearSyncJobs.tsindex 8026c363565..e39795e53b2 100644--- a/src/features/Projects/LinearSync/useLinearSyncJobs.ts+++ b/src/features/Projects/LinearSync/useLinearSyncJobs.ts@@ -57,7 +57,8 @@ export const useLinearSyncJobNotifier = (toast.success(t('linear.sync.job.finished', { result: formatLinearSyncResult(job.result, t) }),);- } else if (job.status === 'error') {+ } else if (job.status === 'error' && job.error !== 'canceled') {+ // A stopped run was the user's own doing; it needs no toast.toast.error(linearSyncJobErrorMessage(job.error, t));}}diff --git a/src/features/Projects/LinearSync/useProjectLinearSync.tsx b/src/features/Projects/LinearSync/useProjectLinearSync.tsxindex 09c6f79e004..432b402069a 100644--- a/src/features/Projects/LinearSync/useProjectLinearSync.tsx+++ b/src/features/Projects/LinearSync/useProjectLinearSync.tsx@@ -81,7 +81,13 @@ export const useProjectLinearSync = (projectId={projectId}onJobStarted={refresh}/>- <SyncJobs jobs={syncJobs.data ?? []} rules={syncRules.data ?? []} />+ <SyncJobs+ canStop={!isViewer}+ jobs={syncJobs.data ?? []}+ projectId={projectId}+ rules={syncRules.data ?? []}+ onChanged={refresh}+ /></Flexbox>),};diff --git a/src/features/Projects/LinearSync/utils.test.ts b/src/features/Projects/LinearSync/utils.test.tsindex f17cde26d7f..328fa06c216 100644--- a/src/features/Projects/LinearSync/utils.test.ts+++ b/src/features/Projects/LinearSync/utils.test.ts@@ -2,7 +2,12 @@ import type { LinearSyncResult } from '@lobechat/types';import type { TFunction } from 'i18next';import { describe, expect, it } from 'vitest';-import { formatLinearSyncResult, isActiveLinearSyncJob, linearSyncJobErrorMessage } from './utils';+import {+ formatLinearSyncResult,+ isActiveLinearSyncJob,+ linearSyncJobErrorMessage,+ linearSyncJobProgress,+} from './utils';const t = ((key: string, options?: { count?: number }) =>options?.count === undefined@@ -67,3 +72,15 @@ describe('background sync jobs', () => {expect(linearSyncJobErrorMessage(null, t)).toBe('linear.sync.error.generic');});});++describe('linearSyncJobProgress', () => {+ it('shows how many a run that keeps going has created so far', () => {+ expect(linearSyncJobProgress({ result: null }, t)).toBe('linear.sync.job.inProgress');+ expect(linearSyncJobProgress({ result: result({ created: 0, truncated: true }) }, t)).toBe(+ 'linear.sync.job.inProgress',+ );+ expect(linearSyncJobProgress({ result: result({ created: 200, truncated: true }) }, t)).toBe(+ 'linear.sync.job.inProgressCreated:200',+ );+ });+});diff --git a/src/features/Projects/LinearSync/utils.ts b/src/features/Projects/LinearSync/utils.tsindex 9638f3e2ffd..30eb22ca7e7 100644--- a/src/features/Projects/LinearSync/utils.ts+++ b/src/features/Projects/LinearSync/utils.ts@@ -36,6 +36,18 @@ export const formatLinearSyncResult = (export const isActiveLinearSyncJob = (job: Pick<LinearSyncJobView, 'status'>) =>job.status === 'pending' || job.status === 'processing';+/**+ * Progress of a running sync. A rule run that goes on by itself carries the+ * total of its finished rounds, so the count grows while it runs.+ */+export const linearSyncJobProgress = (+ job: Pick<LinearSyncJobView, 'result'>,+ t: TFunction<'integration'>,+): string =>+ job.result?.created+ ? t('linear.sync.job.inProgressCreated', { count: job.result.created })+ : t('linear.sync.job.inProgress');+/** Why a background sync did not finish, for the user. */export const linearSyncJobErrorMessage = (code: LinearSyncJobErrorCode | null,@@ -51,6 +63,9 @@ export const linearSyncJobErrorMessage = (case 'timeout': {return t('linear.sync.job.error.timeout');}+ case 'canceled': {+ return t('linear.sync.job.error.canceled');+ }default: {return t('linear.sync.error.generic');}diff --git a/src/services/linear.ts b/src/services/linear.tsindex 157dd738344..e86d2ddaca3 100644--- a/src/services/linear.ts+++ b/src/services/linear.ts@@ -31,6 +31,9 @@ class LinearService {startImport = async (params: { connectionId: string; issueIds: string[]; projectId: string }) =>lambdaClient.linear.startImport.mutate(params);+ cancelSync = async (projectId: string, jobId: string) =>+ lambdaClient.linear.cancelSync.mutate({ jobId, projectId });+listSyncJobs = async (projectId: string) => lambdaClient.linear.listSyncJobs.query({ projectId });listSyncRules = async (projectId: string) =>