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): filter by project alone when a project is chosen (#22096)

Rdmclin28f809d455b94
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 331d80c9bc4..51175677b2b 100644
--- a/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
+++ b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
@@ -15,11 +15,13 @@ import { LinearIssueSyncService, MAX_TASKS_CREATED_PER_SYNC } from '../issueSync
const linear = vi.hoisted(() => ({
getLinearIssuesByIds: vi.fn(),
+ getLinearProjectTeamIds: vi.fn(),
listLinearIssues: vi.fn(),
}));
vi.mock('../issues', async (importOriginal) => ({
...(await importOriginal<typeof IssuesModule>()),
getLinearIssuesByIds: linear.getLinearIssuesByIds,
+ getLinearProjectTeamIds: linear.getLinearProjectTeamIds,
listLinearIssues: linear.listLinearIssues,
}));
@@ -142,6 +144,45 @@ describe('LinearIssueSyncService (real PostgreSQL)', () => {
expect((await linkedTask('1'))?.status).toBe('completed');
});
+ it('closes the task of a project issue that lives in another team than the filter', async () => {
+ // A project linked to teams PKG and LOBE whose issues all live in LOBE,
+ // synced through a rule that names PKG.
+ const projectFilter = {
+ linearProjectId: 'project-1',
+ stateTypes: [...filter.stateTypes],
+ teamId: 'team-pkg',
+ };
+ const project = { id: 'project-1', name: 'LobeHub Model' };
+ const lobeIssue = issue({ id: '1', project, team: { id: 'team-lobe', key: 'LOBE' } });
+ linear.getLinearProjectTeamIds.mockResolvedValue(['team-pkg', 'team-lobe']);
+ serve([lobeIssue]);
+ const service = new LinearIssueSyncService(db, userId);
+ expect((await service.syncByFilter(TOKEN, projectFilter)).created).toBe(1);
+
+ // Closed in Linear, so the open-states filter no longer returns it.
+ linear.listLinearIssues.mockResolvedValue({ hasMore: false, issues: [] });
+ linear.getLinearIssuesByIds.mockResolvedValue([
+ { ...lobeIssue, state: { name: 'Done', type: 'completed' } },
+ ]);
+ const result = await service.syncByFilter(TOKEN, projectFilter);
+
+ expect(result.closed).toBe(1);
+ expect((await linkedTask('1'))?.status).toBe('completed');
+ });
+
+ it('fails a project rule whose teams cannot be read instead of narrowing the closing pass', async () => {
+ linear.getLinearProjectTeamIds.mockRejectedValue(new Error('Linear API error: timeout'));
+ serve([issue({ id: '1', team: { id: 'team-lobe', key: 'LOBE' } })]);
+
+ await expect(
+ new LinearIssueSyncService(db, userId).syncByFilter(TOKEN, {
+ linearProjectId: 'project-1',
+ stateTypes: [...filter.stateTypes],
+ teamId: 'team-pkg',
+ }),
+ ).rejects.toThrow('timeout');
+ });
+
it('does not interrupt a running task when its issue is closed', async () => {
serve([issue({ id: '1' })]);
const service = new LinearIssueSyncService(db, userId);
diff --git a/apps/server/src/services/linear/__tests__/issues.test.ts b/apps/server/src/services/linear/__tests__/issues.test.ts
new file mode 100644
index 00000000000..94e488684d5
--- /dev/null
+++ b/apps/server/src/services/linear/__tests__/issues.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getLinearProjectTeamIds, listLinearIssues } from '../issues';
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ fetchMock.mockReset();
+});
+
+const reply = (data: unknown) => new Response(JSON.stringify({ data }), { status: 200 });
+
+const requestBody = (call: unknown[]) =>
+ JSON.parse((call[1] as RequestInit).body as string) as {
+ query: string;
+ variables: Record<string, any>;
+ };
+
+const emptyIssues = { issues: { nodes: [], pageInfo: { endCursor: null, hasNextPage: false } } };
+
+describe('listLinearIssues filter', () => {
+ it('filters by team when no project is chosen', async () => {
+ fetchMock.mockResolvedValue(reply(emptyIssues));
+
+ await listLinearIssues('token', { stateTypes: ['unstarted'], teamId: 'team-pkg' });
+
+ expect(requestBody(fetchMock.mock.calls[0]).variables.filter).toEqual({
+ state: { type: { in: ['unstarted'] } },
+ team: { id: { eq: 'team-pkg' } },
+ });
+ });
+
+ it('filters by project only when a project is chosen, since its issues may live in another team', async () => {
+ fetchMock.mockResolvedValue(reply(emptyIssues));
+
+ await listLinearIssues('token', {
+ linearProjectId: 'project-1',
+ stateTypes: ['unstarted', 'started'],
+ teamId: 'team-pkg',
+ });
+
+ expect(requestBody(fetchMock.mock.calls[0]).variables.filter).toEqual({
+ project: { id: { eq: 'project-1' } },
+ state: { type: { in: ['unstarted', 'started'] } },
+ });
+ });
+});
+
+describe('getLinearProjectTeamIds', () => {
+ it('reads every page of the teams a project belongs to', async () => {
+ fetchMock
+ .mockResolvedValueOnce(
+ reply({
+ project: {
+ teams: {
+ nodes: [{ id: 'team-pkg' }, { id: 'team-lobe' }],
+ pageInfo: { endCursor: 'cursor-1', hasNextPage: true },
+ },
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ reply({
+ project: {
+ teams: {
+ nodes: [{ id: 'team-ops' }],
+ pageInfo: { endCursor: null, hasNextPage: false },
+ },
+ },
+ }),
+ );
+
+ const ids = await getLinearProjectTeamIds('token', 'project-1');
+
+ expect(ids).toEqual(['team-pkg', 'team-lobe', 'team-ops']);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(requestBody(fetchMock.mock.calls[0]).variables).toMatchObject({
+ projectId: 'project-1',
+ });
+ expect(requestBody(fetchMock.mock.calls[0]).variables.after).toBeUndefined();
+ expect(requestBody(fetchMock.mock.calls[1]).variables).toMatchObject({
+ after: 'cursor-1',
+ projectId: 'project-1',
+ });
+ });
+
+ it('returns no team for a project that does not exist', async () => {
+ fetchMock.mockResolvedValue(reply({ project: null }));
+
+ expect(await getLinearProjectTeamIds('token', 'gone')).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/server/src/services/linear/issueSync.ts b/apps/server/src/services/linear/issueSync.ts
index eec7ec9f2ee..a8f6c522bc7 100644
--- a/apps/server/src/services/linear/issueSync.ts
+++ b/apps/server/src/services/linear/issueSync.ts
@@ -9,6 +9,7 @@ import type {
TaskItem,
} from '@lobechat/types';
import debug from 'debug';
+import pMap from 'p-map';
import { isTaskIdentifierUniqueViolation, TaskModel } from '@/database/models/task';
import {
@@ -20,6 +21,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '../task';
import {
getLinearIssuesByIds,
+ getLinearProjectTeamIds,
LINEAR_PAGE_SIZE,
type LinearIssue,
type LinearIssueFilter,
@@ -226,8 +228,8 @@ 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.
+ * in the filter's teams (for a project, every team it belongs to) 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
@@ -288,10 +290,24 @@ export class LinearIssueSyncService {
if (options.startAfter) return result;
// Linked issues the filter missed: closed since, or moved out of the project.
+ // A link is stored under its issue's own team, which for a project filter
+ // can be any team the project belongs to, not just the filter's team.
const seen = new Set(issues.map((issue) => issue.id));
- const unseen = (await this.linkModel.findByContainer('linear', filter.teamId)).filter(
- (link) => !seen.has(link.externalId),
- );
+ const teamIds = new Set([filter.teamId, ...issues.map((issue) => issue.team.id)]);
+ if (filter.linearProjectId) {
+ // Let a failed lookup fail the run: skipping the project's other teams
+ // would leave their closed issues' tasks open without any sign of it.
+ for (const id of await getLinearProjectTeamIds(accessToken, filter.linearProjectId)) {
+ teamIds.add(id);
+ }
+ }
+ const unseen = (
+ await pMap([...teamIds], (teamId) => this.linkModel.findByContainer('linear', teamId), {
+ concurrency: 5,
+ })
+ )
+ .flat()
+ .filter((link) => !seen.has(link.externalId));
if (unseen.length > 0) {
const open = await this.taskModel.findByIds(unseen.map((link) => link.taskId));
const openTaskIds = new Set(
diff --git a/apps/server/src/services/linear/issues.ts b/apps/server/src/services/linear/issues.ts
index b21f7202eac..e0d7e6f1d63 100644
--- a/apps/server/src/services/linear/issues.ts
+++ b/apps/server/src/services/linear/issues.ts
@@ -95,12 +95,47 @@ export interface LinearIssueFilter {
teamId: string;
}
+/**
+ * A project filters by project alone: a Linear project can belong to several
+ * teams, and its issues may all live in a team other than the chosen one.
+ */
const toIssueFilter = ({ linearProjectId, stateTypes, teamId }: LinearIssueFilter) => ({
state: { type: { in: stateTypes } },
- team: { id: { eq: teamId } },
- ...(linearProjectId ? { project: { id: { eq: linearProjectId } } } : {}),
+ ...(linearProjectId
+ ? { project: { id: { eq: linearProjectId } } }
+ : { team: { id: { eq: teamId } } }),
});
+/** Ids of every team a project belongs to; none when the project does not exist. */
+export const getLinearProjectTeamIds = async (
+ accessToken: string,
+ projectId: string,
+): Promise<string[]> => {
+ const ids: string[] = [];
+ let after: string | undefined;
+ do {
+ const data = await linearGraphql<{
+ project: { teams: Connection<{ id: string }> } | null;
+ }>(
+ accessToken,
+ `query LobeProjectTeams($projectId: String!, $first: Int!, $after: String) {
+ project(id: $projectId) {
+ teams(first: $first, after: $after) {
+ nodes { id }
+ pageInfo { hasNextPage endCursor }
+ }
+ }
+ }`,
+ { after, first: LINEAR_PAGE_SIZE, projectId },
+ );
+ if (!data.project) return ids;
+ const page = data.project.teams;
+ ids.push(...page.nodes.map((team) => team.id));
+ after = page.pageInfo.hasNextPage ? (page.pageInfo.endCursor ?? undefined) : undefined;
+ } while (after);
+ return ids;
+};
+
/** One page of issues matching a filter, most recently updated first. */
export const listLinearIssues = async (
accessToken: string,