Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

improvement(api): list issues across all readable projects by filters (#767)

Kenec05355eee4a
diff --git a/apps/api/src/modules/issues/__tests__/integration/list-all.test.ts b/apps/api/src/modules/issues/__tests__/integration/list-all.test.ts
new file mode 100644
index 00000000..bee591ca
--- /dev/null
+++ b/apps/api/src/modules/issues/__tests__/integration/list-all.test.ts
@@ -0,0 +1,172 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { auth } from '@repo/auth';
+import { app, authedApi, type Api, createProject } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { addProjectMember } from '#tests/helpers/members';
+import { createRole } from '#tests/helpers/roles';
+
+// GET /issues: the filtered issue list over every project the caller may read work items in.
+
+async function setup() {
+ await signUpTestUser();
+ const user = await signUpTestUser();
+ const api = authedApi(user.cookie);
+ await createProject(api, { key: 'MKT', name: 'Marketing' });
+ await createProject(api, { key: 'OPS', name: 'Operations' });
+ return { user, api };
+}
+
+async function columns(api: Api, projectKey: string) {
+ return (await api.projects({ projectKey }).get()).data!.columns;
+}
+
+async function createIssue(
+ api: Api,
+ projectKey: string,
+ title: string,
+ body: Record<string, unknown> = {},
+) {
+ const columnId = (await columns(api, projectKey))[0]!.id;
+ const res = await api.projects({ projectKey }).issues.post({ columnId, title, ...body });
+ return res.data!;
+}
+
+type Query = NonNullable<NonNullable<Parameters<Api['issues']['get']>[0]>['query']>;
+
+const list = (api: Api, query: Query = {}) => api.issues.get({ query });
+
+const titles = (res: Awaited<ReturnType<typeof list>>) => res.data?.map((hit) => hit.title).sort();
+
+describe('cross-project issue list', () => {
+ beforeEach(resetDb);
+
+ it('lists the issues of every project, newest update first, each with its project', async () => {
+ const { api } = await setup();
+ const mkt = await createIssue(api, 'MKT', 'Launch plan');
+ const ops = await createIssue(api, 'OPS', 'Runbook');
+ const archived = await createIssue(api, 'OPS', 'Old runbook');
+ await api.issues({ issueId: archived.id }).archive.post();
+
+ const res = await list(api);
+ const [ownTeam] = (await api.teams.get()).data!;
+ expect(res.status).toBe(200);
+ expect(res.data!.map((hit) => hit.id)).toEqual([ops.id, mkt.id]);
+ expect(res.data![1]).toMatchObject({
+ identifier: `MKT-${mkt.sequenceNumber}`,
+ projectKey: 'MKT',
+ projectName: 'Marketing',
+ projectRef: expect.stringMatching(/\.MKT$/),
+ teamName: ownTeam!.name,
+ archived: false,
+ });
+ expect(titles(await list(api, { includeArchived: 'true' }))).toEqual([
+ 'Launch plan',
+ 'Old runbook',
+ 'Runbook',
+ ]);
+ });
+
+ it('filters by assignee, state type, cycle and parent', async () => {
+ const { user, api } = await setup();
+ await createIssue(api, 'MKT', 'Mine', { assigneeUserId: user.userId });
+ await createIssue(api, 'OPS', 'Mine too', { assigneeUserId: user.userId });
+ await createIssue(api, 'OPS', 'Unassigned');
+ const done = await createIssue(api, 'MKT', 'Done');
+ const doneColumn = (await columns(api, 'MKT')).find((c) => c.stateType === 'completed')!;
+ await api.issues({ issueId: done.id }).patch({ columnId: doneColumn.id });
+ const today = new Date().toISOString().slice(0, 10);
+ const cycle = await api
+ .projects({ projectKey: 'OPS' })
+ .cycles.post({ name: 'Cycle 1', startDate: today, endDate: today });
+ await createIssue(api, 'OPS', 'Planned', { cycleId: cycle.data!.id });
+ const parent = await createIssue(api, 'MKT', 'Parent');
+ await createIssue(api, 'MKT', 'Subtask', { parentId: parent.id });
+
+ expect(titles(await list(api, { assigneeUserId: user.userId }))).toEqual(['Mine', 'Mine too']);
+ expect(titles(await list(api, { stateTypes: 'completed' }))).toEqual(['Done']);
+ expect(titles(await list(api, { stateTypes: 'backlog,unstarted,started' }))).not.toContain(
+ 'Done',
+ );
+ expect(titles(await list(api, { cycleIds: `${cycle.data!.id}` }))).toEqual(['Planned']);
+ expect(titles(await list(api, { parentIds: `${parent.id},0` }))).toEqual(['Subtask']);
+ expect(titles(await list(api, { assigneeUserId: '', cycleIds: '' }))).toHaveLength(7);
+ });
+
+ it('rejects an unknown state type', async () => {
+ const { api } = await setup();
+ const res = await list(api, { stateTypes: 'started,done' });
+ expect(res.status).toBe(400);
+ });
+
+ it('caps the list at limit', async () => {
+ const { api } = await setup();
+ for (const title of ['One', 'Two', 'Three']) await createIssue(api, 'MKT', title);
+
+ expect((await list(api, { limit: 2 })).data).toHaveLength(2);
+ });
+
+ it("leaves out another person's projects and a project whose role may not read work items", async () => {
+ const { api } = await setup();
+ await createIssue(api, 'MKT', 'Shared plan');
+ const other = authedApi((await signUpTestUser()).cookie);
+ const reader = await createRole(api, 'MKT', {
+ name: 'Reader',
+ permissions: { work_items: { read: true } },
+ });
+ const blind = await createRole(api, 'MKT', { name: 'Blind', permissions: {} });
+
+ expect((await list(other)).data).toEqual([]);
+ expect(titles(await list(await addProjectMember(api, 'MKT', reader.data!.id)))).toEqual([
+ 'Shared plan',
+ ]);
+ expect((await list(await addProjectMember(api, 'MKT', blind.data!.id))).data).toEqual([]);
+ });
+
+ it('lists only the project an agent run is bound to', async () => {
+ const { user, api } = await setup();
+ await createIssue(api, 'MKT', 'Launch plan');
+ await createIssue(api, 'OPS', 'Runbook');
+ const mkt = (await api.projects({ projectKey: 'MKT' }).get()).data!.project.id;
+
+ const bound = authedApi(user.cookie, { 'x-agent-project': String(mkt) });
+ expect(titles(await list(bound))).toEqual(['Launch plan']);
+ });
+
+ it('serves the list_issues_all_projects MCP tool over the MCP-enabled projects', async () => {
+ const { user, api } = await setup();
+ await createIssue(api, 'MKT', 'Visible plan');
+ await createIssue(api, 'OPS', 'Hidden plan');
+ const ops = (await api.projects({ projectKey: 'OPS' }).get()).data!.project;
+ await api.teams({ teamId: ops.teamId }).mcp.patch({
+ projects: [{ projectId: ops.id, enabled: false }],
+ });
+ const key = await auth.api.createApiKey({ body: { userId: user.userId, name: 'list' } });
+
+ const response = await app.handle(
+ new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${key.key}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'list_issues_all_projects', arguments: {} },
+ }),
+ }),
+ );
+ const text = await response.text();
+ const { result } = JSON.parse(text.slice(text.indexOf('data: ') + 6)) as {
+ result: { structuredContent: { ok: boolean; data: { title: string }[] } };
+ };
+ expect(result.structuredContent).toMatchObject({
+ ok: true,
+ data: [expect.objectContaining({ title: 'Visible plan', projectKey: 'MKT' })],
+ });
+ expect(result.structuredContent.data).toHaveLength(1);
+ });
+});
diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.ts
index 2566453b..65d2ca5c 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -26,6 +26,9 @@ import {
createIssue,
searchIssues,
searchIssuesInProjects,
+ listIssuesInProjects,
+ ISSUE_STATE_TYPES,
+ type IssueStateType,
listIssues,
listArchivedIssues,
getIssue,
@@ -148,6 +151,7 @@ import {
searchIssuesQuery,
searchAllIssuesQuery,
listIssuesQuery,
+ listAllIssuesQuery,
issueSequenceParams,
updateIssueBody,
subtaskDispositionQuery,
@@ -609,6 +613,67 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
+ // The list_issues filters that mean the same in every project, over every project the
+ // caller may read work items in. Empty values mean "any", as on list_issues.
+ .get(
+ '/issues',
+ async ({ user, query, request }) => {
+ const ids = await readableProjectIds(requireUser(user).id, [['work_items', 'read']], {
+ mcpOnly: isMcpRequest(request.headers),
+ });
+ const bound = boundProjectId(request.headers);
+ const str = (v: string | undefined) => (v ? v : undefined);
+ const csvIds = (v: string | undefined) => {
+ const list = v
+ ?.split(',')
+ .map(Number)
+ .filter((n) => Number.isInteger(n) && n > 0);
+ return list?.length ? list : undefined;
+ };
+ const stateTypes = query.stateTypes
+ ?.split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ const unknown = stateTypes?.find(
+ (s) => !(ISSUE_STATE_TYPES as readonly string[]).includes(s),
+ );
+ if (unknown) throw new HttpError(400, `Unknown state type: ${unknown}`);
+ return listIssuesInProjects(
+ ids.filter((id) => bound == null || id === bound),
+ {
+ assigneeUserId: str(query.assigneeUserId),
+ delegateUserId: str(query.delegateUserId),
+ priority: str(query.priority),
+ dueFrom: str(query.dueFrom),
+ dueTo: str(query.dueTo),
+ createdFrom: instantParam('createdFrom', query.createdFrom),
+ createdTo: instantParam('createdTo', query.createdTo),
+ updatedFrom: instantParam('updatedFrom', query.updatedFrom),
+ updatedTo: instantParam('updatedTo', query.updatedTo),
+ cycleIds: csvIds(query.cycleIds),
+ parentIds: csvIds(query.parentIds),
+ stateTypes: stateTypes?.length ? (stateTypes as IssueStateType[]) : undefined,
+ limit: Math.min(Math.max(query.limit ?? 50, 1), 500),
+ },
+ { includeArchived: query.includeArchived === 'true' },
+ );
+ },
+ {
+ query: listAllIssuesQuery,
+ response: { 200: t.Array(CrossProjectIssueHitResponse), ...errors(400, 401) },
+ detail: {
+ summary: 'List issues in all projects',
+ description:
+ 'List the issues of every project you can read by field filters, most recently ' +
+ 'updated first. Each issue names its project (projectKey, projectRef, projectName, ' +
+ 'teamName); use list_issues for one project and its project-scoped filters. An agent ' +
+ 'run lists only the project it works in.',
+ ...requiresPermission(['work_items', 'read']),
+ ...mcpTool('list_issues_all_projects'),
+ },
+ },
+ )
+
// Reads the full issue including its custom field values. The handler fetches the
// issue for the response, so it asserts access on that row instead of using the
// workItem guard, which would resolve the project id a second time.
diff --git a/apps/api/src/modules/issues/model.ts b/apps/api/src/modules/issues/model.ts
index e9f26edd..442c669f 100644
--- a/apps/api/src/modules/issues/model.ts
+++ b/apps/api/src/modules/issues/model.ts
@@ -591,6 +591,36 @@ export const listIssuesQuery = t.Object({
limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
});
+export const listAllIssuesQuery = t.Composite([
+ t.Pick(listIssuesQuery, [
+ 'assigneeUserId',
+ 'delegateUserId',
+ 'priority',
+ 'dueFrom',
+ 'dueTo',
+ 'createdFrom',
+ 'createdTo',
+ 'updatedFrom',
+ 'updatedTo',
+ 'includeArchived',
+ 'limit',
+ ]),
+ t.Object({
+ cycleIds: t.Optional(
+ t.String({ description: 'CSV of cycle ids; the issue must be in one of them.' }),
+ ),
+ parentIds: t.Optional(
+ t.String({ description: 'CSV of parent issue ids, to list their subtasks.' }),
+ ),
+ stateTypes: t.Optional(
+ t.String({
+ description:
+ "CSV of column state types: backlog, unstarted, started, completed, canceled. 'backlog,unstarted,started' lists the open issues.",
+ }),
+ ),
+ }),
+]);
+
export const issueSequenceParams = t.Object({
projectKey: t.String(),
sequenceNumber: t.Numeric(),
diff --git a/apps/api/src/modules/issues/service.ts b/apps/api/src/modules/issues/service.ts
index e4c330c9..d15f25a1 100644
--- a/apps/api/src/modules/issues/service.ts
+++ b/apps/api/src/modules/issues/service.ts
@@ -422,6 +422,45 @@ function toHit(
};
}
+type FieldFilters = Pick<
+ IssueQuery,
+ 'assigneeUserId' | 'delegateUserId' | 'priority' | 'dueFrom' | 'dueTo'
+> & {
+ createdFrom?: Date;
+ createdTo?: Date;
+ updatedFrom?: Date;
+ updatedTo?: Date;
+};
+
+// The exact filters list_issues and the cross-project list share.
+function fieldConds(filters: FieldFilters): SQL[] {
+ const conds: SQL[] = [];
+ if (filters.assigneeUserId !== undefined)
+ conds.push(
+ filters.assigneeUserId === null
+ ? isNull(issue.assigneeUserId)
+ : eq(issue.assigneeUserId, filters.assigneeUserId),
+ );
+ if (filters.delegateUserId !== undefined)
+ conds.push(
+ filters.delegateUserId === null
+ ? isNull(issue.delegateUserId)
+ : eq(issue.delegateUserId, filters.delegateUserId),
+ );
+ if (filters.priority !== undefined)
+ conds.push(
+ filters.priority === null ? isNull(issue.priority) : eq(issue.priority, filters.priority),
+ );
+ // A null due date never falls in a range, so gte/lte alone exclude it.
+ if (filters.dueFrom !== undefined) conds.push(gte(issue.dueDate, filters.dueFrom));
+ if (filters.dueTo !== undefined) conds.push(lte(issue.dueDate, filters.dueTo));
+ if (filters.createdFrom) conds.push(gte(issue.createdAt, filters.createdFrom));
+ if (filters.createdTo) conds.push(lt(issue.createdAt, filters.createdTo));
+ if (filters.updatedFrom) conds.push(gte(issue.updatedAt, filters.updatedFrom));
+ if (filters.updatedTo) conds.push(lt(issue.updatedAt, filters.updatedTo));
+ return conds;
+}
+
// Server-side issue read backing two routes: text search (search_issues) and the
// filtered list (list_issues). Text search (filters.query) is textMatch, and also
// matches the issue number: a bare number, or "KEY-42" for this project. The other
@@ -468,22 +507,7 @@ export async function searchIssues(
conds.push(
filters.parentId === null ? isNull(issue.parentId) : eq(issue.parentId, filters.parentId),
);
- if (filters.assigneeUserId !== undefined)
- conds.push(
- filters.assigneeUserId === null
- ? isNull(issue.assigneeUserId)
- : eq(issue.assigneeUserId, filters.assigneeUserId),
- );
- if (filters.delegateUserId !== undefined)
- conds.push(
- filters.delegateUserId === null
- ? isNull(issue.delegateUserId)
- : eq(issue.delegateUserId, filters.delegateUserId),
- );
- if (filters.priority !== undefined)
- conds.push(
- filters.priority === null ? isNull(issue.priority) : eq(issue.priority, filters.priority),
- );
+ conds.push(...fieldConds(filters));
// labelIds is AND: the issue must carry every supplied label.
for (const labelId of filters.labelIds ?? []) {
conds.push(
@@ -495,13 +519,6 @@ export async function searchIssues(
),
);
}
- // A null due date never falls in a range, so gte/lte alone exclude it.
- if (filters.dueFrom !== undefined) conds.push(gte(issue.dueDate, filters.dueFrom));
- if (filters.dueTo !== undefined) conds.push(lte(issue.dueDate, filters.dueTo));
- if (filters.createdFrom) conds.push(gte(issue.createdAt, filters.createdFrom));
- if (filters.createdTo) conds.push(lt(issue.createdAt, filters.createdTo));
- if (filters.updatedFrom) conds.push(gte(issue.updatedAt, filters.updatedFrom));
- if (filters.updatedTo) conds.push(lt(issue.updatedAt, filters.updatedTo));
if (filters.blocked) {
const blocker = alias(issue, 'blocker');
@@ -545,6 +562,26 @@ export interface CrossProjectIssueHit extends IssueSearchHit {
teamName: string;
}
+const crossProjectHitColumns = {
+ ...hitColumns,
+ projectId: projectTable.id,
+ projectRef: projectRefSql,
+ projectKey: projectTable.key,
+ projectName: projectTable.name,
+ teamName: team.name,
+};
+
+function toCrossProjectHit({
+ projectId,
+ projectRef,
+ projectKey,
+ projectName,
+ teamName,
+ ...r
+}: HitRow & Omit<CrossProjectIssueHit, keyof IssueSearchHit>): CrossProjectIssueHit {
+ return { ...toHit(r, projectKey), projectId, projectRef, projectKey, projectName, teamName };
+}
+
// Text search across the given projects, archived issues included, at most
// perProjectLimit hits from each project. "KEY-42" matches issue 42 of every listed
// project whose key is KEY, since a key is unique only within its team.
@@ -579,14 +616,7 @@ export async function searchIssuesInProjects(
.where(and(inArray(issue.projectId, projectIds), textMatch(raw, numberMatch)))
.as('ranked');
const rows = await db
- .select({
- ...hitColumns,
- projectId: projectTable.id,
- projectRef: projectRefSql,
- projectKey: projectTable.key,
- projectName: projectTable.name,
- teamName: team.name,
- })
+ .select(crossProjectHitColumns)
.from(issue)
.innerJoin(ranked, eq(ranked.id, issue.id))
.innerJoin(projectTable, eq(projectTable.id, issue.projectId))
@@ -594,14 +624,56 @@ export async function searchIssuesInProjects(
.where(lte(ranked.rank, perProjectLimit))
.orderBy(...order)
.limit(limit);
- const hits = rows.map(({ projectId, projectRef, projectKey, projectName, teamName, ...r }) => ({
- ...toHit(r, projectKey),
- projectId,
- projectRef,
- projectKey,
- projectName,
- teamName,
- }));
+ const hits = rows.map(toCrossProjectHit);
+ await attachLabels(hits);
+ return hits;
+}
+
+export const ISSUE_STATE_TYPES = [
+ 'backlog',
+ 'unstarted',
+ 'started',
+ 'completed',
+ 'canceled',
+] as const;
+export type IssueStateType = (typeof ISSUE_STATE_TYPES)[number];
+
+// The filtered list over the given projects, most recently updated first. The ids it
+// takes (cycles, parents) are global, so they need no project to resolve against.
+export async function listIssuesInProjects(
+ projectIds: number[],
+ filters: FieldFilters & {
+ cycleIds?: number[];
+ parentIds?: number[];
+ stateTypes?: IssueStateType[];
+ limit: number;
+ },
+ opts: { includeArchived?: boolean } = {},
+): Promise<CrossProjectIssueHit[]> {
+ if (!projectIds.length) return [];
+ const conds: SQL[] = [inArray(issue.projectId, projectIds), ...fieldConds(filters)];
+ if (!opts.includeArchived) conds.push(isNull(issue.archivedAt));
+ if (filters.cycleIds) conds.push(inArray(issue.cycleId, filters.cycleIds));
+ if (filters.parentIds) conds.push(inArray(issue.parentId, filters.parentIds));
+ if (filters.stateTypes)
+ conds.push(
+ inArray(
+ issue.columnId,
+ db
+ .select({ id: projectColumn.id })
+ .from(projectColumn)
+ .where(inArray(projectColumn.stateType, filters.stateTypes)),
+ ),
+ );
+ const rows = await db
+ .select(crossProjectHitColumns)
+ .from(issue)
+ .innerJoin(projectTable, eq(projectTable.id, issue.projectId))
+ .innerJoin(team, eq(team.id, projectTable.teamId))
+ .where(and(...conds))
+ .orderBy(...hitOrder(undefined))
+ .limit(filters.limit);
+ const hits = rows.map(toCrossProjectHit);
await attachLabels(hits);
return hits;
}