Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(linear): option to include archived issues in a sync (#22340)

Rdmclin2d7b7610a6e69
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.ts
index 24d81059060..6b5020fa6d4 100644
--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts
@@ -224,6 +224,16 @@ describe('linearRouter', () => {
expect.objectContaining({ connectionId: connection.id, ...filter }),
);
+ await caller({ userId }).countIssues({
+ connectionId: connection.id,
+ ...filter,
+ includeArchived: true,
+ });
+ expect(mocks.countIssues).toHaveBeenLastCalledWith(
+ 'token',
+ expect.objectContaining({ includeArchived: true, ...filter }),
+ );
+
await expect(
caller({ userId }).countIssues({ connectionId: other.id, ...filter }),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
@@ -1047,6 +1057,41 @@ describe('linearRouter', () => {
);
});
+ it('leaves archived issues out of a rule run unless that run asks for them', async () => {
+ const connection = await connect({ userId });
+ mocks.getToken.mockResolvedValue('token');
+ mocks.runSync.mockResolvedValue({ ok: true });
+ mocks.syncByFilter.mockResolvedValue(syncResult);
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ // @ts-expect-error A rule does not keep this: archived issues are chosen per run.
+ includeArchived: true,
+ projectId,
+ stateTypes: ['completed'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+
+ const plain = await caller({ userId }).startRuleSync({ ruleId: rule.id });
+ await new LinearSyncJobService(serverDB, userId).run(plain.id);
+ expect(mocks.syncByFilter).toHaveBeenLastCalledWith(
+ 'token',
+ expect.objectContaining({ includeArchived: undefined, teamId: 'team-1' }),
+ expect.anything(),
+ );
+
+ const archived = await caller({ userId }).startRuleSync({
+ includeArchived: true,
+ ruleId: rule.id,
+ });
+ await new LinearSyncJobService(serverDB, userId).run(archived.id);
+ expect(mocks.syncByFilter).toHaveBeenLastCalledWith(
+ 'token',
+ expect.objectContaining({ includeArchived: true, teamId: 'team-1' }),
+ expect.anything(),
+ );
+ });
+
it("lists only the project's own rules, and drops them with the project", async () => {
const connection = await connect({ userId });
await serverDB
diff --git a/apps/server/src/routers/lambda/linear.ts b/apps/server/src/routers/lambda/linear.ts
index 2107ef24f99..0220d447ab3 100644
--- a/apps/server/src/routers/lambda/linear.ts
+++ b/apps/server/src/routers/lambda/linear.ts
@@ -48,6 +48,8 @@ const MAX_IMPORT_ISSUES = 500;
const stateTypesInput = z.array(z.enum(LINEAR_ISSUE_STATE_TYPES)).min(1);
const issueFilterInput = connectionInput.extend({
+ /** Also list archived issues, which Linear leaves out unless asked. */
+ includeArchived: z.boolean().optional(),
linearProjectId: z.string().nullish(),
stateTypes: stateTypesInput,
teamId: z.string().min(1),
@@ -219,10 +221,14 @@ export const linearRouter = router({
createSyncRule: linearTaskWriteProcedure
.input(
- issueFilterInput.merge(projectInput).extend({
- linearProjectName: z.string().max(255).nullish(),
- teamName: z.string().min(1).max(255),
- }),
+ // A rule keeps what to match; archived issues are chosen per run, in `startRuleSync`.
+ issueFilterInput
+ .omit({ includeArchived: true })
+ .merge(projectInput)
+ .extend({
+ linearProjectName: z.string().max(255).nullish(),
+ teamName: z.string().min(1).max(255),
+ }),
)
.mutation(async ({ ctx, input }) => {
await requireWritableConnection(ctx, input.connectionId);
@@ -262,6 +268,8 @@ export const linearRouter = router({
startRuleSync: linearTaskWriteProcedure
.input(
z.object({
+ /** Also sync archived issues; a per-run choice, like `syncComments`. */
+ includeArchived: z.boolean().optional(),
ruleId: z.string().uuid(),
/** Also copy each issue's Linear comments onto its task. */
syncComments: z.boolean().optional(),
@@ -283,6 +291,7 @@ export const linearRouter = router({
ctx.scope.workspaceId ?? undefined,
{
connectionId: rule.connectionId,
+ includeArchived: input.includeArchived || undefined,
kind: 'rule',
projectId: rule.projectId,
ruleId: rule.id,
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 bf6d952c3b4..988b9d887de 100644
--- a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
+++ b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
@@ -861,3 +861,87 @@ describe('LinearIssueSyncService comments (real PostgreSQL)', () => {
);
});
});
+
+describe('LinearIssueSyncService archived issues (real PostgreSQL, Linear over fetch)', () => {
+ /** Linear's own rule: archived issues are left out unless the query asks for them. */
+ let linearIssues: (LinearIssue & { archived?: boolean })[] = [];
+
+ beforeEach(async () => {
+ const actual = await vi.importActual<typeof IssuesModule>('../issues');
+ linear.listLinearIssues.mockImplementation(actual.listLinearIssues);
+ linear.getLinearIssuesByIds.mockImplementation(actual.getLinearIssuesByIds);
+ linear.getLinearProjectTeamIds.mockImplementation(actual.getLinearProjectTeamIds);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_url: string, init: RequestInit) => {
+ const { query, variables } = JSON.parse(init.body as string) as {
+ query: string;
+ variables: { filter?: any; includeArchived?: boolean };
+ };
+ const includeArchived =
+ variables.includeArchived === true || query.includes('includeArchived: true');
+ const { filter: where = {} } = variables;
+ const nodes = linearIssues
+ .filter((item) => includeArchived || !item.archived)
+ .filter((item) => !where.id || where.id.in.includes(item.id))
+ .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);
+ return new Response(
+ JSON.stringify({
+ data: { issues: { nodes, pageInfo: { endCursor: null, hasNextPage: false } } },
+ }),
+ { status: 200 },
+ );
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ linearIssues = [];
+ });
+
+ const done = { name: 'Done', type: 'completed' } as const;
+
+ it('syncs archived issues of a rule only when the run asks for them', async () => {
+ linearIssues = [
+ issue({ id: '1', state: done }),
+ { ...issue({ id: '2', state: done }), archived: true },
+ ];
+ const service = new LinearIssueSyncService(db, userId);
+ const rule = { stateTypes: ['completed' as const], teamId: TEAM };
+
+ const plain = await service.syncByFilter(TOKEN, rule);
+ expect(plain.created).toBe(1);
+ expect(await linkedTask('2')).toBeNull();
+
+ const withArchived = await service.syncByFilter(TOKEN, { ...rule, includeArchived: true });
+ expect(withArchived).toMatchObject({ created: 1, unchanged: 1 });
+ expect((await linkedTask('2'))?.status).toBe('completed');
+ });
+
+ it('imports a picked archived issue instead of reporting it missing', async () => {
+ linearIssues = [{ ...issue({ id: '1', state: done }), archived: true }];
+
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+
+ expect(result).toMatchObject({ created: 1, skipped: [], skippedCount: 0 });
+ expect((await linkedTask('1'))?.status).toBe('completed');
+ });
+
+ it('closes the task of a linked issue Linear completed and archived since', async () => {
+ linearIssues = [issue({ id: '1' })];
+ const service = new LinearIssueSyncService(db, userId);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+
+ linearIssues = [{ ...issue({ id: '1', state: done }), archived: true }];
+ const result = await service.syncByFilter(TOKEN, {
+ ...filter,
+ stateTypes: [...filter.stateTypes],
+ });
+
+ expect(result.closed).toBe(1);
+ expect((await linkedTask('1'))?.status).toBe('completed');
+ });
+});
diff --git a/apps/server/src/services/linear/__tests__/issues.test.ts b/apps/server/src/services/linear/__tests__/issues.test.ts
index 7240ed005f3..3ccf264a4f2 100644
--- a/apps/server/src/services/linear/__tests__/issues.test.ts
+++ b/apps/server/src/services/linear/__tests__/issues.test.ts
@@ -2,7 +2,12 @@
import { LINEAR_NO_PROJECT_ID } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { countLinearIssues, getLinearProjectTeamIds, listLinearIssues } from '../issues';
+import {
+ countLinearIssues,
+ getLinearIssuesByIds,
+ getLinearProjectTeamIds,
+ listLinearIssues,
+} from '../issues';
const fetchMock = vi.fn();
@@ -68,6 +73,42 @@ describe('listLinearIssues filter', () => {
});
});
+describe('archived issues', () => {
+ it('leaves archived issues out of the list and the count unless asked, as Linear does', async () => {
+ fetchMock.mockImplementation(async () => reply(emptyIssues));
+ const filter = { stateTypes: ['completed' as const], teamId: 'team-pkg' };
+
+ await listLinearIssues('token', filter);
+ await countLinearIssues('token', filter);
+ await listLinearIssues('token', { ...filter, includeArchived: true });
+ await countLinearIssues('token', { ...filter, includeArchived: true });
+
+ const sent = fetchMock.mock.calls.map((call) => requestBody(call));
+ for (const body of sent) {
+ expect(body.query).toContain('includeArchived: $includeArchived');
+ }
+ expect(sent.map((body) => body.variables.includeArchived)).toEqual([false, false, true, true]);
+ });
+
+ it('looks picked and linked issues up by id whether archived or not', async () => {
+ fetchMock.mockResolvedValue(
+ reply({
+ issues: {
+ nodes: [{ id: 'archived-1' }],
+ pageInfo: { endCursor: null, hasNextPage: false },
+ },
+ }),
+ );
+
+ const issues = await getLinearIssuesByIds('token', ['archived-1']);
+
+ expect(issues).toMatchObject([{ id: 'archived-1' }]);
+ const body = requestBody(fetchMock.mock.calls[0]);
+ expect(body.query).toContain('includeArchived: true');
+ expect(body.variables.filter).toEqual({ id: { in: ['archived-1'] } });
+ });
+});
+
describe('getLinearProjectTeamIds', () => {
it('reads every page of the teams a project belongs to', async () => {
fetchMock
@@ -141,6 +182,7 @@ describe('countLinearIssues', () => {
team: { id: { eq: 'team-pkg' } },
},
first: 50,
+ includeArchived: false,
});
expect(requestBody(fetchMock.mock.calls[1]).variables.after).toBe('cursor-1');
});
diff --git a/apps/server/src/services/linear/issues.ts b/apps/server/src/services/linear/issues.ts
index 9571ae92980..58802a665d3 100644
--- a/apps/server/src/services/linear/issues.ts
+++ b/apps/server/src/services/linear/issues.ts
@@ -92,6 +92,12 @@ export const listLinearProjects = async (
};
export interface LinearIssueFilter {
+ /**
+ * Also match archived issues. Archiving is not a state: Linear sets
+ * `archivedAt` and leaves `state` alone, and its issue queries skip archived
+ * issues unless asked. Absent: archived issues are left out, as in Linear.
+ */
+ includeArchived?: boolean;
/** A Linear project, `LINEAR_NO_PROJECT_ID` for issues in none, or empty for the whole team. */
linearProjectId?: string | null;
stateTypes: LinearIssueStateType[];
@@ -149,8 +155,8 @@ export const listLinearIssues = async (
): Promise<{ cursor?: string; hasMore: boolean; issues: LinearIssue[] }> => {
const data = await linearGraphql<{ issues: Connection<LinearIssue> }>(
accessToken,
- `query LobeIssues($first: Int!, $after: String, $filter: IssueFilter) {
- issues(first: $first, after: $after, orderBy: updatedAt, filter: $filter) {
+ `query LobeIssues($first: Int!, $after: String, $filter: IssueFilter, $includeArchived: Boolean) {
+ issues(first: $first, after: $after, orderBy: updatedAt, filter: $filter, includeArchived: $includeArchived) {
nodes { ${ISSUE_FIELDS} }
pageInfo { hasNextPage endCursor }
}
@@ -159,6 +165,7 @@ export const listLinearIssues = async (
after: options.after,
filter: toIssueFilter(filter),
first: Math.min(options.first ?? LINEAR_PAGE_SIZE, LINEAR_PAGE_SIZE),
+ includeArchived: !!filter.includeArchived,
},
);
const { nodes, pageInfo } = data.issues;
@@ -187,8 +194,8 @@ export const countLinearIssues = async (
do {
const data = await linearGraphql<{ issues: Connection<{ id: string }> }>(
accessToken,
- `query LobeIssueCount($first: Int!, $after: String, $filter: IssueFilter) {
- issues(first: $first, after: $after, filter: $filter) {
+ `query LobeIssueCount($first: Int!, $after: String, $filter: IssueFilter, $includeArchived: Boolean) {
+ issues(first: $first, after: $after, filter: $filter, includeArchived: $includeArchived) {
nodes { id }
pageInfo { hasNextPage endCursor }
}
@@ -197,6 +204,7 @@ export const countLinearIssues = async (
after,
filter: toIssueFilter(filter),
first: Math.min(LINEAR_PAGE_SIZE, limit - count),
+ includeArchived: !!filter.includeArchived,
},
);
count += data.issues.nodes.length;
@@ -207,7 +215,13 @@ 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. */
+/**
+ * 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 (
accessToken: string,
ids: string[],
@@ -218,7 +232,7 @@ export const getLinearIssuesByIds = async (
const data = await linearGraphql<{ issues: Connection<LinearIssue> }>(
accessToken,
`query LobeIssuesById($first: Int!, $filter: IssueFilter) {
- issues(first: $first, filter: $filter) {
+ issues(first: $first, filter: $filter, includeArchived: true) {
nodes { ${ISSUE_FIELDS} }
pageInfo { hasNextPage endCursor }
}
diff --git a/apps/server/src/services/linear/syncJob.ts b/apps/server/src/services/linear/syncJob.ts
index 6f1a0b0edc4..b86fc1f168a 100644
--- a/apps/server/src/services/linear/syncJob.ts
+++ b/apps/server/src/services/linear/syncJob.ts
@@ -345,7 +345,12 @@ export class LinearSyncJobService {
const token = await getLinearAccessToken(this.db, rule.connectionId);
return sync.syncByFilter(
token,
- { linearProjectId: rule.linearProjectId, stateTypes: rule.stateTypes, teamId: rule.teamId },
+ {
+ includeArchived: metadata.includeArchived,
+ linearProjectId: rule.linearProjectId,
+ stateTypes: rule.stateTypes,
+ teamId: rule.teamId,
+ },
{ ...options, noCreate: metadata.reconcileOnly, startAfter: metadata.cursor },
);
}
diff --git a/locales/en-US/integration.json b/locales/en-US/integration.json
index a1f4bbfd961..0dde067eed8 100644
--- a/locales/en-US/integration.json
+++ b/locales/en-US/integration.json
@@ -125,6 +125,9 @@
"linear.sync.modal.saveRuleHint": "Sync every issue matching these filters now, and keep the filters to sync again later",
"linear.sync.modal.title": "Import issues from {{account}}",
"linear.sync.options.importTitle": "Import options",
+ "linear.sync.options.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.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",
diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.json
index a824893e721..df49782941e 100644
--- a/locales/zh-CN/integration.json
+++ b/locales/zh-CN/integration.json
@@ -125,6 +125,9 @@
"linear.sync.modal.saveRuleHint": "立即同步符合当前筛选的所有 Issue,并保存筛选条件以便之后再次同步",
"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.syncComments": "同步评论",
"linear.sync.options.syncCommentsDesc": "把 Issue 下的 Linear 评论导入到任务活动,保留原作者和时间",
"linear.sync.options.syncCommentsRuleDesc": "已同步的任务也会补上缺少的评论",
diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.ts
index b92405486a6..8101334cfd9 100644
--- a/packages/locales/src/default/integration.ts
+++ b/packages/locales/src/default/integration.ts
@@ -153,6 +153,11 @@ export default {
'Sync every issue matching these filters now, and keep the filters to sync again later',
'linear.sync.modal.title': 'Import issues from {{account}}',
'linear.sync.options.importTitle': 'Import options',
+ 'linear.sync.options.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.syncComments': 'Sync comments',
'linear.sync.options.syncCommentsDesc':
"Copy each issue's Linear comments into the task's activity, keeping the author and time",
diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.ts
index e03a06a6786..33978b94b56 100644
--- a/packages/types/src/linear.ts
+++ b/packages/types/src/linear.ts
@@ -213,6 +213,11 @@ export interface LinearSyncJobMetadata {
* requests deep, so a run stops handing off after a few.
*/
handOffs?: number;
+ /**
+ * A rule run also reads archived issues (`kind: 'rule'`). Picked issues are
+ * looked up by id, which finds archived ones either way.
+ */
+ includeArchived?: boolean;
/** Picked issues (`kind: 'issues'`). */
issueIds?: string[];
kind: 'issues' | 'rule';
diff --git a/src/features/Integrations/Linear/swrKeys.ts b/src/features/Integrations/Linear/swrKeys.ts
index a0dae6a3b1f..e9006f68496 100644
--- a/src/features/Integrations/Linear/swrKeys.ts
+++ b/src/features/Integrations/Linear/swrKeys.ts
@@ -2,6 +2,7 @@ import type { LinearIssueStateType } from '@lobechat/types';
interface IssueFilterKeyParams {
connectionId: string;
+ includeArchived?: boolean;
linearProjectId?: string | null;
stateTypes: LinearIssueStateType[];
teamId: string;
@@ -13,6 +14,7 @@ const issueFilterKey = (params: IssueFilterKeyParams) =>
params.teamId,
params.linearProjectId ?? null,
[...params.stateTypes].sort().join(','),
+ !!params.includeArchived,
] as const;
/**
diff --git a/src/features/Projects/LinearSync/ImportIssuesContent.tsx b/src/features/Projects/LinearSync/ImportIssuesContent.tsx
index 0c9cb6a331b..a5a6e931254 100644
--- a/src/features/Projects/LinearSync/ImportIssuesContent.tsx
+++ b/src/features/Projects/LinearSync/ImportIssuesContent.tsx
@@ -23,7 +23,7 @@ import { jobsShownInDialog, useLinearSyncJobs } from './useLinearSyncJobs';
import {
canLeaveLinearScopeStep,
isActiveLinearSyncJob,
- linearScopeProjectLabel,
+ linearImportScopeSummary,
linearSyncErrorMessage,
} from './utils';
@@ -31,9 +31,9 @@ type Step = 'scope' | 'issues' | 'run';
/**
* Import Linear issues into the project in three steps: pick the scope (team,
- * Linear project, states), pick issues — or save the scope as a rule and sync
- * all of it — then watch the sync. The sync runs in the background, so the
- * dialog can be closed while it works. Linear is only read.
+ * Linear project, states) and the import options, pick issues — or save the
+ * scope as a rule and sync all of it — then watch the sync. The sync runs in the
+ * background, so the dialog can be closed while it works. Linear is only read.
*/
const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
({ connection, onSynced, projectId }) => {
@@ -44,6 +44,8 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
const [selected, setSelected] = useState<Set<string>>(() => new Set());
// Comments carry much of an issue's context, so they come along unless unchecked.
const [syncComments, setSyncComments] = useState(true);
+ // Archived issues stay out, as in Linear, unless asked for.
+ const [includeArchived, setIncludeArchived] = useState(false);
const [starting, setStarting] = useState<'import' | 'rule' | null>(null);
const [jobId, setJobId] = useState<string>();
// Shown as the running title until the job loads, so a single import never reads as a rule sync.
@@ -74,6 +76,12 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
setSelected(new Set());
};
+ const changeIncludeArchived = (checked: boolean) => {
+ setIncludeArchived(checked);
+ // The list changes with it; a hidden selection would import blind.
+ setSelected(new Set());
+ };
+
const changeSelection = (ids: string[], checked: boolean) =>
setSelected((current) => {
const next = new Set(current);
@@ -126,7 +134,7 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
ruleId = rule.id;
setSavedRuleId(rule.id);
}
- return linearService.startRuleSync(ruleId, { syncComments });
+ return linearService.startRuleSync(ruleId, { includeArchived, syncComments });
});
const leaveRunning = () => {
@@ -134,12 +142,6 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
close();
};
- const scopeLabel = [
- filter.teamName,
- linearScopeProjectLabel(filter, t, { withAll: true }),
- t('linear.sync.filter.statesSummary', { count: filter.stateTypes.length }),
- ].join(' · ');
-
const footer = (() => {
if (step === 'scope') {
return (
@@ -222,30 +224,34 @@ const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
return (
<Flexbox gap={20}>
{step === 'scope' ? (
- <ScopeStep connectionId={connection.id} value={filter} onChange={updateFilter} />
+ <>
+ <ScopeStep connectionId={connection.id} value={filter} onChange={updateFilter} />
+ <ImportOptions
+ includeArchived={includeArchived}
+ syncComments={syncComments}
+ onIncludeArchivedChange={changeIncludeArchived}
+ onSyncCommentsChange={setSyncComments}
+ />
+ </>
) : null}
{step === 'issues' ? (
<Flexbox gap={12}>
<Text ellipsis fontSize={12} type={'secondary'}>
- {scopeLabel}
+ {linearImportScopeSummary(filter, { includeArchived }, t)}
</Text>
<IssueList
disabled={starting !== null}
selected={selected}
filter={{
connectionId: connection.id,
+ includeArchived,
linearProjectId: filter.linearProjectId,
stateTypes: filter.stateTypes,
teamId: filter.teamId!,
}}
onSelectionChange={changeSelection}
/>
- <ImportOptions
- disabled={starting !== null}
- syncComments={syncComments}
- onSyncCommentsChange={setSyncComments}
- />
</Flexbox>
) : null}
diff --git a/src/features/Projects/LinearSync/ImportOptions.tsx b/src/features/Projects/LinearSync/ImportOptions.tsx
index 375ef518d18..d0ff710467e 100644
--- a/src/features/Projects/LinearSync/ImportOptions.tsx
+++ b/src/features/Projects/LinearSync/ImportOptions.tsx
@@ -19,14 +19,38 @@ const styles = stylex.create({
});
interface ImportOptionsProps {
- disabled?: boolean;
+ includeArchived: boolean;
+ onIncludeArchivedChange: (checked: boolean) => void;
onSyncCommentsChange: (checked: boolean) => void;
syncComments: boolean;
}
+interface OptionProps {
+ checked: boolean;
+ desc: string;
+ label: string;
+ onChange: (checked: boolean) => void;
+}
+
+const Option = memo<OptionProps>(({ checked, desc, label, onChange }) => (
+ <label {...stylex.props(styles.option)}>
+ <Flexbox horizontal align={'flex-start'} gap={8}>
+ <Checkbox checked={checked} style={{ marginBlockStart: 2 }} onChange={onChange} />
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text>{label}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {desc}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ </label>
+));
+
+Option.displayName = 'LinearImportOption';
+
/** What an import brings along besides the issues themselves. */
const ImportOptions = memo<ImportOptionsProps>(
- ({ disabled, onSyncCommentsChange, syncComments }) => {
+ ({ includeArchived, onIncludeArchivedChange, onSyncCommentsChange, syncComments }) => {
const { t } = useTranslation('integration');
return (
@@ -34,24 +58,20 @@ const ImportOptions = memo<ImportOptionsProps>(
<Text fontSize={12} type={'secondary'} weight={500}>
{t('linear.sync.options.importTitle')}
</Text>
- <div {...stylex.props(styles.group)}>
- <label {...stylex.props(styles.option)}>
- <Flexbox horizontal align={'flex-start'} gap={8}>
- <Checkbox
- checked={syncComments}
- disabled={disabled}
- style={{ marginBlockStart: 2 }}
- onChange={onSyncCommentsChange}
- />
- <Flexbox gap={2} style={{ minWidth: 0 }}>
- <Text>{t('linear.sync.options.syncComments')}</Text>
- <Text fontSize={12} type={'secondary'}>
- {t('linear.sync.options.syncCommentsDesc')}
- </Text>
- </Flexbox>
- </Flexbox>
- </label>
- </div>
+ <Flexbox gap={12} {...stylex.props(styles.group)}>
+ <Option
+ checked={syncComments}
+ desc={t('linear.sync.options.syncCommentsDesc')}
+ label={t('linear.sync.options.syncComments')}
+ onChange={onSyncCommentsChange}
+ />
+ <Option
+ checked={includeArchived}
+ desc={t('linear.sync.options.includeArchivedDesc')}
+ label={t('linear.sync.options.includeArchived')}
+ onChange={onIncludeArchivedChange}
+ />
+ </Flexbox>
</Flexbox>
);
},
diff --git a/src/features/Projects/LinearSync/IssueList.test.tsx b/src/features/Projects/LinearSync/IssueList.test.tsx
index 70c6e55116f..9f00be0c7d7 100644
--- a/src/features/Projects/LinearSync/IssueList.test.tsx
+++ b/src/features/Projects/LinearSync/IssueList.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import type { LinearIssuePage, LinearIssueSummary } from '@lobechat/types';
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -44,10 +44,10 @@ const page = (count: number, hasMore: boolean): LinearIssuePage => ({
issues: Array.from({ length: count }, (_, index) => issue(index)),
});
-const renderList = () =>
+const renderList = (listFilter: typeof filter & { includeArchived?: boolean } = filter) =>
render(
<SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
- <IssueList filter={filter} selected={new Set()} onSelectionChange={vi.fn()} />
+ <IssueList filter={listFilter} selected={new Set()} onSelectionChange={vi.fn()} />
</SWRConfig>,
);
@@ -87,3 +87,23 @@ describe('IssueList header', () => {
expect(mocks.countIssues).not.toHaveBeenCalled();
});
});
+
+describe('IssueList archived issues', () => {
+ it('asks for archived issues on every page, reading on from the cursor', async () => {
+ mocks.listIssues.mockImplementation(async ({ cursor }: { cursor?: string }) =>
+ cursor ? page(3, false) : page(50, true),
+ );
+ mocks.countIssues.mockResolvedValue({ capped: false, count: 53 });
+ const archivedFilter = { ...filter, includeArchived: true };
+
+ renderList(archivedFilter);
+ fireEvent.click(await screen.findByText('linear.sync.list.loadMore'));
+
+ // The first page is refetched too, so the order of calls is not fixed.
+ await waitFor(() =>
+ expect(mocks.listIssues).toHaveBeenCalledWith({ ...archivedFilter, cursor: 'cursor-1' }),
+ );
+ expect(mocks.listIssues).toHaveBeenCalledWith({ ...archivedFilter, cursor: undefined });
+ expect(mocks.countIssues).toHaveBeenCalledWith(archivedFilter);
+ });
+});
diff --git a/src/features/Projects/LinearSync/IssueList.tsx b/src/features/Projects/LinearSync/IssueList.tsx
index e4503804414..b9951c4b955 100644
--- a/src/features/Projects/LinearSync/IssueList.tsx
+++ b/src/features/Projects/LinearSync/IssueList.tsx
@@ -86,7 +86,7 @@ const IssueList = memo<IssueListProps>(({ disabled, filter, onSelectionChange, s
if (!filter || (previous && !previous.hasMore)) return null;
return [...linearKeys.issues(filter), index === 0 ? null : previous?.cursor] as const;
},
- ([, , , , , cursor]) => linearService.listIssues({ ...filter!, cursor: cursor ?? undefined }),
+ ([, , , , , , cursor]) => linearService.listIssues({ ...filter!, cursor: cursor ?? undefined }),
// The first page is refetched even when cached: an import since it was read
// changes which issues show as synced.
{ revalidateOnFocus: false },
diff --git a/src/features/Projects/LinearSync/SyncRules.test.tsx b/src/features/Projects/LinearSync/SyncRules.test.tsx
index a58839c9cf5..65aa8849902 100644
--- a/src/features/Projects/LinearSync/SyncRules.test.tsx
+++ b/src/features/Projects/LinearSync/SyncRules.test.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -63,4 +63,18 @@ describe('SyncRules', () => {
expect(main).toBeEnabled();
expect(menu).toBeEnabled();
});
+
+ it('runs a rule without archived issues unless that is asked for', async () => {
+ linearServiceMocks.startRuleSync.mockResolvedValue({ id: 'job-1' });
+ renderRules([]);
+
+ fireEvent.click(await screen.findByText('linear.sync.rules.run'));
+
+ await waitFor(() =>
+ expect(linearServiceMocks.startRuleSync).toHaveBeenCalledWith('rule-1', {
+ includeArchived: false,
+ syncComments: true,
+ }),
+ );
+ });
});
diff --git a/src/features/Projects/LinearSync/SyncRules.tsx b/src/features/Projects/LinearSync/SyncRules.tsx
index ead11fc558a..7216ffc5d58 100644
--- a/src/features/Projects/LinearSync/SyncRules.tsx
+++ b/src/features/Projects/LinearSync/SyncRules.tsx
@@ -77,6 +77,8 @@ const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, proje
// Tucked into each rule's sync menu; applies to the next run of any rule, and
// re-running with it on fills in the comments already-synced tasks lack.
const [syncComments, setSyncComments] = useState(true);
+ // Off by default, as in Linear; on, a run also reaches the rule's archived issues.
+ const [includeArchived, setIncludeArchived] = useState(false);
const optionItems: DropdownItem[] = [
{
children: [
@@ -89,6 +91,15 @@ const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, proje
onCheckedChange: setSyncComments,
type: 'checkbox',
},
+ {
+ checked: includeArchived,
+ closeOnClick: false,
+ desc: t('linear.sync.options.includeArchivedRuleDesc'),
+ key: 'includeArchived',
+ label: t('linear.sync.options.includeArchived'),
+ onCheckedChange: setIncludeArchived,
+ type: 'checkbox',
+ },
],
key: 'options',
label: t('linear.sync.options.syncTitle'),
@@ -118,7 +129,7 @@ const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, proje
const runRule = async (rule: LinearSyncRuleView) => {
setStarting(rule.id);
try {
- await linearService.startRuleSync(rule.id, { syncComments });
+ await linearService.startRuleSync(rule.id, { includeArchived, syncComments });
onJobStarted();
} catch (error) {
toast.error(linearSyncErrorMessage(error, t));
diff --git a/src/features/Projects/LinearSync/utils.test.ts b/src/features/Projects/LinearSync/utils.test.ts
index 40372281336..65678fc844b 100644
--- a/src/features/Projects/LinearSync/utils.test.ts
+++ b/src/features/Projects/LinearSync/utils.test.ts
@@ -7,6 +7,7 @@ import {
canLeaveLinearScopeStep,
formatLinearSyncResult,
isActiveLinearSyncJob,
+ linearImportScopeSummary,
linearIssueListCounts,
linearScopeProjectLabel,
linearSyncJobErrorMessage,
@@ -136,6 +137,24 @@ describe('linearIssueListCounts', () => {
});
});
+describe('linearImportScopeSummary', () => {
+ const filter = {
+ linearProjectId: null,
+ linearProjectName: null,
+ stateTypes: ['backlog', 'unstarted'],
+ teamName: 'Engineering',
+ };
+
+ it('names archived issues only when they are included', () => {
+ expect(linearImportScopeSummary(filter, { includeArchived: false }, t)).toBe(
+ 'Engineering · linear.sync.filter.allProjects · linear.sync.filter.statesSummary:2',
+ );
+ expect(linearImportScopeSummary(filter, { includeArchived: true }, t)).toBe(
+ 'Engineering · linear.sync.filter.allProjects · linear.sync.filter.statesSummary:2 · linear.sync.options.includeArchived',
+ );
+ });
+});
+
describe('linearScopeProjectLabel', () => {
it('names the project, says No project, or falls back to All projects only when asked', () => {
const scope = (linearProjectId: string | null, linearProjectName: string | null = null) => ({
diff --git a/src/features/Projects/LinearSync/utils.ts b/src/features/Projects/LinearSync/utils.ts
index 45b07cb5359..f01c83c8375 100644
--- a/src/features/Projects/LinearSync/utils.ts
+++ b/src/features/Projects/LinearSync/utils.ts
@@ -30,6 +30,29 @@ export const linearScopeProjectLabel = (
return options.withAll ? t('linear.sync.filter.allProjects') : undefined;
};
+/**
+ * The scope above the issue list. Including archived issues is chosen a step
+ * back, but it decides what the list holds, so it is named here too.
+ */
+export const linearImportScopeSummary = (
+ filter: {
+ linearProjectId: string | null;
+ linearProjectName: string | null;
+ stateTypes: unknown[];
+ teamName: string | null;
+ },
+ options: { includeArchived: boolean },
+ t: TFunction<'integration'>,
+): string =>
+ [
+ filter.teamName,
+ linearScopeProjectLabel(filter, t, { withAll: true }),
+ t('linear.sync.filter.statesSummary', { count: filter.stateTypes.length }),
+ options.includeArchived && t('linear.sync.options.includeArchived'),
+ ]
+ .filter(Boolean)
+ .join(' · ');
+
/**
* Whether the scope step may move on. "All projects" waits for the team's
* project list, since without it the choice may be a mistake; "No project"
diff --git a/src/services/linear.ts b/src/services/linear.ts
index 62781c173d2..a407e9209ca 100644
--- a/src/services/linear.ts
+++ b/src/services/linear.ts
@@ -4,6 +4,8 @@ import { lambdaClient } from '@/libs/trpc/client';
export interface LinearIssueFilterParams {
connectionId: string;
+ /** Also match archived issues, which Linear leaves out unless asked. */
+ includeArchived?: boolean;
linearProjectId?: string | null;
stateTypes: LinearIssueStateType[];
teamId: string;
@@ -48,7 +50,7 @@ class LinearService {
lambdaClient.linear.listSyncRules.query({ projectId });
createSyncRule = async (
- params: LinearIssueFilterParams & {
+ params: Omit<LinearIssueFilterParams, 'includeArchived'> & {
linearProjectName?: string | null;
projectId: string;
teamName: string;
@@ -58,8 +60,10 @@ class LinearService {
deleteSyncRule = async (ruleId: string) => lambdaClient.linear.deleteSyncRule.mutate({ ruleId });
/** Starts a background run of a saved rule; returns the job id. */
- startRuleSync = async (ruleId: string, options: { syncComments?: boolean } = {}) =>
- lambdaClient.linear.startRuleSync.mutate({ ruleId, ...options });
+ startRuleSync = async (
+ ruleId: string,
+ options: { includeArchived?: boolean; syncComments?: boolean } = {},
+ ) => lambdaClient.linear.startRuleSync.mutate({ ruleId, ...options });
}
export const linearService = new LinearService();