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.

🐛 fix(linear): archive the task of an issue archived in Linear (#22459)

Rdmclin2b477606131e6
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 988b9d887de..06c8a75f0a3 100644
--- a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
+++ b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
@@ -10,9 +10,11 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TaskModel } from '@/database/models/task';
+import { TaskArchiveModel } from '@/database/models/taskArchive';
import { TaskExternalLinkModel } from '@/database/models/taskExternalLink';
import { tasks, users } from '@/database/schemas';
+import type * as ArchiveGuardModule from '../../task/archiveGuard';
import { LinearApiError } from '../client';
import type * as IssuesModule from '../issues';
import type { LinearIssue, LinearIssueComment } from '../issues';
@@ -23,13 +25,21 @@ import {
} from '../issueSync';
const linear = vi.hoisted(() => ({
+ getArchivedLinearIssuesByIds: vi.fn(),
getLinearIssuesByIds: vi.fn(),
getLinearProjectTeamIds: vi.fn(),
listLinearIssueComments: vi.fn(),
listLinearIssues: vi.fn(),
}));
+const openGoals = vi.hoisted(() => ({ taskIds: new Set<string>() }));
+vi.mock('../../task/archiveGuard', async (importOriginal) => ({
+ ...(await importOriginal<typeof ArchiveGuardModule>()),
+ findTasksInOpenGoals: async (_db: unknown, _scope: unknown, items: { id: string }[]) =>
+ new Set(items.map((item) => item.id).filter((id) => openGoals.taskIds.has(id))),
+}));
vi.mock('../issues', async (importOriginal) => ({
...(await importOriginal<typeof IssuesModule>()),
+ getArchivedLinearIssuesByIds: linear.getArchivedLinearIssuesByIds,
getLinearIssuesByIds: linear.getLinearIssuesByIds,
getLinearProjectTeamIds: linear.getLinearProjectTeamIds,
listLinearIssueComments: linear.listLinearIssueComments,
@@ -62,6 +72,9 @@ const serve = (issues: LinearIssue[]) => {
linear.getLinearIssuesByIds.mockImplementation(async (_token: string, ids: string[]) =>
issues.filter((item) => ids.includes(item.id)),
);
+ linear.getArchivedLinearIssuesByIds.mockImplementation(async (_token: string, ids: string[]) =>
+ issues.filter((item) => ids.includes(item.id) && item.archivedAt),
+ );
};
const filter = { stateTypes: ['backlog', 'unstarted', 'started'] as const, teamId: TEAM };
@@ -869,6 +882,7 @@ describe('LinearIssueSyncService archived issues (real PostgreSQL, Linear over f
beforeEach(async () => {
const actual = await vi.importActual<typeof IssuesModule>('../issues');
linear.listLinearIssues.mockImplementation(actual.listLinearIssues);
+ linear.getArchivedLinearIssuesByIds.mockImplementation(actual.getArchivedLinearIssuesByIds);
linear.getLinearIssuesByIds.mockImplementation(actual.getLinearIssuesByIds);
linear.getLinearProjectTeamIds.mockImplementation(actual.getLinearProjectTeamIds);
vi.stubGlobal(
@@ -884,6 +898,7 @@ describe('LinearIssueSyncService archived issues (real PostgreSQL, Linear over f
const nodes = linearIssues
.filter((item) => includeArchived || !item.archived)
.filter((item) => !where.id || where.id.in.includes(item.id))
+ .filter((item) => !where.archivedAt || !!item.archivedAt)
.filter((item) => !where.state || where.state.type.in.includes(item.state.type))
.filter((item) => !where.team || item.team.id === where.team.id.eq)
.map(({ archived: _archived, ...rest }) => rest);
@@ -944,4 +959,216 @@ describe('LinearIssueSyncService archived issues (real PostgreSQL, Linear over f
expect(result.closed).toBe(1);
expect((await linkedTask('1'))?.status).toBe('completed');
});
+
+ describe('archiving tasks like their issues', () => {
+ const ARCHIVED_AT = '2026-09-01T08:00:00.000Z';
+ const rule = {
+ includeArchived: true,
+ stateTypes: ['backlog' as const, 'unstarted' as const, 'completed' as const],
+ teamId: TEAM,
+ };
+ const archivedIssue = (id: string, archivedAt = ARCHIVED_AT) => ({
+ ...issue({ archivedAt, id, state: done }),
+ archived: true,
+ });
+
+ afterEach(() => openGoals.taskIds.clear());
+
+ it('archives the task of a picked archived issue at the time Linear did', async () => {
+ linearIssues = [archivedIssue('1')];
+
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+
+ expect(result).toMatchObject({ archived: 1, created: 1 });
+ const task = await linkedTask('1');
+ expect(task?.status).toBe('completed');
+ expect(task?.archivedAt?.toISOString()).toBe(ARCHIVED_AT);
+ });
+
+ it('leaves the task of an unarchived issue out of the archive', async () => {
+ linearIssues = [issue({ archivedAt: null, id: '1' })];
+
+ const result = await new LinearIssueSyncService(db, userId).syncByFilter(TOKEN, rule);
+
+ expect(result.archived).toBeUndefined();
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+ });
+
+ it('archives an already imported task on the next run that reads its archived issue', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1', state: done })];
+ await service.syncByFilter(TOKEN, rule);
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+
+ linearIssues = [archivedIssue('1')];
+ const result = await service.syncByFilter(TOKEN, rule);
+
+ expect(result.archived).toBe(1);
+ expect((await linkedTask('1'))?.archivedAt?.toISOString()).toBe(ARCHIVED_AT);
+ });
+
+ it('archives an open task whose issue a rule no longer lists, closing nothing', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1' })];
+ await service.syncByFilter(TOKEN, rule);
+
+ linearIssues = [{ ...issue({ archivedAt: ARCHIVED_AT, id: '1' }), archived: true }];
+ const result = await service.syncByFilter(TOKEN, { ...rule, includeArchived: false });
+
+ expect(result).toMatchObject({ archived: 1, closed: 0 });
+ const task = await linkedTask('1');
+ expect(task?.archivedAt?.toISOString()).toBe(ARCHIVED_AT);
+ expect(task?.status).not.toBe('completed');
+ });
+
+ it('archives a closed task whose issue is archived later, without the option, and asks once', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1', state: done }), issue({ id: '2', state: done })];
+ await service.syncByFilter(TOKEN, rule);
+
+ // Archived in Linear after closing, so a listing without the option misses it.
+ linearIssues = [archivedIssue('1'), issue({ id: '2', state: done })];
+ const plain = { ...rule, includeArchived: false, stateTypes: ['backlog' as const] };
+ const result = await service.syncByFilter(TOKEN, plain);
+
+ expect(result.archived).toBe(1);
+ expect((await linkedTask('1'))?.archivedAt?.toISOString()).toBe(ARCHIVED_AT);
+ expect((await linkedTask('2'))?.archivedAt).toBeNull();
+
+ // Applied: restored stays restored, and this link is not asked about again.
+ await new TaskArchiveModel(db, userId).unarchive((await linkedTask('1'))!.id);
+ linear.getArchivedLinearIssuesByIds.mockClear();
+ expect((await service.syncByFilter(TOKEN, plain)).archived).toBeUndefined();
+ expect(linear.getArchivedLinearIssuesByIds.mock.calls[0][1]).toEqual(['2']);
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+ });
+
+ it('does not archive again a task restored in LobeHub', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [archivedIssue('1')];
+ await service.syncByFilter(TOKEN, rule);
+ const task = await linkedTask('1');
+ await new TaskArchiveModel(db, userId).unarchive(task!.id);
+
+ const result = await service.syncByFilter(TOKEN, rule);
+
+ expect(result.archived).toBeUndefined();
+ expect(result.unchanged).toBe(1);
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+ });
+
+ it('does not archive again from an older read a task restored since', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1', state: done })];
+ await service.syncByFilter(TOKEN, rule);
+ // What an overlapping run read before this archive was applied.
+ const [staleLink] = await new TaskExternalLinkModel(db, userId).findByExternalIds('linear', [
+ '1',
+ ]);
+ const staleTask = await linkedTask('1');
+
+ linearIssues = [archivedIssue('1')];
+ await service.syncByFilter(TOKEN, rule);
+ await new TaskArchiveModel(db, userId).unarchive(staleTask!.id);
+
+ const result = { archived: undefined, closed: 0, skipped: [], unchanged: 0 };
+ await (service as any).syncLinked(archivedIssue('1'), staleLink, staleTask, {}, result);
+
+ expect(result.archived).toBeUndefined();
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+ });
+
+ it('keeps the task archived when Linear restores the issue, and applies a new archive', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [archivedIssue('1')];
+ await service.syncByFilter(TOKEN, rule);
+
+ linearIssues = [issue({ archivedAt: null, id: '1', state: done })];
+ const restored = await service.syncByFilter(TOKEN, rule);
+ expect(restored.archived).toBeUndefined();
+ const task = await linkedTask('1');
+ expect(task?.archivedAt?.toISOString()).toBe(ARCHIVED_AT);
+
+ // Restored here as well, then archived in Linear once more.
+ await new TaskArchiveModel(db, userId).unarchive(task!.id);
+ const later = '2026-10-15T08:00:00.000Z';
+ linearIssues = [archivedIssue('1', later)];
+ const again = await service.syncByFilter(TOKEN, rule);
+
+ expect(again.archived).toBe(1);
+ expect((await linkedTask('1'))?.archivedAt?.toISOString()).toBe(later);
+ });
+
+ it('keeps the time of a task archived in LobeHub first, without counting it', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1', state: done })];
+ await service.syncByFilter(TOKEN, rule);
+ const task = await linkedTask('1');
+ const own = await new TaskArchiveModel(db, userId).archive(task!.id);
+
+ linearIssues = [archivedIssue('1')];
+ const result = await service.syncByFilter(TOKEN, rule);
+
+ expect(result.archived).toBeUndefined();
+ expect((await linkedTask('1'))?.archivedAt).toEqual(own?.archivedAt);
+ });
+
+ it('leaves a running task for a later run, reporting it once', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1' })];
+ await service.syncByFilter(TOKEN, rule);
+ const task = await linkedTask('1');
+ await db.update(tasks).set({ status: 'running' }).where(eq(tasks.id, task!.id));
+
+ linearIssues = [archivedIssue('1')];
+ const running = await service.syncByFilter(TOKEN, rule);
+
+ expect(running.archived).toBeUndefined();
+ expect(running.skipped).toEqual([{ identifier: 'ENG-1', reason: 'running' }]);
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+
+ await db.update(tasks).set({ status: 'paused' }).where(eq(tasks.id, task!.id));
+ const later = await service.syncByFilter(TOKEN, rule);
+
+ expect(later).toMatchObject({ archived: 1, closed: 1 });
+ expect((await linkedTask('1'))?.archivedAt?.toISOString()).toBe(ARCHIVED_AT);
+ });
+
+ it('leaves a task with a live heartbeat for a later run', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1' })];
+ await service.syncByFilter(TOKEN, rule);
+ const task = await linkedTask('1');
+ await db
+ .update(tasks)
+ .set({ automationMode: 'heartbeat', heartbeatInterval: 60 })
+ .where(eq(tasks.id, task!.id));
+
+ linearIssues = [{ ...issue({ archivedAt: ARCHIVED_AT, id: '1' }), archived: true }];
+ const live = await service.syncByFilter(TOKEN, rule);
+ expect(live.archived).toBeUndefined();
+ expect(live.skipped).toEqual([{ identifier: 'ENG-1', reason: 'live' }]);
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+
+ await db.update(tasks).set({ heartbeatInterval: 0 }).where(eq(tasks.id, task!.id));
+ expect((await service.syncByFilter(TOKEN, rule)).archived).toBe(1);
+ });
+
+ it('leaves an unfinished task of an open goal for a later run', async () => {
+ const service = new LinearIssueSyncService(db, userId);
+ linearIssues = [issue({ id: '1' })];
+ await service.syncByFilter(TOKEN, rule);
+ const task = await linkedTask('1');
+ openGoals.taskIds.add(task!.id);
+
+ linearIssues = [{ ...issue({ archivedAt: ARCHIVED_AT, id: '1' }), archived: true }];
+ const held = await service.syncByFilter(TOKEN, rule);
+ expect(held.archived).toBeUndefined();
+ expect(held.skipped).toEqual([{ identifier: 'ENG-1', reason: 'live' }]);
+ expect((await linkedTask('1'))?.archivedAt).toBeNull();
+
+ openGoals.taskIds.clear();
+ expect((await service.syncByFilter(TOKEN, rule)).archived).toBe(1);
+ });
+ });
});
diff --git a/apps/server/src/services/linear/__tests__/issues.test.ts b/apps/server/src/services/linear/__tests__/issues.test.ts
index 3ccf264a4f2..0b5d7cb9d29 100644
--- a/apps/server/src/services/linear/__tests__/issues.test.ts
+++ b/apps/server/src/services/linear/__tests__/issues.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
countLinearIssues,
+ getArchivedLinearIssuesByIds,
getLinearIssuesByIds,
getLinearProjectTeamIds,
listLinearIssues,
@@ -105,6 +106,7 @@ describe('archived issues', () => {
expect(issues).toMatchObject([{ id: 'archived-1' }]);
const body = requestBody(fetchMock.mock.calls[0]);
expect(body.query).toContain('includeArchived: true');
+ expect(body.query).toContain('archivedAt');
expect(body.variables.filter).toEqual({ id: { in: ['archived-1'] } });
});
});
@@ -212,3 +214,25 @@ describe('countLinearIssues', () => {
).toEqual({ capped: false, count: 50 });
});
});
+
+describe('getArchivedLinearIssuesByIds', () => {
+ it('asks Linear for only the archived ones, including them in the query', async () => {
+ const fetchMock = vi.fn(
+ async () =>
+ new Response(
+ JSON.stringify({
+ data: { issues: { nodes: [], pageInfo: { endCursor: null, hasNextPage: false } } },
+ }),
+ { status: 200 },
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ await getArchivedLinearIssuesByIds('token', ['a', 'b']);
+
+ const { query, variables } = JSON.parse((fetchMock.mock.calls[0] as any)[1].body);
+ expect(query).toContain('includeArchived: true');
+ expect(variables.filter).toEqual({ archivedAt: { null: false }, id: { in: ['a', 'b'] } });
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/apps/server/src/services/linear/__tests__/syncJob.test.ts b/apps/server/src/services/linear/__tests__/syncJob.test.ts
index 39c8d31a006..c42d9d457fa 100644
--- a/apps/server/src/services/linear/__tests__/syncJob.test.ts
+++ b/apps/server/src/services/linear/__tests__/syncJob.test.ts
@@ -105,6 +105,18 @@ describe('mergeLinearSyncResults', () => {
expect(merged.skipped).toEqual([skipped('A'), skipped('B')]);
});
+ it('adds up tasks archived across rounds, whichever kind of round it was', () => {
+ for (const resumed of [true, false]) {
+ expect(
+ mergeLinearSyncResults(result({ archived: 2 }), result({ archived: 3 }), { resumed })
+ .archived,
+ ).toBe(5);
+ }
+ expect(
+ mergeLinearSyncResults(result({}), result({}), { resumed: true }).archived,
+ ).toBeUndefined();
+ });
+
it('takes what a pass from the start saw from it alone', () => {
expect(
mergeLinearSyncResults(
diff --git a/apps/server/src/services/linear/issueSync.ts b/apps/server/src/services/linear/issueSync.ts
index a5e2338c564..0301ebb1e6c 100644
--- a/apps/server/src/services/linear/issueSync.ts
+++ b/apps/server/src/services/linear/issueSync.ts
@@ -10,9 +10,11 @@ import type {
} from '@lobechat/types';
import { isLinearNoProject } from '@lobechat/types';
import debug from 'debug';
+import { sql } from 'drizzle-orm';
import pMap from 'p-map';
import { isTaskIdentifierUniqueViolation, TaskModel } from '@/database/models/task';
+import { TaskArchiveModel } from '@/database/models/taskArchive';
import {
TaskExternalLinkModel,
type TaskExternalLinkWithTask,
@@ -20,9 +22,11 @@ import {
import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '../task';
+import { findTasksInOpenGoals } from '../task/archiveGuard';
import { LinearApiError } from './client';
import { linearCommentToContent } from './issueComments';
import {
+ getArchivedLinearIssuesByIds,
getLinearIssuesByIds,
getLinearProjectTeamIds,
LINEAR_PAGE_SIZE,
@@ -64,7 +68,7 @@ interface SyncedFields {
interface SyncOptions {
/**
- * Only close tasks whose issue Linear closed; never create or rewrite. Used
+ * Only close or archive tasks like their issue; never create or rewrite. Used
* for linked issues that a filtered sync no longer matches.
*/
closeOnly?: boolean;
@@ -110,7 +114,8 @@ const hashTask = (task: TaskItem): string =>
priority: task.priority ?? 0,
});
-const linkMetadata = (issue: LinearIssue): LinearIssueLinkMetadata => ({
+const linkMetadata = (issue: LinearIssue, appliedArchivedAt?: string): LinearIssueLinkMetadata => ({
+ ...(appliedArchivedAt ? { appliedArchivedAt } : {}),
assigneeName: issue.assignee?.displayName,
labels: issue.labels?.nodes.map((label) => label.name),
projectName: issue.project?.name,
@@ -160,7 +165,9 @@ const parentsFirst = (issues: LinearIssue[]): LinearIssue[] => {
* in LobeHub since the last sync, in which case the edit is kept;
* - a task whose issue Linear completed or canceled is closed the same way,
* except a running task, which is never interrupted;
- * - a task is never reopened, deleted or recreated by a sync.
+ * - a task whose issue Linear archived is archived once, unless it is still
+ * live, which waits for a later run;
+ * - a task is never reopened, restored, deleted or recreated by a sync.
*/
export class LinearIssueSyncService {
private readonly db: LobeChatDatabase;
@@ -246,7 +253,8 @@ export class LinearIssueSyncService {
/**
* Sync every issue matching a filter, then close the tasks of linked issues
* in the filter's teams (for a project, every team it belongs to) that the
- * filter no longer matches because Linear closed them.
+ * filter no longer matches because Linear closed them, and archive those of
+ * issues Linear archived.
*
* 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
@@ -361,6 +369,19 @@ export class LinearIssueSyncService {
if (CLOSED_STATE_TYPES.has(issue.state.type)) closing.push(issue.id);
}
}
+ // Issues archived since their task closed, which Linear also does on its
+ // own after a while. A closed task is not reread above, and a run without
+ // archived issues never lists these. Once applied, a link is not asked again.
+ const closedUnarchived = unseen.filter(
+ (link) => closedTaskIds.has(link.taskId) && !link.metadata?.appliedArchivedAt,
+ );
+ if (closedUnarchived.length > 0) {
+ const archived = await getArchivedLinearIssuesByIds(
+ accessToken,
+ closedUnarchived.map((link) => link.externalId),
+ );
+ await this.syncIssues(archived, { closeOnly: true }, result);
+ }
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
@@ -465,6 +486,12 @@ export class LinearIssueSyncService {
let current = task;
if (closed) current = (await this.close(task, issue.state.type)) ?? task;
result.created += 1;
+ if (
+ issue.archivedAt &&
+ (await this.archiveOnce(issue, issue.archivedAt, task.id)) === 'archived'
+ ) {
+ result.archived = (result.archived ?? 0) + 1;
+ }
return { link, task: current };
}
@@ -548,29 +575,59 @@ export class LinearIssueSyncService {
}
}
+ let skippedRunning = false;
if (CLOSED_STATE_TYPES.has(issue.state.type) && !CLOSED_TASK_STATUSES.has(task.status)) {
// Rechecked under the row lock: the task may have started since the batch was read.
const closed =
task.status !== 'running' && (await this.close(task, issue.state.type)) !== undefined;
- if (closed) result.closed += 1;
- else skip(result, issue.identifier, 'running');
+ if (closed) {
+ result.closed += 1;
+ } else {
+ skip(result, issue.identifier, 'running');
+ skippedRunning = true;
+ }
counted = true;
}
+ // Applied at most once per Linear archive, so a task restored in LobeHub
+ // stays restored. Nothing here ever restores a task.
+ let appliedArchivedAt =
+ link.metadata?.appliedArchivedAt === issue.archivedAt
+ ? (issue.archivedAt ?? undefined)
+ : undefined;
+ if (issue.archivedAt && !appliedArchivedAt) {
+ const outcome = await this.archiveOnce(issue, issue.archivedAt, task.id);
+ if (outcome === 'archived' || outcome === 'applied') {
+ appliedArchivedAt = issue.archivedAt;
+ if (outcome === 'archived') {
+ result.archived = (result.archived ?? 0) + 1;
+ counted = true;
+ }
+ } else {
+ // Reported, since the archive is still owed; a later run retries it.
+ if (!skippedRunning) skip(result, issue.identifier, outcome);
+ counted = true;
+ }
+ }
+
if (!counted) result.unchanged += 1;
- // Display facts only. `syncedHash` is written solely by `create` and
- // `applyLinearFields`, together with the task, so a run working from an
- // older read can never put a stale hash back.
+ // Display facts and the applied archive. `syncedHash` is written solely by
+ // `create` and `applyLinearFields`, together with the task, so a run working
+ // from an older read can never put a stale hash back.
const issueUpdatedAt = new Date(issue.updatedAt);
- if (link.externalUpdatedAt?.getTime() === issueUpdatedAt.getTime()) return;
+ if (
+ link.externalUpdatedAt?.getTime() === issueUpdatedAt.getTime() &&
+ link.metadata?.appliedArchivedAt === appliedArchivedAt
+ )
+ return;
await this.linkModel.update(link.id, {
externalContainerId: issue.team.id,
externalIdentifier: issue.identifier,
externalUpdatedAt: issueUpdatedAt,
externalUrl: issue.url,
- metadata: linkMetadata(issue),
+ metadata: linkMetadata(issue, appliedArchivedAt),
});
}
@@ -616,6 +673,56 @@ export class LinearIssueSyncService {
return skippedRunning ? undefined : updated;
}
+ /**
+ * Archive the task like its issue, at Linear's time, under the rules of a
+ * manual archive, recording it on the link in one transaction. Rechecked under
+ * the row lock: a run working from an older read must not archive again a task
+ * restored since another run applied this archive.
+ *
+ * - `archived`: done by this call;
+ * - `applied`: nothing to do: already applied, or archived in LobeHub first,
+ * which stays as it is and is recorded;
+ * - `running` / `live`: left for a later run, since it is running, has a schedule
+ * or heartbeat that can fire, or is unfinished in an open Goal.
+ */
+ private async archiveOnce(
+ issue: LinearIssue,
+ archivedAt: string,
+ taskId: string,
+ ): Promise<'applied' | 'archived' | 'live' | 'running'> {
+ return this.db.transaction(async (tx) => {
+ const tasks = new TaskModel(tx, this.userId, this.workspaceId);
+ await tasks.lockForUpdate(taskId);
+ const links = new TaskExternalLinkModel(tx, this.userId, this.workspaceId);
+ const [link] = await links.findByExternalIds('linear', [issue.id]);
+ const task = await tasks.findById(taskId);
+ if (!link || link.taskId !== taskId || !task) return 'live';
+ if (link.metadata?.appliedArchivedAt === archivedAt) return 'applied';
+
+ const record = () => links.update(link.id, { metadata: linkMetadata(issue, archivedAt) });
+ if (task.archivedAt) {
+ await record();
+ return 'applied';
+ }
+
+ const inOpenGoal = await findTasksInOpenGoals(
+ tx,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ [task],
+ );
+ if (inOpenGoal.size > 0) return 'live';
+
+ const [archived] = await new TaskArchiveModel(tx, this.userId, this.workspaceId).archiveMany(
+ [taskId],
+ { at: sql`${archivedAt}::timestamptz` },
+ );
+ if (!archived) return task.status === 'running' ? 'running' : 'live';
+
+ await record();
+ return 'archived';
+ });
+ }
+
/**
* Copy the Linear comments of these issues onto their tasks, oldest first,
* skipping those copied before. Only tasks the caller can see get comments;
diff --git a/apps/server/src/services/linear/issues.ts b/apps/server/src/services/linear/issues.ts
index 58802a665d3..81977a1bd95 100644
--- a/apps/server/src/services/linear/issues.ts
+++ b/apps/server/src/services/linear/issues.ts
@@ -13,6 +13,8 @@ export const LINEAR_PAGE_SIZE = 50;
/** An issue with everything a sync writes into a task. */
export interface LinearIssue {
+ /** Set while the issue is archived in Linear. Archiving is not a state. */
+ archivedAt?: string | null;
assignee?: { displayName: string } | null;
description?: string | null;
id: string;
@@ -29,7 +31,7 @@ export interface LinearIssue {
}
const ISSUE_FIELDS = `
- id identifier title description url priority updatedAt
+ id identifier title description url priority updatedAt archivedAt
state { name type }
parent { id }
assignee { displayName }
@@ -215,16 +217,10 @@ export const countLinearIssues = async (
return { capped: hasMore, count };
};
-/**
- * Issues by id, in pages of the API's maximum size. Unknown or inaccessible ids
- * are omitted; archived ones are always returned. An id is asked for because it
- * was picked (archived issues are listed only when asked for, so one picked was
- * meant) or because a task is linked to it, and an issue archived after it was
- * linked must still close its task.
- */
-export const getLinearIssuesByIds = async (
+const fetchLinearIssuesByIds = async (
accessToken: string,
ids: string[],
+ where: object = {},
): Promise<LinearIssue[]> => {
const issues: LinearIssue[] = [];
for (let start = 0; start < ids.length; start += LINEAR_PAGE_SIZE) {
@@ -237,13 +233,33 @@ export const getLinearIssuesByIds = async (
pageInfo { hasNextPage endCursor }
}
}`,
- { filter: { id: { in: batch } }, first: batch.length },
+ { filter: { ...where, id: { in: batch } }, first: batch.length },
);
issues.push(...data.issues.nodes);
}
return issues;
};
+/**
+ * Issues by id, in pages of the API's maximum size. Unknown or inaccessible ids
+ * are omitted; archived ones are always returned. An id is asked for because it
+ * was picked (archived issues are listed only when asked for, so one picked was
+ * meant) or because a task is linked to it, and an issue archived after it was
+ * linked must still close its task.
+ */
+export const getLinearIssuesByIds = (accessToken: string, ids: string[]): Promise<LinearIssue[]> =>
+ fetchLinearIssuesByIds(accessToken, ids);
+
+/**
+ * Only the archived ones among these issues. Filtered by Linear, so checking a
+ * long tail of closed issues costs a request per page but returns almost nothing.
+ */
+export const getArchivedLinearIssuesByIds = (
+ accessToken: string,
+ ids: string[],
+): Promise<LinearIssue[]> =>
+ fetchLinearIssuesByIds(accessToken, ids, { archivedAt: { null: false } });
+
/** A comment on an issue, with what a sync copies onto the task. */
export interface LinearIssueComment {
body: string;
diff --git a/apps/server/src/services/linear/syncJob.ts b/apps/server/src/services/linear/syncJob.ts
index b86fc1f168a..521a1926a7d 100644
--- a/apps/server/src/services/linear/syncJob.ts
+++ b/apps/server/src/services/linear/syncJob.ts
@@ -65,8 +65,10 @@ export const mergeLinearSyncResults = (
{ resumed }: { resumed: boolean },
): LinearSyncResult => {
if (!previous) return latest;
+ const archived = (previous.archived ?? 0) + (latest.archived ?? 0);
const commentsImported = (previous.commentsImported ?? 0) + (latest.commentsImported ?? 0);
const written = {
+ ...(archived ? { archived } : {}),
closed: previous.closed + latest.closed,
...(commentsImported ? { commentsImported } : {}),
created: previous.created + latest.created,
diff --git a/locales/en-US/integration.json b/locales/en-US/integration.json
index 0dde067eed8..b9b7e9e6a63 100644
--- a/locales/en-US/integration.json
+++ b/locales/en-US/integration.json
@@ -97,6 +97,7 @@
"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.live": "Archived in Linear, but the task has a live schedule or an open goal; a later sync archives 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",
"linear.sync.job.skipReason.unavailable": "Task is in the trash or not visible to you",
@@ -126,8 +127,8 @@
"linear.sync.modal.title": "Import issues from {{account}}",
"linear.sync.options.importTitle": "Import options",
"linear.sync.options.includeArchived": "Include archived issues",
- "linear.sync.options.includeArchivedDesc": "Also list and import issues archived in Linear, which are left out otherwise",
- "linear.sync.options.includeArchivedRuleDesc": "Also sync issues archived in Linear that match this rule",
+ "linear.sync.options.includeArchivedDesc": "Also list and import issues archived in Linear, and archive their tasks here too",
+ "linear.sync.options.includeArchivedRuleDesc": "Also sync issues archived in Linear that match this rule, and archive their tasks",
"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",
@@ -138,6 +139,7 @@
"linear.sync.project.noConnection": "No Linear workspace is connected yet.",
"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.archived": "{{count}} archived",
"linear.sync.result.closed": "{{count}} closed",
"linear.sync.result.commentsImported": "{{count}} comments added",
"linear.sync.result.created": "{{count}} created",
diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.json
index df49782941e..9d248875676 100644
--- a/locales/zh-CN/integration.json
+++ b/locales/zh-CN/integration.json
@@ -97,6 +97,7 @@
"linear.sync.job.skipReason.closed": "在 Linear 中已关闭,未导入",
"linear.sync.job.skipReason.commentsFailed": "任务已同步,但评论未能同步,下次同步会重试",
"linear.sync.job.skipReason.failed": "写入失败,下次同步会重试",
+ "linear.sync.job.skipReason.live": "已在 Linear 归档,但任务还有生效中的定时或未结束的目标,之后的同步会归档",
"linear.sync.job.skipReason.missing": "Linear 中已不存在,或当前连接无权访问",
"linear.sync.job.skipReason.running": "任务正在运行,未关闭",
"linear.sync.job.skipReason.unavailable": "任务在回收站或你无权查看",
@@ -126,8 +127,8 @@
"linear.sync.modal.title": "从 {{account}} 导入 Issue",
"linear.sync.options.importTitle": "导入选项",
"linear.sync.options.includeArchived": "包含已归档的 Issue",
- "linear.sync.options.includeArchivedDesc": "同时列出并导入 Linear 中已归档的 Issue,默认不包含",
- "linear.sync.options.includeArchivedRuleDesc": "同时同步符合此规则、在 Linear 中已归档的 Issue",
+ "linear.sync.options.includeArchivedDesc": "同时列出并导入 Linear 中已归档的 Issue,对应任务也会归档",
+ "linear.sync.options.includeArchivedRuleDesc": "同时同步符合此规则、在 Linear 中已归档的 Issue,对应任务也会归档",
"linear.sync.options.syncComments": "同步评论",
"linear.sync.options.syncCommentsDesc": "把 Issue 下的 Linear 评论导入到任务活动,保留原作者和时间",
"linear.sync.options.syncCommentsRuleDesc": "已同步的任务也会补上缺少的评论",
@@ -138,6 +139,7 @@
"linear.sync.project.noConnection": "还没有连接 Linear 工作区。",
"linear.sync.project.title": "从 Linear 同步",
"linear.sync.projectHint": "要把 Issue 同步到项目,请打开项目,进入「设置 → 高级设置」。",
+ "linear.sync.result.archived": "归档 {{count}} 个",
"linear.sync.result.closed": "关闭 {{count}} 个",
"linear.sync.result.commentsImported": "新增评论 {{count}} 条",
"linear.sync.result.created": "新建 {{count}} 个",
diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.ts
index 8101334cfd9..06ac515fbd3 100644
--- a/packages/locales/src/default/integration.ts
+++ b/packages/locales/src/default/integration.ts
@@ -124,6 +124,8 @@ export default {
'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.live':
+ 'Archived in Linear, but the task has a live schedule or an open goal; a later sync archives 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',
'linear.sync.job.skipReason.unavailable': 'Task is in the trash or not visible to you',
@@ -155,9 +157,9 @@ export default {
'linear.sync.options.importTitle': 'Import options',
'linear.sync.options.includeArchived': 'Include archived issues',
'linear.sync.options.includeArchivedDesc':
- 'Also list and import issues archived in Linear, which are left out otherwise',
+ 'Also list and import issues archived in Linear, and archive their tasks here too',
'linear.sync.options.includeArchivedRuleDesc':
- 'Also sync issues archived in Linear that match this rule',
+ 'Also sync issues archived in Linear that match this rule, and archive their tasks',
'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",
@@ -172,6 +174,7 @@ export default {
'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.archived': '{{count}} archived',
'linear.sync.result.closed': '{{count}} closed',
'linear.sync.result.commentsImported': '{{count}} comments added',
'linear.sync.result.created': '{{count}} created',
diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.ts
index 33978b94b56..de50089c8ad 100644
--- a/packages/types/src/linear.ts
+++ b/packages/types/src/linear.ts
@@ -77,6 +77,12 @@ export type TaskExternalProvider = 'linear';
/** Facts about the linked Linear issue kept on the link row, for display only. */
export interface LinearIssueLinkMetadata {
+ /**
+ * The Linear archive the task already took up. Each archive applies once, so
+ * a task restored in LobeHub stays restored while the issue stays archived.
+ * Gone once Linear restores the issue, so archiving it again applies again.
+ */
+ appliedArchivedAt?: string;
assigneeName?: string;
/**
* The issue's comments were read and copied at least once. A closed task
@@ -138,6 +144,8 @@ export interface LinearIssueCount {
/** Why an issue was left alone. */
export type LinearSyncSkipReason =
+ /** Linear archived it, but the task has a live schedule or heartbeat or an open Goal; a later run retries. */
+ | 'live'
/** Linear closed it, but the task is running; it is not interrupted. */
| 'running'
/** The linked task is in the trash or no longer visible to the caller. */
@@ -152,6 +160,8 @@ export type LinearSyncSkipReason =
| 'missing';
export interface LinearSyncResult {
+ /** Tasks archived because their issue was archived in Linear. Absent in older results. */
+ archived?: number;
/** 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. */
diff --git a/src/features/Projects/LinearSync/utils.test.ts b/src/features/Projects/LinearSync/utils.test.ts
index 65678fc844b..706230dd568 100644
--- a/src/features/Projects/LinearSync/utils.test.ts
+++ b/src/features/Projects/LinearSync/utils.test.ts
@@ -31,6 +31,12 @@ const result = (overrides: Partial<LinearSyncResult>): LinearSyncResult => ({
});
describe('formatLinearSyncResult', () => {
+ it('says how many tasks were archived, so a created task missing from the list is explained', () => {
+ expect(formatLinearSyncResult(result({ archived: 1, created: 2 }), t)).toBe(
+ 'linear.sync.result.created:2 · linear.sync.result.archived:1',
+ );
+ });
+
it('lists only what changed, and says when more remain', () => {
expect(
formatLinearSyncResult(
diff --git a/src/features/Projects/LinearSync/utils.ts b/src/features/Projects/LinearSync/utils.ts
index f01c83c8375..1000998b35f 100644
--- a/src/features/Projects/LinearSync/utils.ts
+++ b/src/features/Projects/LinearSync/utils.ts
@@ -79,6 +79,7 @@ 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.archived && t('linear.sync.result.archived', { count: result.archived }),
result.commentsImported &&
t('linear.sync.result.commentsImported', { count: result.commentsImported }),
result.keptLocalEdits &&