🤯 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): show the total issue count in the import picker (#22258)
Rdmclin233d75e88e49d
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.tsindex 79b1d3cf9c0..bc1ef874f9e 100644--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts@@ -30,6 +30,7 @@ vi.mock('@/envs/linear', () => ({}));const mocks = vi.hoisted(() => ({+ countIssues: vi.fn(),getToken: vi.fn(),listTeams: vi.fn(),revoke: vi.fn(),@@ -54,6 +55,7 @@ vi.mock('@/server/services/linear/token', () => ({LinearReconnectRequiredError: class LinearReconnectRequiredError extends Error {},}));vi.mock('@/server/services/linear/issues', () => ({+ countLinearIssues: mocks.countIssues,listLinearProjects: vi.fn(),listLinearTeams: mocks.listTeams,}));@@ -197,6 +199,26 @@ describe('linearRouter', () => {expect(mocks.getToken).not.toHaveBeenCalled();});+ it("counts the issues of the picker filter through the caller's connection", async () => {+ const connection = await connect({ userId });+ const other = await connect({ userId: otherUserId });+ mocks.getToken.mockResolvedValue('token');+ mocks.countIssues.mockResolvedValue({ capped: false, count: 234 });+ const filter = { stateTypes: ['unstarted' as const], teamId: 'team-pkg' };++ await expect(+ caller({ userId }).countIssues({ connectionId: connection.id, ...filter }),+ ).resolves.toEqual({ capped: false, count: 234 });+ expect(mocks.countIssues).toHaveBeenCalledWith(+ 'token',+ expect.objectContaining({ connectionId: connection.id, ...filter }),+ );++ await expect(+ caller({ userId }).countIssues({ connectionId: other.id, ...filter }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+it('asks to reconnect when Linear rejects the token', async () => {const connection = await connect({ userId });const { LinearApiError } = await import('@/server/services/linear/client');diff --git a/apps/server/src/routers/lambda/linear.ts b/apps/server/src/routers/lambda/linear.tsindex 65136c6f014..3dfbf9b3142 100644--- a/apps/server/src/routers/lambda/linear.ts+++ b/apps/server/src/routers/lambda/linear.ts@@ -20,7 +20,11 @@ import {LinearApiError,revokeLinearToken,} from '@/server/services/linear/client';-import { listLinearProjects, listLinearTeams } from '@/server/services/linear/issues';+import {+ countLinearIssues,+ listLinearProjects,+ listLinearTeams,+} from '@/server/services/linear/issues';import { LinearIssueSyncService } from '@/server/services/linear/issueSync';import { startLinearRuleSyncJob, startLinearSyncJob } from '@/server/services/linear/startSyncJob';import { toLinearSyncJobView } from '@/server/services/linear/syncJob';@@ -144,6 +148,14 @@ export const linearRouter = router({);}),+ /** How many issues match the picker filter, counted up to a limit. */+ countIssues: linearProcedure.input(issueFilterInput).query(async ({ ctx, input }) => {+ await requireConnection(ctx, input.connectionId);+ return callLinear(async () =>+ countLinearIssues(await getLinearAccessToken(ctx.serverDB, input.connectionId), input),+ );+ }),+/*** Import (or re-sync) the picked issues into a LobeHub project. Runs in the* background; poll `listSyncJobs` for the outcome.diff --git a/apps/server/src/services/linear/__tests__/issues.test.ts b/apps/server/src/services/linear/__tests__/issues.test.tsindex 94e488684d5..1bc048c1420 100644--- a/apps/server/src/services/linear/__tests__/issues.test.ts+++ b/apps/server/src/services/linear/__tests__/issues.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { getLinearProjectTeamIds, listLinearIssues } from '../issues';+import { countLinearIssues, getLinearProjectTeamIds, listLinearIssues } from '../issues';const fetchMock = vi.fn();@@ -97,3 +97,60 @@ describe('getLinearProjectTeamIds', () => {expect(fetchMock).toHaveBeenCalledTimes(1);});});++describe('countLinearIssues', () => {+ const idPage = (count: number, endCursor: string | null) =>+ reply({+ issues: {+ nodes: Array.from({ length: count }, (_, index) => ({ id: `issue-${endCursor}-${index}` })),+ pageInfo: { endCursor, hasNextPage: endCursor !== null },+ },+ });++ it('adds up every page of ids with the picker filter', async () => {+ fetchMock.mockResolvedValueOnce(idPage(50, 'cursor-1')).mockResolvedValueOnce(idPage(12, null));++ const total = await countLinearIssues('token', {+ stateTypes: ['unstarted', 'started'],+ teamId: 'team-pkg',+ });++ expect(total).toEqual({ capped: false, count: 62 });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ const first = requestBody(fetchMock.mock.calls[0]);+ expect(first.query).toContain('nodes { id }');+ expect(first.variables).toEqual({+ filter: {+ state: { type: { in: ['unstarted', 'started'] } },+ team: { id: { eq: 'team-pkg' } },+ },+ first: 50,+ });+ expect(requestBody(fetchMock.mock.calls[1]).variables.after).toBe('cursor-1');+ });++ it('stops at the limit and reports the count as a lower bound', async () => {+ fetchMock+ .mockResolvedValueOnce(idPage(50, 'cursor-1'))+ .mockResolvedValueOnce(idPage(30, 'cursor-2'));++ const total = await countLinearIssues(+ 'token',+ { stateTypes: ['started'], teamId: 'team-pkg' },+ 80,+ );++ expect(total).toEqual({ capped: true, count: 80 });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ // The last page asks only for what is left under the limit.+ expect(requestBody(fetchMock.mock.calls[1]).variables.first).toBe(30);+ });++ it('is exact when the last page ends right at the limit', async () => {+ fetchMock.mockResolvedValueOnce(idPage(50, null));++ expect(+ await countLinearIssues('token', { stateTypes: ['started'], teamId: 'team-pkg' }, 50),+ ).toEqual({ capped: false, count: 50 });+ });+});diff --git a/apps/server/src/services/linear/issues.ts b/apps/server/src/services/linear/issues.tsindex f344335b324..b6359420562 100644--- a/apps/server/src/services/linear/issues.ts+++ b/apps/server/src/services/linear/issues.ts@@ -1,4 +1,5 @@import type {+ LinearIssueCount,LinearIssueStateType,LinearProjectSummary,LinearTeamSummary,@@ -164,6 +165,44 @@ export const listLinearIssues = async (};};+/**+ * Linear's issue connection has no total count, so the picker counts by paging+ * through ids. Counting stops here to bound the requests one filter costs.+ */+export const LINEAR_ISSUE_COUNT_LIMIT = 1000;++/** How many issues match the filter, up to `limit`. */+export const countLinearIssues = async (+ accessToken: string,+ filter: LinearIssueFilter,+ limit = LINEAR_ISSUE_COUNT_LIMIT,+): Promise<LinearIssueCount> => {+ let count = 0;+ let after: string | undefined;+ let hasMore = false;+ 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) {+ nodes { id }+ pageInfo { hasNextPage endCursor }+ }+ }`,+ {+ after,+ filter: toIssueFilter(filter),+ first: Math.min(LINEAR_PAGE_SIZE, limit - count),+ },+ );+ count += data.issues.nodes.length;+ hasMore = data.issues.pageInfo.hasNextPage;+ after = hasMore ? (data.issues.pageInfo.endCursor ?? undefined) : undefined;+ } while (after && count < limit);++ return { capped: hasMore, count };+};+/** Issues by id, in pages of the API's maximum size. Unknown or inaccessible ids are omitted. */export const getLinearIssuesByIds = async (accessToken: string,diff --git a/locales/en-US/integration.json b/locales/en-US/integration.jsonindex 4ab83fa63b8..58c3d53adb5 100644--- a/locales/en-US/integration.json+++ b/locales/en-US/integration.json@@ -108,9 +108,11 @@"linear.sync.job.titleRule": "Rule: {{rule}}","linear.sync.job.titleRuleDeleted": "Rule (deleted)","linear.sync.list.count": "{{count}} issues",+ "linear.sync.list.countAtLeast": "{{count}}+ issues","linear.sync.list.empty": "No issues match these filters.","linear.sync.list.linked": "Synced · {{task}}","linear.sync.list.loadMore": "Load more",+ "linear.sync.list.loaded": "{{count}} loaded","linear.sync.list.openInLinear": "Open in Linear","linear.sync.list.pickTeam": "Choose a team to see its issues.","linear.sync.list.selectAll": "Select all {{count}} loaded",diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.jsonindex 3e1c908d6b7..d952208f91e 100644--- a/locales/zh-CN/integration.json+++ b/locales/zh-CN/integration.json@@ -108,9 +108,11 @@"linear.sync.job.titleRule": "按规则同步:{{rule}}","linear.sync.job.titleRuleDeleted": "按规则同步(规则已删除)","linear.sync.list.count": "{{count}} 个 Issue",+ "linear.sync.list.countAtLeast": "{{count}}+ 个 Issue","linear.sync.list.empty": "没有符合筛选条件的 Issue。","linear.sync.list.linked": "已同步 · {{task}}","linear.sync.list.loadMore": "加载更多",+ "linear.sync.list.loaded": "已加载 {{count}} 个","linear.sync.list.openInLinear": "在 Linear 中打开","linear.sync.list.pickTeam": "选择团队后查看其 Issue。","linear.sync.list.selectAll": "全选已加载的 {{count}} 个",diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.tsindex 5ad701e7cf1..1030f319be2 100644--- a/packages/locales/src/default/integration.ts+++ b/packages/locales/src/default/integration.ts@@ -134,9 +134,11 @@ export default {'linear.sync.job.titleRule': 'Rule: {{rule}}','linear.sync.job.titleRuleDeleted': 'Rule (deleted)','linear.sync.list.count': '{{count}} issues',+ 'linear.sync.list.countAtLeast': '{{count}}+ issues','linear.sync.list.empty': 'No issues match these filters.','linear.sync.list.linked': 'Synced · {{task}}','linear.sync.list.loadMore': 'Load more',+ 'linear.sync.list.loaded': '{{count}} loaded','linear.sync.list.openInLinear': 'Open in Linear','linear.sync.list.pickTeam': 'Choose a team to see its issues.','linear.sync.list.selectAll': 'Select all {{count}} loaded',diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.tsindex 8ecc36c695c..f093df8a22c 100644--- a/packages/types/src/linear.ts+++ b/packages/types/src/linear.ts@@ -119,6 +119,13 @@ export interface LinearIssuePage {issues: LinearIssueSummary[];}+/** How many issues match a picker filter; counting stops at a limit. */+export interface LinearIssueCount {+ /** True when more issues match than were counted; `count` is then a lower bound. */+ capped: boolean;+ count: number;+}+/** Why an issue was left alone. */export type LinearSyncSkipReason =/** Linear closed it, but the task is running; it is not interrupted. */diff --git a/src/features/Integrations/Linear/swrKeys.ts b/src/features/Integrations/Linear/swrKeys.tsindex 42ae7756661..a0dae6a3b1f 100644--- a/src/features/Integrations/Linear/swrKeys.ts+++ b/src/features/Integrations/Linear/swrKeys.ts@@ -1,5 +1,20 @@import type { LinearIssueStateType } from '@lobechat/types';+interface IssueFilterKeyParams {+ connectionId: string;+ linearProjectId?: string | null;+ stateTypes: LinearIssueStateType[];+ teamId: string;+}++const issueFilterKey = (params: IssueFilterKeyParams) =>+ [+ params.connectionId,+ params.teamId,+ params.linearProjectId ?? null,+ [...params.stateTypes].sort().join(','),+ ] as const;+/*** SWR keys of the Linear integration. Kept beside the feature because the* central registry (`@/libs/swr/keys`) is over the file-size limit; they@@ -9,19 +24,9 @@ export const linearKeys = {config: () => ['linear:config'] as const,connections: (workspaceId: string | null | undefined) =>['linear:connections', workspaceId ?? null] as const,- issues: (params: {- connectionId: string;- linearProjectId?: string | null;- stateTypes: LinearIssueStateType[];- teamId: string;- }) =>- [- 'linear:issues',- params.connectionId,- params.teamId,- params.linearProjectId ?? null,- [...params.stateTypes].sort().join(','),- ] as const,+ issueCount: (params: IssueFilterKeyParams) =>+ ['linear:issueCount', ...issueFilterKey(params)] as const,+ issues: (params: IssueFilterKeyParams) => ['linear:issues', ...issueFilterKey(params)] as const,projects: (connectionId: string, teamId: string) =>['linear:projects', connectionId, teamId] as const,syncRules: (projectId: string) => ['linear:syncRules', projectId] as const,diff --git a/src/features/Projects/LinearSync/IssueList.test.tsx b/src/features/Projects/LinearSync/IssueList.test.tsxnew file mode 100644index 00000000000..70c6e55116f--- /dev/null+++ b/src/features/Projects/LinearSync/IssueList.test.tsx@@ -0,0 +1,89 @@+/**+ * @vitest-environment happy-dom+ */+import type { LinearIssuePage, LinearIssueSummary } from '@lobechat/types';+import { render, screen } from '@testing-library/react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import IssueList from './IssueList';++const mocks = vi.hoisted(() => ({+ countIssues: vi.fn(),+ listIssues: vi.fn(),+}));++vi.mock('@/services/linear', () => ({+ linearService: { countIssues: mocks.countIssues, listIssues: mocks.listIssues },+}));++vi.mock('react-i18next', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useTranslation: () => ({+ t: (key: string, options?: { count?: number }) =>+ options?.count === undefined ? key : `${key}:${options.count}`,+ }),+}));++const filter = { connectionId: 'connection-1', stateTypes: ['unstarted' as const], teamId: 'team' };++const issue = (index: number): LinearIssueSummary => ({+ id: `issue-${index}`,+ identifier: `LOBE-${index}`,+ priority: 0,+ stateName: 'Todo',+ stateType: 'unstarted',+ title: `Issue ${index}`,+ updatedAt: '2026-11-04T00:00:00.000Z',+ url: `https://linear.app/lobehub/issue/LOBE-${index}`,+});++const page = (count: number, hasMore: boolean): LinearIssuePage => ({+ cursor: hasMore ? 'cursor-1' : undefined,+ hasMore,+ issues: Array.from({ length: count }, (_, index) => issue(index)),+});++const renderList = () =>+ render(+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>+ <IssueList filter={filter} selected={new Set()} onSelectionChange={vi.fn()} />+ </SWRConfig>,+ );++beforeEach(() => {+ mocks.countIssues.mockReset();+ mocks.listIssues.mockReset();+});++describe('IssueList header', () => {+ it('shows the total of the filter, not the 50 loaded, while more pages remain', async () => {+ mocks.listIssues.mockResolvedValue(page(50, true));+ mocks.countIssues.mockResolvedValue({ capped: false, count: 234 });++ renderList();++ expect(await screen.findByText('linear.sync.list.count:234')).toBeTruthy();+ expect(screen.getByText('linear.sync.list.loaded:50')).toBeTruthy();+ expect(mocks.countIssues).toHaveBeenCalledWith(filter);+ });++ it('reads as "at least" until the count arrives', async () => {+ mocks.listIssues.mockResolvedValue(page(50, true));+ mocks.countIssues.mockReturnValue(new Promise(() => {}));++ renderList();++ expect(await screen.findByText('linear.sync.list.countAtLeast:50')).toBeTruthy();+ });++ it('does not count again when the first page holds every issue', async () => {+ mocks.listIssues.mockResolvedValue(page(12, false));++ renderList();++ expect(await screen.findByText('linear.sync.list.count:12')).toBeTruthy();+ expect(screen.queryByText(/linear\.sync\.list\.loaded/)).toBeNull();+ expect(mocks.countIssues).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Projects/LinearSync/IssueList.tsx b/src/features/Projects/LinearSync/IssueList.tsxindex 29a7a1c152b..e4503804414 100644--- a/src/features/Projects/LinearSync/IssueList.tsx+++ b/src/features/Projects/LinearSync/IssueList.tsx@@ -7,6 +7,7 @@ import * as stylex from '@stylexjs/stylex';import { CheckIcon, ExternalLinkIcon } from 'lucide-react';import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';+import useSWR from 'swr';import useSWRInfinite from 'swr/infinite';import LinearIcon from '@/features/Integrations/Linear/LinearIcon';@@ -14,7 +15,7 @@ import { linearKeys } from '@/features/Integrations/Linear/swrKeys';import { type LinearIssueFilterParams, linearService } from '@/services/linear';import StateIcon from './StateIcon';-import { linearSyncErrorMessage } from './utils';+import { linearIssueListCounts, linearSyncErrorMessage } from './utils';const styles = stylex.create({body: {@@ -40,6 +41,10 @@ const styles = stylex.create({height: 40,paddingInline: 12,},+ // Total and loaded counts sit at the far end of the header, apart from the selection.+ headNote: {+ marginInlineStart: 'auto',+ },identifier: {color: cssVar.colorTextTertiary,flexShrink: 0,@@ -93,6 +98,15 @@ const IssueList = memo<IssueListProps>(({ disabled, filter, onSelectionChange, sconst allSelected = ids.length > 0 && selectedCount === ids.length;const hasMore = data?.at(-1)?.hasMore;+ // Counted only when the first page is not everything; the list does not wait for it.+ const { data: total } = useSWR(+ filter && data?.[0]?.hasMore ? linearKeys.issueCount(filter) : null,+ () => linearService.countIssues(filter!),+ { revalidateOnFocus: false },+ );+ const counts = linearIssueListCounts({ hasMore: !!hasMore, loaded: issues.length, total }, t);+ const headNote = [selectedCount > 0 && counts.total, counts.loaded].filter(Boolean).join(' · ');+const placeholder = (content: ReactNode) => (<Center gap={8} height={'100%'} paddingInline={24}>{content}@@ -204,8 +218,13 @@ const IssueList = memo<IssueListProps>(({ disabled, filter, onSelectionChange, s<Text fontSize={12} type={'secondary'}>{selectedCount > 0? t('linear.sync.list.selected', { count: selectedCount })- : t('linear.sync.list.count', { count: issues.length })}+ : counts.total}</Text>+ {headNote ? (+ <Text fontSize={12} type={'secondary'} {...stylex.props(styles.headNote)}>+ {headNote}+ </Text>+ ) : null}</Flexbox>) : null}<div {...stylex.props(styles.body, !filter && styles.bodyWithoutHead)}>{body}</div>diff --git a/src/features/Projects/LinearSync/utils.test.ts b/src/features/Projects/LinearSync/utils.test.tsindex 442ea9562e3..ae574763a1a 100644--- a/src/features/Projects/LinearSync/utils.test.ts+++ b/src/features/Projects/LinearSync/utils.test.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';import {formatLinearSyncResult,isActiveLinearSyncJob,+ linearIssueListCounts,linearSyncJobErrorMessage,linearSyncJobProgress,} from './utils';@@ -93,3 +94,41 @@ describe('linearSyncJobProgress', () => {);});});++describe('linearIssueListCounts', () => {+ it('reads the loaded count as the total once every page is in', () => {+ expect(linearIssueListCounts({ hasMore: false, loaded: 12 }, t)).toEqual({+ total: 'linear.sync.list.count:12',+ });+ });++ it('shows the counted total and how many are loaded while pages remain', () => {+ expect(+ linearIssueListCounts({ hasMore: true, loaded: 50, total: { capped: false, count: 234 } }, t),+ ).toEqual({ loaded: 'linear.sync.list.loaded:50', total: 'linear.sync.list.count:234' });+ });++ it('reads as "at least" while the total is being counted, so the first page does not look like all', () => {+ expect(linearIssueListCounts({ hasMore: true, loaded: 50 }, t)).toEqual({+ loaded: 'linear.sync.list.loaded:50',+ total: 'linear.sync.list.countAtLeast:50',+ });+ });++ it('reads as "at least" when the count stopped at its limit or fell behind the loaded pages', () => {+ expect(+ linearIssueListCounts({ hasMore: true, loaded: 50, total: { capped: true, count: 1000 } }, t)+ .total,+ ).toBe('linear.sync.list.countAtLeast:1000');+ expect(+ linearIssueListCounts(+ { hasMore: true, loaded: 1050, total: { capped: true, count: 1000 } },+ t,+ ).total,+ ).toBe('linear.sync.list.countAtLeast:1050');+ expect(+ linearIssueListCounts({ hasMore: true, loaded: 100, total: { capped: false, count: 100 } }, t)+ .total,+ ).toBe('linear.sync.list.countAtLeast:100');+ });+});diff --git a/src/features/Projects/LinearSync/utils.ts b/src/features/Projects/LinearSync/utils.tsindex 0cbc0169bb6..9ef8bfaca60 100644--- a/src/features/Projects/LinearSync/utils.ts+++ b/src/features/Projects/LinearSync/utils.ts@@ -1,4 +1,9 @@-import type { LinearSyncJobErrorCode, LinearSyncJobView, LinearSyncResult } from '@lobechat/types';+import type {+ LinearIssueCount,+ LinearSyncJobErrorCode,+ LinearSyncJobView,+ LinearSyncResult,+} from '@lobechat/types';import { TRPCClientError } from '@trpc/client';import type { TFunction } from 'i18next';@@ -35,6 +40,28 @@ export const formatLinearSyncResult = (return parts.join(' · ');};+/**+ * Header counts of the issue picker. The list loads one page at a time, so the+ * loaded count is the total only once every page is in; until then the total+ * comes from the separate count, or reads as "at least" what is loaded.+ */+export const linearIssueListCounts = (+ { hasMore, loaded, total }: { hasMore: boolean; loaded: number; total?: LinearIssueCount },+ t: TFunction<'integration'>,+): { loaded?: string; total: string } => {+ if (!hasMore) return { total: t('linear.sync.list.count', { count: loaded }) };++ // The count can lag behind pages loaded later, or stop at its limit below them.+ const count = Math.max(total?.count ?? 0, loaded);+ const exact = !!total && !total.capped && total.count > loaded;+ return {+ loaded: t('linear.sync.list.loaded', { count: loaded }),+ total: exact+ ? t('linear.sync.list.count', { count })+ : t('linear.sync.list.countAtLeast', { count }),+ };+};+export const isActiveLinearSyncJob = (job: Pick<LinearSyncJobView, 'status'>) =>job.status === 'pending' || job.status === 'processing';diff --git a/src/services/linear.ts b/src/services/linear.tsindex 13f180aab94..62781c173d2 100644--- a/src/services/linear.ts+++ b/src/services/linear.ts@@ -27,6 +27,10 @@ class LinearService {listIssues = async (params: LinearIssueFilterParams & { cursor?: string }) =>lambdaClient.linear.listIssues.query(params);+ /** How many issues match the filter; the count stops at a server-side limit. */+ countIssues = async (params: LinearIssueFilterParams) =>+ lambdaClient.linear.countIssues.query(params);+/** Starts a background import; returns the job id. */startImport = async (params: {connectionId: string;