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.

feat: search issues across all projects from the command palette and MCP (#705)

San Chenf2473836c28e
diff --git a/apps/api/src/mcp/instructions.ts b/apps/api/src/mcp/instructions.ts
index 79103b84..e972f06a 100644
--- a/apps/api/src/mcp/instructions.ts
+++ b/apps/api/src/mcp/instructions.ts
@@ -31,7 +31,8 @@ A checklistId and a checklist item's id come from get_issue: an issue carries it
checklists and their items.
search_issues and list_issues are for finding issues by text or by field, not for
-resolving an identifier.
+resolving an identifier. search_issues_all_projects searches by text in every
+project you can read, for when you do not know the project.
## You
diff --git a/apps/api/src/modules/agents/queue/service.ts b/apps/api/src/modules/agents/queue/service.ts
index 322960e6..d4abe6d1 100644
--- a/apps/api/src/modules/agents/queue/service.ts
+++ b/apps/api/src/modules/agents/queue/service.ts
@@ -1,20 +1,6 @@
-import {
- db,
- agentRun,
- agentSchedule,
- aiAgent,
- project,
- projectMember,
- team,
- teamRole,
- issue,
- revision,
-} from '@repo/db';
+import { db, agentRun, agentSchedule, aiAgent, project, team, issue, revision } from '@repo/db';
import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
-import { workspaceGrants } from '#modules/workspaces/service';
-import { toMemberContext, type MemberRole } from '#modules/members/service';
-import { projectAccess } from '#shared/workspace-roles';
-import { hasPermission } from '#shared/permissions';
+import { readableProjectIds } from '#shared/access';
import { iso } from '#shared/lib';
import { executionState, contextTokensOf } from '../core/run-queue';
@@ -26,44 +12,15 @@ const runnerPresence = sql<'push' | 'online' | 'offline' | 'never'>`CASE
WHEN ${aiAgent.lastSeenAt} > now() - interval '90 seconds' THEN 'online'
ELSE 'offline' END`;
-async function queueProjectIds(userId: string, mcpOnly = false) {
- const grants = await workspaceGrants(userId);
- const grantedTeams = [...grants.keys()];
- const rows = await db
- .select({
- id: project.id,
- teamId: project.teamId,
- role: projectMember.role,
- permissions: teamRole.permissions,
- })
- .from(project)
- .innerJoin(team, eq(team.id, project.teamId))
- .leftJoin(
- projectMember,
- and(eq(projectMember.projectId, project.id), eq(projectMember.userId, userId)),
- )
- .leftJoin(teamRole, eq(teamRole.id, projectMember.roleId))
- .where(
- and(
- mcpOnly ? and(eq(project.mcpEnabled, true), eq(team.mcpEnabled, true)) : undefined,
- or(
- isNotNull(projectMember.userId),
- grantedTeams.length ? inArray(project.teamId, grantedTeams) : undefined,
- ),
- ),
- );
- return rows
- .filter((row) => {
- const member = row.role ? toMemberContext(row.role as MemberRole, row.permissions) : null;
- const access = projectAccess(member, grants.get(row.teamId) ?? null);
- return (
- access &&
- hasPermission(access.permissions, 'work_items', 'read') &&
- hasPermission(access.permissions, 'ai_agents', 'read')
- );
- })
- .map((row) => row.id)
- .sort((a, b) => a - b);
+function queueProjectIds(userId: string, mcpOnly = false) {
+ return readableProjectIds(
+ userId,
+ [
+ ['work_items', 'read'],
+ ['ai_agents', 'read'],
+ ],
+ { mcpOnly, includeArchived: true },
+ );
}
export async function listRunnerQueue(
diff --git a/apps/api/src/modules/issues/__tests__/integration/search-all.test.ts b/apps/api/src/modules/issues/__tests__/integration/search-all.test.ts
new file mode 100644
index 00000000..31d17ea3
--- /dev/null
+++ b/apps/api/src/modules/issues/__tests__/integration/search-all.test.ts
@@ -0,0 +1,219 @@
+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { auth } from '@repo/auth';
+import { db, team } from '@repo/db';
+import { inArray } from 'drizzle-orm';
+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';
+import { emptyPermissions } from '#shared/permissions';
+import { readOnlyPermissions, setWorkspaceRoleGrant } from '#shared/workspace-roles';
+
+// GET /issues/search: text search 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 createIssue(api: Api, projectKey: string, title: string) {
+ const view = await api.projects({ projectKey }).get();
+ const res = await api
+ .projects({ projectKey })
+ .issues.post({ columnId: view.data!.columns[0]!.id, title });
+ return res.data!;
+}
+
+function search(
+ api: Api,
+ query: { q: string; limit?: number; perProjectLimit?: number; excludeProjectId?: number },
+) {
+ return api.issues.search.get({ query });
+}
+
+const titles = (res: Awaited<ReturnType<typeof search>>) =>
+ res.data?.map((hit) => hit.title).sort();
+
+describe('cross-project issue search', () => {
+ beforeEach(resetDb);
+ afterEach(() => setWorkspaceRoleGrant('admin', readOnlyPermissions()));
+
+ it('matches issues in every project of the caller, each with its project', async () => {
+ const { api } = await setup();
+ const mkt = await createIssue(api, 'MKT', 'Zephyr launch');
+ await createIssue(api, 'OPS', 'Zephyr rollout');
+ await createIssue(api, 'OPS', 'Unrelated');
+ await api.issues({ issueId: mkt.id }).archive.post();
+
+ const res = await search(api, { q: 'zephyr' });
+ const [ownTeam] = (await api.teams.get()).data!;
+ expect(res.status).toBe(200);
+ expect(titles(res)).toEqual(['Zephyr launch', 'Zephyr rollout']);
+ expect(res.data!.find((hit) => hit.id === mkt.id)).toMatchObject({
+ identifier: `MKT-${mkt.sequenceNumber}`,
+ projectKey: 'MKT',
+ projectName: 'Marketing',
+ projectRef: expect.stringMatching(/\.MKT$/),
+ teamName: ownTeam!.name,
+ archived: true,
+ });
+ });
+
+ it("leaves out another person's projects", async () => {
+ const { api } = await setup();
+ await createIssue(api, 'MKT', 'Secret plan');
+ const other = authedApi((await signUpTestUser()).cookie);
+
+ const res = await search(other, { q: 'secret' });
+ expect(res.status).toBe(200);
+ expect(res.data).toEqual([]);
+ });
+
+ it('leaves out a project whose role may not read work items', async () => {
+ const { api } = await setup();
+ await createIssue(api, 'MKT', 'Shared plan');
+ await createIssue(api, 'OPS', 'Shared runbook');
+ const reader = await createRole(api, 'MKT', {
+ name: 'Reader',
+ permissions: { work_items: { read: true } },
+ });
+ const blind = await createRole(api, 'OPS', { name: 'Blind', permissions: {} });
+ const asReader = await addProjectMember(api, 'MKT', reader.data!.id);
+ const asBlind = await addProjectMember(api, 'OPS', blind.data!.id);
+
+ expect(titles(await search(asReader, { q: 'shared' }))).toEqual(['Shared plan']);
+ expect(titles(await search(asBlind, { q: 'shared' }))).toEqual([]);
+ });
+
+ it('includes a project reached through a workspace role that reads work items', async () => {
+ const owner = await signUpTestUser({ team: false });
+ const lead = await signUpTestUser();
+ const admin = await signUpTestUser();
+ const asLead = authedApi(lead.cookie);
+ const project = (await createProject(asLead, { key: 'MKT', name: 'Marketing' })).data!;
+ await createIssue(asLead, 'MKT', 'Quarterly report');
+ const asAdmin = authedApi(admin.cookie);
+ const [adminTeam] = (await asAdmin.teams.get()).data!;
+ await db
+ .update(team)
+ .set({ workspaceId: owner.workspaceId! })
+ .where(inArray(team.id, [project.teamId, adminTeam!.id]));
+ await authedApi(owner.cookie)
+ .workspaces({ workspaceId: owner.workspaceId! })
+ .managers.post({ userId: admin.userId });
+
+ expect(titles(await search(authedApi(owner.cookie), { q: 'report' }))).toEqual([
+ 'Quarterly report',
+ ]);
+ expect(titles(await search(asAdmin, { q: 'report' }))).toEqual(['Quarterly report']);
+
+ setWorkspaceRoleGrant('admin', emptyPermissions());
+ expect(titles(await search(asAdmin, { q: 'report' }))).toEqual([]);
+ });
+
+ it('resolves "KEY-42" to that project, and a bare number to every project', async () => {
+ const { api } = await setup();
+ const mkt = await createIssue(api, 'MKT', 'First marketing');
+ const ops = await createIssue(api, 'OPS', 'First operations');
+ expect(ops.sequenceNumber).toBe(mkt.sequenceNumber);
+
+ const keyed = await search(api, { q: `ops-${ops.sequenceNumber}` });
+ expect(keyed.data!.map((hit) => hit.id)).toEqual([ops.id]);
+ expect(titles(await search(api, { q: String(mkt.sequenceNumber) }))).toEqual([
+ 'First marketing',
+ 'First operations',
+ ]);
+ });
+
+ it('caps the hits at limit and leaves out the excluded project', async () => {
+ const { api } = await setup();
+ const ops = await createIssue(api, 'OPS', 'Item four');
+ for (const title of ['Item one', 'Item two', 'Item three']) {
+ await createIssue(api, 'MKT', title);
+ }
+ const projectId = (await api.projects({ projectKey: 'MKT' }).get()).data!.project.id;
+
+ const capped = await search(api, { q: 'item', limit: 2 });
+ expect(capped.data!.map((hit) => hit.projectKey)).toEqual(['MKT', 'MKT']);
+ expect((await search(api, { q: 'item', limit: 2, excludeProjectId: projectId })).data).toEqual([
+ expect.objectContaining({ id: ops.id }),
+ ]);
+ });
+
+ it('takes at most perProjectLimit hits from each project, five by default', async () => {
+ const { api } = await setup();
+ for (let i = 1; i <= 6; i++) await createIssue(api, 'MKT', `Report ${i}`);
+ for (let i = 1; i <= 2; i++) await createIssue(api, 'OPS', `Report ops ${i}`);
+ const keysOf = (res: Awaited<ReturnType<typeof search>>) =>
+ res.data!.map((hit) => hit.projectKey).sort();
+
+ expect(keysOf(await search(api, { q: 'report' }))).toEqual([
+ ...Array<string>(5).fill('MKT'),
+ 'OPS',
+ 'OPS',
+ ]);
+ expect(keysOf(await search(api, { q: 'report', perProjectLimit: 2 }))).toEqual([
+ 'MKT',
+ 'MKT',
+ 'OPS',
+ 'OPS',
+ ]);
+ const newest = await search(api, { q: 'report', perProjectLimit: 2 });
+ expect(newest.data!.find((hit) => hit.projectKey === 'MKT')!.title).toBe('Report 6');
+ expect((await search(api, { q: 'report', limit: 3 })).data).toHaveLength(3);
+ });
+
+ it('rejects an empty query', async () => {
+ const { user } = await setup();
+ const res = await app.handle(
+ new Request('http://localhost/issues/search?q=', { headers: { cookie: user.cookie } }),
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it('serves the search_issues_all_projects MCP tool over the MCP-enabled projects', async () => {
+ const { user, api } = await setup();
+ await createIssue(api, 'MKT', 'Older plan');
+ 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: 'search' } });
+
+ 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: 'search_issues_all_projects',
+ arguments: { q: 'plan', perProjectLimit: 1 },
+ },
+ }),
+ }),
+ );
+ 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 5282466c..a5fe4b58 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -9,8 +9,10 @@ import {
assertProjectOwner,
assertProjectWritable,
assertWritable,
+ readableProjectIds,
requireUser,
} from '#shared/access';
+import { isMcpRequest } from '#shared/mcp-request';
import { getProjectById } from '#modules/projects/service';
import { HttpError, instantParam } from '#shared/lib';
import { accessErrors, commonErrors, errors } from '#shared/responses';
@@ -18,6 +20,7 @@ import { deleteObject } from '@repo/storage';
import {
createIssue,
searchIssues,
+ searchIssuesInProjects,
listIssues,
listArchivedIssues,
getIssue,
@@ -123,6 +126,7 @@ import {
updateWorklogBody,
IssueWithFieldsResponse,
IssueSearchHitResponse,
+ CrossProjectIssueHitResponse,
FeedItemResponse,
FeedPageResponse,
GroupedFeedPageResponse,
@@ -137,6 +141,7 @@ import {
bulkArchiveIssuesBody,
bulkDeleteIssuesBody,
searchIssuesQuery,
+ searchAllIssuesQuery,
listIssuesQuery,
issueSequenceParams,
updateIssueBody,
@@ -567,6 +572,37 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
)
+ // Text search across every project the caller may read work items in, matched like
+ // search_issues. This route comes before /issues/:issueId so the static "search"
+ // segment wins over the numeric param.
+ .get(
+ '/issues/search',
+ async ({ user, query, request }) => {
+ const ids = await readableProjectIds(requireUser(user).id, [['work_items', 'read']], {
+ mcpOnly: isMcpRequest(request.headers),
+ });
+ const clamp = (value: number) => Math.min(Math.max(value, 1), 50);
+ return searchIssuesInProjects(
+ ids.filter((id) => id !== query.excludeProjectId),
+ query.q,
+ { limit: clamp(query.limit ?? 20), perProjectLimit: clamp(query.perProjectLimit ?? 5) },
+ );
+ },
+ {
+ query: searchAllIssuesQuery,
+ response: { 200: t.Array(CrossProjectIssueHitResponse), ...errors(400, 401) },
+ detail: {
+ summary: 'Search issues in all projects',
+ description:
+ 'Search the issues of every project you can read by text, archived issues included, ' +
+ 'at most perProjectLimit hits from each project. Each hit names its project ' +
+ '(projectKey, projectRef, projectName, teamName); use search_issues for one project.',
+ ...requiresPermission(['work_items', 'read']),
+ ...mcpTool('search_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 843d40de..90bf66e5 100644
--- a/apps/api/src/modules/issues/model.ts
+++ b/apps/api/src/modules/issues/model.ts
@@ -335,6 +335,17 @@ export const IssueSearchHitResponse = t.Object({
completedAt: t.Nullable(t.String()),
});
+export const CrossProjectIssueHitResponse = t.Composite([
+ IssueSearchHitResponse,
+ t.Object({
+ projectId: t.Number(),
+ projectRef: t.String(),
+ projectKey: t.String(),
+ projectName: t.String(),
+ teamName: t.String(),
+ }),
+]);
+
// FeedItemRow from activity.ts: one timeline entry (comment or change-log).
// kind is the FeedKind union (a string).
export const FeedItemResponse = t.Object({
@@ -532,6 +543,19 @@ export const searchIssuesQuery = t.Object({
limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
});
+export const searchAllIssuesQuery = t.Object({
+ q: t.String({
+ minLength: 1,
+ description:
+ 'Case-insensitive substring, matched against the title, description, issue number ("KEY-42" or a bare number), and custom field text.',
+ }),
+ limit: t.Optional(t.Numeric({ description: 'Max results (1-50). Default 20.' })),
+ perProjectLimit: t.Optional(
+ t.Numeric({ description: 'Max results from one project (1-50). Default 5.' }),
+ ),
+ excludeProjectId: t.Optional(t.Numeric({ description: "Leave out this project's issues." })),
+});
+
export const listIssuesQuery = t.Object({
columnId: t.Optional(t.Numeric({ description: 'Exact column (state) id.' })),
typeId: t.Optional(t.Numeric({ description: 'Exact issue type id.' })),
diff --git a/apps/api/src/modules/issues/service.ts b/apps/api/src/modules/issues/service.ts
index 5a152c46..bc16bbb9 100644
--- a/apps/api/src/modules/issues/service.ts
+++ b/apps/api/src/modules/issues/service.ts
@@ -15,6 +15,7 @@ import {
customFieldOption,
initiative,
cycle,
+ team,
} from '@repo/db';
import {
and,
@@ -36,6 +37,7 @@ import {
import type { IssueQuery } from '#modules/agents/core/issue-query';
import { iso, num, numOrNull, HttpError } from '#shared/lib';
import type { ProjectRow } from '#modules/projects/service';
+import { projectRefSql } from '#modules/teams/ref';
import { assertProjectFeature } from '#shared/access';
import {
getCustomFieldById,
@@ -299,13 +301,90 @@ function escapeLike(value: string): string {
return value.replace(/[\\%_]/g, (c) => `\\${c}`);
}
+// The issue number in a text query: a bare number, or "KEY-42".
+function parseIssueNumber(raw: string): { key: string | null; seq: number } | null {
+ if (/^\d+$/.test(raw)) return { key: null, seq: Number(raw) };
+ const m = raw.match(/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/);
+ return m ? { key: m[1], seq: Number(m[2]) } : null;
+}
+
+// Text search: raw matches, case-insensitively, the title, description, scalar custom
+// field text values and select/multi_select option labels, or numberMatch.
+function textMatch(raw: string, numberMatch: SQL | undefined): SQL {
+ const pattern = `%${escapeLike(raw)}%`;
+ return or(
+ ilike(issue.title, pattern),
+ ilike(issue.description, pattern),
+ exists(
+ db
+ .select({ one: sql`1` })
+ .from(issueFieldValue)
+ .where(
+ and(eq(issueFieldValue.issueId, issue.id), ilike(issueFieldValue.valueText, pattern)),
+ ),
+ ),
+ exists(
+ db
+ .select({ one: sql`1` })
+ .from(issueFieldOption)
+ .innerJoin(customFieldOption, eq(customFieldOption.id, issueFieldOption.optionId))
+ .where(
+ and(eq(issueFieldOption.issueId, issue.id), ilike(customFieldOption.value, pattern)),
+ ),
+ ),
+ numberMatch,
+ )!;
+}
+
+function hitOrder(numberMatch: SQL | undefined): SQL[] {
+ const recent = sql`${issue.updatedAt} desc`;
+ return numberMatch ? [sql`case when ${numberMatch} then 0 else 1 end`, recent] : [recent];
+}
+
+const hitColumns = {
+ id: issue.id,
+ sequenceNumber: issue.sequenceNumber,
+ typeId: issue.typeId,
+ initiativeId: issue.initiativeId,
+ cycleId: issue.cycleId,
+ parentId: issue.parentId,
+ assigneeUserId: issue.assigneeUserId,
+ delegateUserId: issue.delegateUserId,
+ columnId: issue.columnId,
+ title: issue.title,
+ priority: issue.priority,
+ dueDate: issue.dueDate,
+ archivedAt: issue.archivedAt,
+ createdAt: issue.createdAt,
+ updatedAt: issue.updatedAt,
+ completedAt,
+};
+
+type HitRow = Omit<
+ IssueSearchHit,
+ 'identifier' | 'labelIds' | 'archived' | 'createdAt' | 'updatedAt' | 'completedAt'
+> & { archivedAt: Date | null; createdAt: Date; updatedAt: Date; completedAt: Date | null };
+
+function toHit(
+ { archivedAt, createdAt, updatedAt, completedAt, ...r }: HitRow,
+ projectKey: string,
+): IssueSearchHit {
+ return {
+ ...r,
+ identifier: `${projectKey}-${r.sequenceNumber}`,
+ labelIds: [],
+ archived: archivedAt !== null,
+ createdAt: iso(createdAt),
+ updatedAt: iso(updatedAt),
+ completedAt: completedAt ? iso(completedAt) : null,
+ };
+}
+
// Server-side issue read backing two routes: text search (search_issues) and the
-// filtered list (list_issues). Text search (filters.query) matches, case-
-// insensitively, the title, description, the issue number (a bare number, or
-// "KEY-42" for this project), scalar custom field text values, and
-// select/multi_select option labels. The other fields apply as exact filters (used
-// by list_issues). includeArchived adds archived issues to the result (search always
-// sets it; list defaults to active only).
+// 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
+// fields apply as exact filters (used by list_issues). includeArchived adds archived
+// issues to the result (search always sets it; list defaults to active only).
export async function searchIssues(
project: ProjectRow,
filters: IssueQuery & {
@@ -320,40 +399,12 @@ export async function searchIssues(
if (!opts.includeArchived) conds.push(isNull(issue.archivedAt));
const raw = filters.query?.trim();
- let seqMatch: number | null = null;
+ let numberMatch: SQL | undefined;
if (raw) {
- const pattern = `%${escapeLike(raw)}%`;
- // Recognise the issue number: a bare number, or "KEY-42" whose key matches this
- // project. Matched against sequence_number (the identifier is not a column).
- if (/^\d+$/.test(raw)) {
- seqMatch = Number(raw);
- } else {
- const m = raw.match(/^([A-Za-z][A-Za-z0-9]*)-(\d+)$/);
- if (m && m[1].toLowerCase() === project.key.toLowerCase()) seqMatch = Number(m[2]);
- }
- const textConds: SQL[] = [
- ilike(issue.title, pattern),
- ilike(issue.description, pattern),
- exists(
- db
- .select({ one: sql`1` })
- .from(issueFieldValue)
- .where(
- and(eq(issueFieldValue.issueId, issue.id), ilike(issueFieldValue.valueText, pattern)),
- ),
- ),
- exists(
- db
- .select({ one: sql`1` })
- .from(issueFieldOption)
- .innerJoin(customFieldOption, eq(customFieldOption.id, issueFieldOption.optionId))
- .where(
- and(eq(issueFieldOption.issueId, issue.id), ilike(customFieldOption.value, pattern)),
- ),
- ),
- ];
- if (seqMatch !== null) textConds.push(eq(issue.sequenceNumber, seqMatch));
- conds.push(or(...textConds)!);
+ const number = parseIssueNumber(raw);
+ if (number && (number.key === null || number.key.toLowerCase() === project.key.toLowerCase()))
+ numberMatch = eq(issue.sequenceNumber, number.seq);
+ conds.push(textMatch(raw, numberMatch));
}
// Exact filters, mirroring matchesIssue: undefined skips the filter, null matches
@@ -410,58 +461,82 @@ export async function searchIssues(
if (filters.updatedFrom) conds.push(gte(issue.updatedAt, filters.updatedFrom));
if (filters.updatedTo) conds.push(lt(issue.updatedAt, filters.updatedTo));
- // Exact number match first (if any), then most recently updated.
- const orderBy =
- seqMatch !== null
- ? [
- sql`case when ${issue.sequenceNumber} = ${seqMatch} then 0 else 1 end`,
- sql`${issue.updatedAt} desc`,
- ]
- : [sql`${issue.updatedAt} desc`];
-
const base = db
- .select({
- id: issue.id,
- sequenceNumber: issue.sequenceNumber,
- typeId: issue.typeId,
- initiativeId: issue.initiativeId,
- cycleId: issue.cycleId,
- parentId: issue.parentId,
- assigneeUserId: issue.assigneeUserId,
- delegateUserId: issue.delegateUserId,
- columnId: issue.columnId,
- title: issue.title,
- priority: issue.priority,
- dueDate: issue.dueDate,
- archivedAt: issue.archivedAt,
- createdAt: issue.createdAt,
- updatedAt: issue.updatedAt,
- completedAt,
- })
+ .select(hitColumns)
.from(issue)
.where(and(...conds))
- .orderBy(...orderBy);
+ .orderBy(...hitOrder(numberMatch));
const rows = filters.limit !== undefined ? await base.limit(filters.limit) : await base;
- const hits: IssueSearchHit[] = rows.map((r) => ({
- id: r.id,
- sequenceNumber: r.sequenceNumber,
- identifier: `${project.key}-${r.sequenceNumber}`,
- title: r.title,
- columnId: r.columnId,
- typeId: r.typeId,
- initiativeId: r.initiativeId,
- cycleId: r.cycleId,
- parentId: r.parentId,
- assigneeUserId: r.assigneeUserId,
- delegateUserId: r.delegateUserId,
- priority: r.priority,
- dueDate: r.dueDate,
- labelIds: [],
- archived: r.archivedAt !== null,
- createdAt: iso(r.createdAt),
- updatedAt: iso(r.updatedAt),
- completedAt: r.completedAt ? iso(r.completedAt) : null,
+ const hits = rows.map((r) => toHit(r, project.key));
+ await attachLabels(hits);
+ return hits;
+}
+
+export interface CrossProjectIssueHit extends IssueSearchHit {
+ projectId: number;
+ projectRef: string;
+ projectKey: string;
+ projectName: string;
+ teamName: string;
+}
+
+// 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.
+export async function searchIssuesInProjects(
+ projectIds: number[],
+ query: string,
+ { limit, perProjectLimit }: { limit: number; perProjectLimit: number },
+): Promise<CrossProjectIssueHit[]> {
+ const raw = query.trim();
+ if (!projectIds.length || !raw) return [];
+ const number = parseIssueNumber(raw);
+ const numberMatch = number
+ ? and(
+ eq(issue.sequenceNumber, number.seq),
+ number.key === null
+ ? undefined
+ : sql`lower(${projectTable.key}) = ${number.key.toLowerCase()}`,
+ )
+ : undefined;
+ const order = hitOrder(numberMatch);
+ // Only the id and the rank: the window sees every match, the hit columns are read
+ // for the rows that pass the cap.
+ const ranked = db
+ .select({
+ id: issue.id,
+ rank: sql<number>`row_number() over (partition by ${issue.projectId} order by ${sql.join(order, sql`, `)})`.as(
+ 'rank',
+ ),
+ })
+ .from(issue)
+ .innerJoin(projectTable, eq(projectTable.id, issue.projectId))
+ .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,
+ })
+ .from(issue)
+ .innerJoin(ranked, eq(ranked.id, issue.id))
+ .innerJoin(projectTable, eq(projectTable.id, issue.projectId))
+ .innerJoin(team, eq(team.id, projectTable.teamId))
+ .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,
}));
await attachLabels(hits);
return hits;
diff --git a/apps/api/src/shared/access.ts b/apps/api/src/shared/access.ts
index c78ecf7c..ef25be1a 100644
--- a/apps/api/src/shared/access.ts
+++ b/apps/api/src/shared/access.ts
@@ -1,3 +1,5 @@
+import { db, project, projectMember, team, teamRole } from '@repo/db';
+import { and, eq, inArray, isNotNull, isNull, or } from 'drizzle-orm';
import { HttpError } from './lib';
import {
getProjectById,
@@ -10,9 +12,15 @@ import {
getMemberContext,
getProjectPermissions,
getTeamPermissions,
+ toMemberContext,
+ type MemberRole,
} from '#modules/members/service';
import { getTeamMembership, runsTeam, type TeamStanding } from '#modules/teams/service';
-import { projectWorkspaceGrant, workspaceGrant } from '#modules/workspaces/service';
+import {
+ projectWorkspaceGrant,
+ workspaceGrant,
+ workspaceGrants,
+} from '#modules/workspaces/service';
import {
hasPermission,
emptyPermissions,
@@ -414,3 +422,49 @@ export async function projectsWithPermission(
.filter((entry) => hasPermission(entry.permissions, resource, action))
.map((entry) => entry.projectId);
}
+
+// Every project the user reaches, as a member or through their workspace role, where
+// their access holds each permission. mcpOnly keeps the projects open to MCP clients.
+export async function readableProjectIds(
+ userId: string,
+ required: [PermissionResource, PermissionAction][],
+ opts: { mcpOnly?: boolean; includeArchived?: boolean } = {},
+): Promise<number[]> {
+ const grants = await workspaceGrants(userId);
+ const grantedTeams = [...grants.keys()];
+ const rows = await db
+ .select({
+ id: project.id,
+ teamId: project.teamId,
+ role: projectMember.role,
+ permissions: teamRole.permissions,
+ })
+ .from(project)
+ .innerJoin(team, eq(team.id, project.teamId))
+ .leftJoin(
+ projectMember,
+ and(eq(projectMember.projectId, project.id), eq(projectMember.userId, userId)),
+ )
+ .leftJoin(teamRole, eq(teamRole.id, projectMember.roleId))
+ .where(
+ and(
+ opts.includeArchived ? undefined : isNull(project.archivedAt),
+ opts.mcpOnly ? and(eq(project.mcpEnabled, true), eq(team.mcpEnabled, true)) : undefined,
+ or(
+ isNotNull(projectMember.userId),
+ grantedTeams.length ? inArray(project.teamId, grantedTeams) : undefined,
+ ),
+ ),
+ );
+ return rows
+ .filter((row) => {
+ const member = row.role ? toMemberContext(row.role as MemberRole, row.permissions) : null;
+ const access = projectAccess(member, grants.get(row.teamId) ?? null);
+ return (
+ access &&
+ required.every(([resource, action]) => hasPermission(access.permissions, resource, action))
+ );
+ })
+ .map((row) => row.id)
+ .sort((a, b) => a - b);
+}
diff --git a/apps/web/messages/ar/palette.json b/apps/web/messages/ar/palette.json
index beb5ca40..1c6841a2 100644
--- a/apps/web/messages/ar/palette.json
+++ b/apps/web/messages/ar/palette.json
@@ -2,6 +2,10 @@
"placeholder": "اكتب أمرًا أو ابحث…",
"noResults": "لا توجد نتائج.",
"issues": "المهام",
+ "otherProjectIssues": "المهام في المشاريع الأخرى",
+ "searchScope": "نطاق البحث",
+ "scopeCurrent": "هذا المشروع",
+ "scopeAll": "كل المشاريع",
"searching": "جارٍ البحث…",
"selectAllIssues": "تحديد كل المهام",
"newIssue": "مهمة جديدة",
diff --git a/apps/web/messages/en/palette.json b/apps/web/messages/en/palette.json
index 997642ff..50aba40e 100644
--- a/apps/web/messages/en/palette.json
+++ b/apps/web/messages/en/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Type a command or search…",
"noResults": "No results found.",
"issues": "Issues",
+ "otherProjectIssues": "Issues in other projects",
+ "searchScope": "Search scope",
+ "scopeCurrent": "This project",
+ "scopeAll": "All projects",
"searching": "Searching…",
"selectAllIssues": "Select all issues",
"newIssue": "New issue",
diff --git a/apps/web/messages/es-ES/palette.json b/apps/web/messages/es-ES/palette.json
index 74b69906..80e8602c 100644
--- a/apps/web/messages/es-ES/palette.json
+++ b/apps/web/messages/es-ES/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Escribe un comando o busca…",
"noResults": "No se han encontrado resultados.",
"issues": "Tickets",
+ "otherProjectIssues": "Tickets de otros proyectos",
+ "searchScope": "Ámbito de búsqueda",
+ "scopeCurrent": "Este proyecto",
+ "scopeAll": "Todos los proyectos",
"searching": "Buscando…",
"selectAllIssues": "Seleccionar todos los tickets",
"newIssue": "Nuevo ticket",
diff --git a/apps/web/messages/fa/palette.json b/apps/web/messages/fa/palette.json
index edaa049a..6784a655 100644
--- a/apps/web/messages/fa/palette.json
+++ b/apps/web/messages/fa/palette.json
@@ -2,6 +2,10 @@
"placeholder": "یک دستور بنویسید یا جستجو کنید…",
"noResults": "نتیجه‌ای یافت نشد.",
"issues": "تسک‌ها",
+ "otherProjectIssues": "تسک‌ها در پروژه‌های دیگر",
+ "searchScope": "محدوده جستجو",
+ "scopeCurrent": "این پروژه",
+ "scopeAll": "همه پروژه‌ها",
"searching": "در حال جستجو…",
"selectAllIssues": "انتخاب همه تسک‌ها",
"newIssue": "تسک جدید",
diff --git a/apps/web/messages/fr/palette.json b/apps/web/messages/fr/palette.json
index 59a1f6f0..f3a57e4d 100644
--- a/apps/web/messages/fr/palette.json
+++ b/apps/web/messages/fr/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Saisissez une commande ou une recherche…",
"noResults": "Aucun résultat.",
"issues": "Tickets",
+ "otherProjectIssues": "Tickets des autres projets",
+ "searchScope": "Portée de la recherche",
+ "scopeCurrent": "Ce projet",
+ "scopeAll": "Tous les projets",
"searching": "Recherche…",
"selectAllIssues": "Sélectionner tous les tickets",
"newIssue": "Nouveau ticket",
diff --git a/apps/web/messages/id/palette.json b/apps/web/messages/id/palette.json
index 4c6a806b..c095ef0b 100644
--- a/apps/web/messages/id/palette.json
+++ b/apps/web/messages/id/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Ketik perintah atau cari…",
"noResults": "Tidak ada hasil yang ditemukan.",
"issues": "Issue",
+ "otherProjectIssues": "Issue di proyek lain",
+ "searchScope": "Cakupan pencarian",
+ "scopeCurrent": "Proyek ini",
+ "scopeAll": "Semua proyek",
"searching": "Mencari…",
"selectAllIssues": "Pilih semua issue",
"newIssue": "Issue baru",
diff --git a/apps/web/messages/ko/palette.json b/apps/web/messages/ko/palette.json
index 913d1f7e..e2196735 100644
--- a/apps/web/messages/ko/palette.json
+++ b/apps/web/messages/ko/palette.json
@@ -2,6 +2,10 @@
"placeholder": "명령 입력 또는 검색…",
"noResults": "검색 결과가 없습니다.",
"issues": "이슈",
+ "otherProjectIssues": "다른 프로젝트의 이슈",
+ "searchScope": "검색 범위",
+ "scopeCurrent": "이 프로젝트",
+ "scopeAll": "모든 프로젝트",
"searching": "검색 중…",
"selectAllIssues": "모든 이슈 선택",
"newIssue": "새 이슈",
diff --git a/apps/web/messages/pt-BR/palette.json b/apps/web/messages/pt-BR/palette.json
index d527f081..c4af932d 100644
--- a/apps/web/messages/pt-BR/palette.json
+++ b/apps/web/messages/pt-BR/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Digite um comando ou busque…",
"noResults": "Nenhum resultado encontrado.",
"issues": "Issues",
+ "otherProjectIssues": "Issues de outros projetos",
+ "searchScope": "Escopo da busca",
+ "scopeCurrent": "Este projeto",
+ "scopeAll": "Todos os projetos",
"searching": "Buscando…",
"selectAllIssues": "Selecionar todas as issues",
"newIssue": "Nova issue",
diff --git a/apps/web/messages/ru/palette.json b/apps/web/messages/ru/palette.json
index 1721f9b4..6ac50935 100644
--- a/apps/web/messages/ru/palette.json
+++ b/apps/web/messages/ru/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Введите команду или поисковый запрос…",
"noResults": "Ничего не найдено.",
"issues": "Задачи",
+ "otherProjectIssues": "Задачи в других проектах",
+ "searchScope": "Область поиска",
+ "scopeCurrent": "Этот проект",
+ "scopeAll": "Все проекты",
"searching": "Поиск…",
"selectAllIssues": "Выбрать все задачи",
"newIssue": "Новая задача",
diff --git a/apps/web/messages/tr/palette.json b/apps/web/messages/tr/palette.json
index 68740f08..98857c11 100644
--- a/apps/web/messages/tr/palette.json
+++ b/apps/web/messages/tr/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Bir komut yazın veya arama yapın…",
"noResults": "Sonuç bulunamadı.",
"issues": "İşler",
+ "otherProjectIssues": "Diğer projelerdeki işler",
+ "searchScope": "Arama kapsamı",
+ "scopeCurrent": "Bu proje",
+ "scopeAll": "Tüm projeler",
"searching": "Aranıyor…",
"selectAllIssues": "Tüm işleri seç",
"newIssue": "Yeni iş",
diff --git a/apps/web/messages/uk/palette.json b/apps/web/messages/uk/palette.json
index 08f0f188..a25e5364 100644
--- a/apps/web/messages/uk/palette.json
+++ b/apps/web/messages/uk/palette.json
@@ -2,6 +2,10 @@
"placeholder": "Введіть команду або пошуковий запит…",
"noResults": "Нічого не знайдено.",
"issues": "Задачі",
+ "otherProjectIssues": "Задачі в інших проєктах",
+ "searchScope": "Область пошуку",
+ "scopeCurrent": "Цей проєкт",
+ "scopeAll": "Усі проєкти",
"searching": "Пошук…",
"selectAllIssues": "Вибрати всі задачі",
"newIssue": "Нова задача",
diff --git a/apps/web/messages/zh-CN/palette.json b/apps/web/messages/zh-CN/palette.json
index 3c579ce5..03d565aa 100644
--- a/apps/web/messages/zh-CN/palette.json
+++ b/apps/web/messages/zh-CN/palette.json
@@ -2,6 +2,10 @@
"placeholder": "输入命令或搜索…",
"noResults": "未找到结果。",
"issues": "工作项",
+ "otherProjectIssues": "其他项目的工作项",
+ "searchScope": "搜索范围",
+ "scopeCurrent": "当前项目",
+ "scopeAll": "所有项目",
"searching": "正在搜索…",
"selectAllIssues": "选择所有工作项",
"newIssue": "新建工作项",
diff --git a/apps/web/messages/zh-TW/palette.json b/apps/web/messages/zh-TW/palette.json
index 65c7e8ef..bc0a15d5 100644
--- a/apps/web/messages/zh-TW/palette.json
+++ b/apps/web/messages/zh-TW/palette.json
@@ -2,6 +2,10 @@
"placeholder": "輸入命令或搜尋…",
"noResults": "未找到結果。",
"issues": "工作項目",
+ "otherProjectIssues": "其他專案的工作項目",
+ "searchScope": "搜尋範圍",
+ "scopeCurrent": "目前專案",
+ "scopeAll": "所有專案",
"searching": "正在搜尋…",
"selectAllIssues": "選擇所有工作項目",
"newIssue": "新建工作項目",
diff --git a/apps/web/src/components/layout/CommandLayer.tsx b/apps/web/src/components/layout/CommandLayer.tsx
index 6dc46f86..8e73deef 100644
--- a/apps/web/src/components/layout/CommandLayer.tsx
+++ b/apps/web/src/components/layout/CommandLayer.tsx
@@ -83,7 +83,7 @@ export default function CommandLayer({
onOpenChange={onOpenChange}
sections={sections}
currentProjectKey={currentProjectKey}
- hasProject={hasProject}
+ currentProjectId={project?.project.id ?? null}
onOpenIssue={onOpenIssue}
/>
{issue.dialogs}
diff --git a/apps/web/src/components/layout/CommandPalette.test.tsx b/apps/web/src/components/layout/CommandPalette.test.tsx
new file mode 100644
index 00000000..5a2cba94
--- /dev/null
+++ b/apps/web/src/components/layout/CommandPalette.test.tsx
@@ -0,0 +1,240 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { NextIntlClientProvider } from 'next-intl';
+import { AppRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';
+import { JSDOM } from 'jsdom';
+import palette from '../../../messages/en/palette.json';
+import common from '../../../messages/en/common.json';
+import documents from '../../../messages/en/documents.json';
+
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'NodeFilter',
+ 'DocumentFragment',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLInputElement',
+ 'SVGElement',
+ 'ShadowRoot',
+ 'Event',
+ 'CustomEvent',
+ 'MouseEvent',
+ 'KeyboardEvent',
+ 'MutationObserver',
+ 'getComputedStyle',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'ResizeObserver',
+ 'localStorage',
+ 'fetch',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+const hit = {
+ sequenceNumber: 1,
+ columnId: 1,
+ typeId: null,
+ initiativeId: null,
+ cycleId: null,
+ parentId: null,
+ assigneeUserId: null,
+ delegateUserId: null,
+ priority: null,
+ dueDate: null,
+ labelIds: [],
+ archived: false,
+};
+const currentHit = { ...hit, id: 1, identifier: 'MKT-1', title: 'Launch plan' };
+const otherHit = {
+ ...hit,
+ id: 2,
+ identifier: 'OPS-1',
+ title: 'Launch runbook',
+ projectId: 2,
+ projectRef: 'eng.OPS',
+ projectKey: 'OPS',
+ projectName: 'Operations',
+ teamName: 'Engineering',
+};
+
+let dom: JSDOM;
+let root: Root;
+let client: QueryClient;
+let requests: URL[];
+let held: Promise<void> | null;
+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
+
+const allProjectRequests = () => requests.filter((url) => url.pathname === '/issues/search');
+const headings = () =>
+ [...document.querySelectorAll('[cmdk-group-heading]')].map((el) => el.textContent);
+const tabs = () => [...document.querySelectorAll<HTMLElement>('[role="tab"]')];
+
+async function settle(ms = 0) {
+ await act(async () => new Promise((resolve) => setTimeout(resolve, ms)));
+}
+
+async function render(project: { key: string; id: number } | null) {
+ const { default: CommandPalette } = await import('./CommandPalette');
+ await act(async () =>
+ root.render(
+ <AppRouterContext.Provider value={{ push() {}, prefetch() {} } as never}>
+ <QueryClientProvider client={client}>
+ <NextIntlClientProvider
+ locale="en"
+ messages={{ palette, common, documents }}
+ timeZone="UTC"
+ >
+ <CommandPalette
+ open
+ onOpenChange={() => {}}
+ sections={[]}
+ currentProjectKey={project?.key ?? null}
+ currentProjectId={project?.id ?? null}
+ onOpenIssue={() => {}}
+ />
+ </NextIntlClientProvider>
+ </QueryClientProvider>
+ </AppRouterContext.Provider>,
+ ),
+ );
+ await settle();
+}
+
+// Types into the search input the way React sees a keystroke, then waits out the
+// palette's debounce and the requests it sends.
+async function type(value: string) {
+ const input = document.querySelector<HTMLInputElement>('[cmdk-input]')!;
+ const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(input, value);
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ });
+ await settle(300);
+ await settle(20);
+}
+
+beforeEach(async () => {
+ originalGlobalDescriptors = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', {
+ url: 'https://example.test/eng/MKT',
+ pretendToBeVisual: true,
+ });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ requests = [];
+ held = null;
+ Object.defineProperties(globalThis, {
+ getComputedStyle: { configurable: true, value: dom.window.getComputedStyle.bind(dom.window) },
+ requestAnimationFrame: {
+ configurable: true,
+ value: dom.window.requestAnimationFrame.bind(dom.window),
+ },
+ cancelAnimationFrame: {
+ configurable: true,
+ value: dom.window.cancelAnimationFrame.bind(dom.window),
+ },
+ ResizeObserver: {
+ configurable: true,
+ value: class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ },
+ fetch: {
+ configurable: true,
+ value: async (input: string | URL) => {
+ const url = new URL(String(input));
+ requests.push(url);
+ if (url.pathname === '/issues/search') {
+ await held;
+ return Response.json([otherHit]);
+ }
+ if (url.pathname.endsWith('/issues/search')) return Response.json([currentHit]);
+ return Response.json(null);
+ },
+ },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ Object.defineProperty(window, '__ITSAPLAN_ENV__', {
+ value: { apiUrl: 'https://api.test', privacyUrl: '', termsUrl: '' },
+ });
+ window.HTMLElement.prototype.scrollIntoView = () => {};
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ client.clear();
+ // Better Auth's stores dispose their browser listeners one second after unmount.
+ await new Promise((resolve) => setTimeout(resolve, 1100));
+ dom.window.close();
+ for (const [name, descriptor] of originalGlobalDescriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('CommandPalette search scope', () => {
+ it('searches every project by default, below the open one', async () => {
+ await render({ key: 'eng.MKT', id: 1 });
+ assert.deepEqual(
+ tabs().map((tab) => [tab.textContent, tab.getAttribute('aria-selected')]),
+ [
+ ['This project', 'false'],
+ ['All projects', 'true'],
+ ],
+ );
+
+ await type('launch');
+ assert.equal(allProjectRequests()[0]!.searchParams.get('excludeProjectId'), '1');
+ assert.deepEqual(headings(), ['Issues', 'Engineering / OperationsOPS']);
+ });
+
+ it('searches only the open project once narrowed, and remembers the choice', async () => {
+ await render({ key: 'eng.MKT', id: 1 });
+ await act(async () => tabs()[0]!.click());
+ await type('launch');
+
+ assert.equal(allProjectRequests().length, 0);
+ assert.deepEqual(headings(), ['Issues']);
+ assert.equal(localStorage.getItem('command-palette:search-scope'), 'current');
+ });
+
+ it('searches every project with no switch when no project is open', async () => {
+ localStorage.setItem('command-palette:search-scope', 'current');
+ await render(null);
+ assert.equal(tabs().length, 0);
+
+ await type('launch');
+ assert.equal(allProjectRequests()[0]!.searchParams.has('excludeProjectId'), false);
+ assert.deepEqual(headings(), ['Engineering / OperationsOPS']);
+ });
+
+ it('drops the other projects, still searching, once narrowed to the open project', async () => {
+ held = new Promise(() => {});
+ await render({ key: 'eng.MKT', id: 1 });
+ await type('launch');
+ assert.deepEqual(headings(), ['Issues', 'Issues in other projects']);
+
+ await act(async () => tabs()[0]!.click());
+ await settle();
+ assert.deepEqual(headings(), ['Issues']);
+ });
+});
diff --git a/apps/web/src/components/layout/CommandPalette.tsx b/apps/web/src/components/layout/CommandPalette.tsx
index 6a5ef64b..652ba2d0 100644
--- a/apps/web/src/components/layout/CommandPalette.tsx
+++ b/apps/web/src/components/layout/CommandPalette.tsx
@@ -1,11 +1,16 @@
import { Fragment, useEffect, useState } from 'react';
+import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useDebouncedValue } from '@/hooks/useDebouncedValue';
-import { useIssueSearchQuery } from '@/services/issues.service';
+import { useIssueSearchQuery, useOtherProjectIssueSearch } from '@/services/issues.service';
+import { issuePath } from '@/utils/paths';
import type { Command, CommandPage, CommandSection } from '@/utils/commands';
import { substringFilter } from '@/utils/commandFilter';
import CommandPaletteDocuments from './CommandPaletteDocuments';
import CommandPaletteIssues from '@/components/layout/CommandPaletteIssues';
+import CommandPaletteOtherIssues from './CommandPaletteOtherIssues';
+import CommandPaletteScope from './CommandPaletteScope';
+import { usePaletteSearchScope } from './hooks/usePaletteSearchScope';
import CommandPaletteRow from '@/components/layout/CommandPaletteRow';
import {
CommandDialog,
@@ -20,25 +25,28 @@ import {
// for the issue in front of the user, then the board, the general commands, the
// project list and every section they may open. A command with a submenu opens a
// second level (status, priority, assignee, labels); Backspace on an empty input
-// goes back. While the user is typing, a last "Issues" group lists issues the
-// server matches by identifier, title, description, number or custom fields
-// (archived issues included), so a search separates sections, commands and issues.
+// goes back. While the user is typing, an "Issues" group lists issues of the current
+// project the server matches by identifier, title, description, number or custom
+// fields (archived issues included), and the last groups list the matches in every
+// other project the user can read, one group per project. While a project is open, a
+// switch narrows the search to it.
export default function CommandPalette({
open,
onOpenChange,
sections,
currentProjectKey,
- hasProject,
+ currentProjectId,
onOpenIssue,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
sections: CommandSection[];
currentProjectKey: string | null;
- hasProject: boolean;
+ currentProjectId: number | null;
onOpenIssue: (sequenceNumber: number) => void;
}) {
const t = useTranslations('palette');
+ const router = useRouter();
const [query, setQuery] = useState('');
const [page, setPage] = useState<CommandPage | null>(null);
@@ -66,6 +74,14 @@ export default function CommandPalette({
const debounced = useDebouncedValue(query, 250);
const search = useIssueSearchQuery(currentProjectKey, debounced, { enabled: open && !page });
const hits = search.data ?? [];
+ const { scope, setScope } = usePaletteSearchScope();
+ const allProjects = currentProjectKey === null || scope === 'all';
+ const others = useOtherProjectIssueSearch(
+ debounced,
+ { key: currentProjectKey, id: currentProjectId },
+ { enabled: open && !page && allProjects },
+ );
+ const hasProject = currentProjectId !== null;
const searching = query.trim().length > 0;
function run(command: Command) {
@@ -93,6 +109,9 @@ export default function CommandPalette({
}
}}
/>
+ {!page && currentProjectKey !== null && (
+ <CommandPaletteScope scope={scope} onChange={setScope} />
+ )}
<CommandList>
<CommandEmpty>{t('noResults')}</CommandEmpty>
{page ? (
@@ -123,11 +142,23 @@ export default function CommandPalette({
palette would list the entire project on open. */}
{!page && hasProject && searching && (hits.length > 0 || search.isFetching) && (
<CommandPaletteIssues
+ heading={t('issues')}
hits={hits}
fetching={search.isFetching}
- onOpenIssue={(seq) => {
+ onOpenIssue={(hit) => {
+ onOpenChange(false);
+ onOpenIssue(hit.sequenceNumber);
+ }}
+ />
+ )}
+ {!page && searching && (others.hits.length > 0 || others.fetching) && (
+ <CommandPaletteOtherIssues
+ hits={others.hits}
+ fetching={others.fetching}
+ loadingHeading={hasProject ? t('otherProjectIssues') : t('issues')}
+ onOpenIssue={(hit) => {
onOpenChange(false);
- onOpenIssue(seq);
+ router.push(issuePath(hit.projectRef, hit.sequenceNumber));
}}
/>
)}
diff --git a/apps/web/src/components/layout/CommandPaletteIssues.tsx b/apps/web/src/components/layout/CommandPaletteIssues.tsx
index 940820e1..4cb6d728 100644
--- a/apps/web/src/components/layout/CommandPaletteIssues.tsx
+++ b/apps/web/src/components/layout/CommandPaletteIssues.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from 'react';
import { Hash } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { IssueSearchHit } from '@/lib/api/endpoints/issues';
@@ -5,24 +6,30 @@ import { ISSUE_PREFIX } from '@/utils/commandFilter';
import { CommandGroup, CommandItem, CommandSeparator } from '@/components/ui/command';
import ArchivedBadge from '@/components/common/ArchivedBadge';
-// The palette's "Issues" group. The list comes from the server (already filtered
-// and ordered); the ISSUE_PREFIX value keeps cmdk from re-filtering it.
-export default function CommandPaletteIssues({
+// A palette group of issue hits. The list comes from the server (already filtered
+// and ordered); the ISSUE_PREFIX value keeps cmdk from re-filtering it. A later
+// group starts its values at valueOffset, so the values stay unique and it sorts
+// below the groups before it.
+export default function CommandPaletteIssues<T extends IssueSearchHit>({
+ heading,
hits,
fetching,
+ valueOffset = 0,
onOpenIssue,
}: {
- hits: IssueSearchHit[];
+ heading: ReactNode;
+ hits: T[];
fetching: boolean;
- onOpenIssue: (sequenceNumber: number) => void;
+ valueOffset?: number;
+ onOpenIssue: (hit: T) => void;
}) {
const t = useTranslations('palette');
return (
<>
<CommandSeparator />
- <CommandGroup heading={t('issues')}>
+ <CommandGroup heading={heading}>
{hits.length === 0 && fetching && (
- <CommandItem value={`${ISSUE_PREFIX}0`} disabled>
+ <CommandItem value={`${ISSUE_PREFIX}${valueOffset}`} disabled>
<Hash />
<span className="text-muted-foreground">{t('searching')}</span>
</CommandItem>
@@ -30,8 +37,8 @@ export default function CommandPaletteIssues({
{hits.map((issue, i) => (
<CommandItem
key={issue.id}
- value={`${ISSUE_PREFIX}${i}`}
- onSelect={() => onOpenIssue(issue.sequenceNumber)}
+ value={`${ISSUE_PREFIX}${valueOffset + i}`}
+ onSelect={() => onOpenIssue(issue)}
>
<Hash />
<span className="flex-1 truncate">{issue.title}</span>
diff --git a/apps/web/src/components/layout/CommandPaletteOtherIssues.test.tsx b/apps/web/src/components/layout/CommandPaletteOtherIssues.test.tsx
new file mode 100644
index 00000000..bc2f723d
--- /dev/null
+++ b/apps/web/src/components/layout/CommandPaletteOtherIssues.test.tsx
@@ -0,0 +1,188 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import type { CrossProjectIssueHit, IssueSearchHit } from '@/lib/api/endpoints/issues';
+import palette from '../../../messages/en/palette.json';
+import common from '../../../messages/en/common.json';
+
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'SVGElement',
+ 'Event',
+ 'MutationObserver',
+ 'getComputedStyle',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'ResizeObserver',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+function hit(id: number, identifier: string, title: string): IssueSearchHit {
+ return {
+ id,
+ sequenceNumber: Number(identifier.split('-')[1]),
+ identifier,
+ title,
+ columnId: 1,
+ typeId: null,
+ initiativeId: null,
+ cycleId: null,
+ parentId: null,
+ assigneeUserId: null,
+ delegateUserId: null,
+ priority: null,
+ dueDate: null,
+ labelIds: [],
+ archived: false,
+ };
+}
+
+const current = [hit(1, 'MKT-1', 'Launch plan'), hit(2, 'MKT-2', 'Launch budget')];
+
+function other(
+ id: number,
+ identifier: string,
+ project: { id: number; key: string; name: string; team: string },
+): CrossProjectIssueHit {
+ return {
+ ...hit(id, identifier, `Launch ${identifier}`),
+ projectId: project.id,
+ projectRef: `eng.${project.key}`,
+ projectKey: project.key,
+ projectName: project.name,
+ teamName: project.team,
+ };
+}
+
+const ops = { id: 2, key: 'OPS', name: 'Operations', team: 'Engineering' };
+const doc = { id: 3, key: 'DOC', name: 'Docs', team: 'Engineering' };
+const sup = { id: 4, key: 'SUP', name: 'Helpdesk', team: 'Support' };
+// Server order: OPS's best hit first, then DOC's, then SUP's.
+const others = [
+ other(3, 'OPS-1', ops),
+ other(4, 'DOC-1', doc),
+ other(5, 'OPS-2', ops),
+ other(6, 'SUP-1', sup),
+];
+
+let dom: JSDOM;
+let root: Root;
+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
+let opened: string[];
+
+async function render(otherHits = others, fetching = false) {
+ const { Command, CommandList } = await import('@/components/ui/command');
+ const { substringFilter } = await import('@/utils/commandFilter');
+ const { default: CommandPaletteIssues } = await import('./CommandPaletteIssues');
+ const { default: CommandPaletteOtherIssues } = await import('./CommandPaletteOtherIssues');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ palette, common }} timeZone="UTC">
+ <Command filter={substringFilter}>
+ <CommandList>
+ <CommandPaletteIssues
+ heading="Issues"
+ hits={current}
+ fetching={false}
+ onOpenIssue={(issue) => opened.push(issue.identifier)}
+ />
+ <CommandPaletteOtherIssues
+ hits={otherHits}
+ fetching={fetching}
+ loadingHeading="Issues in other projects"
+ onOpenIssue={(issue) => opened.push(`${issue.projectRef}/${issue.sequenceNumber}`)}
+ />
+ </CommandList>
+ </Command>
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+beforeEach(async () => {
+ originalGlobalDescriptors = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { pretendToBeVisual: true });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperties(globalThis, {
+ getComputedStyle: { configurable: true, value: dom.window.getComputedStyle.bind(dom.window) },
+ ResizeObserver: {
+ configurable: true,
+ value: class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ window.HTMLElement.prototype.scrollIntoView = () => {};
+ opened = [];
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originalGlobalDescriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+const headings = () =>
+ [...document.querySelectorAll('[cmdk-group-heading]')].map((el) => el.textContent);
+const rows = () => [...document.querySelectorAll<HTMLElement>('[cmdk-item]')];
+
+describe('CommandPaletteOtherIssues', () => {
+ it('groups the other projects by project below the current one, in server order', async () => {
+ await render();
+ assert.deepEqual(headings(), [
+ 'Issues',
+ 'Engineering / OperationsOPS',
+ 'Engineering / DocsDOC',
+ 'Support / HelpdeskSUP',
+ ]);
+ assert.deepEqual(
+ rows().map((row) => row.textContent),
+ [
+ 'Launch planMKT-1',
+ 'Launch budgetMKT-2',
+ 'Launch OPS-1OPS-1',
+ 'Launch OPS-2OPS-2',
+ 'Launch DOC-1DOC-1',
+ 'Launch SUP-1SUP-1',
+ ],
+ );
+ assert.equal(new Set(rows().map((row) => row.dataset.value)).size, 6);
+ });
+
+ it('shows one searching row until the first hits arrive', async () => {
+ await render([], true);
+ assert.deepEqual(headings(), ['Issues', 'Issues in other projects']);
+ assert.equal(rows().at(-1)!.textContent, 'Searching…');
+ });
+
+ it('opens the hit that was selected', async () => {
+ await render();
+ await act(async () => rows().at(-1)!.click());
+ assert.deepEqual(opened, ['eng.SUP/1']);
+ });
+});
diff --git a/apps/web/src/components/layout/CommandPaletteOtherIssues.tsx b/apps/web/src/components/layout/CommandPaletteOtherIssues.tsx
new file mode 100644
index 00000000..b84b87a5
--- /dev/null
+++ b/apps/web/src/components/layout/CommandPaletteOtherIssues.tsx
@@ -0,0 +1,58 @@
+import type { CrossProjectIssueHit } from '@/lib/api/endpoints/issues';
+import CommandPaletteIssues from './CommandPaletteIssues';
+
+// The other projects' hits, one group per project in the order the server ranks
+// their best hit. Values are numbered across the groups, after the current project's
+// group, so they stay unique and cmdk keeps that order.
+export default function CommandPaletteOtherIssues({
+ hits,
+ fetching,
+ loadingHeading,
+ onOpenIssue,
+}: {
+ hits: CrossProjectIssueHit[];
+ fetching: boolean;
+ loadingHeading: string;
+ onOpenIssue: (hit: CrossProjectIssueHit) => void;
+}) {
+ if (hits.length === 0) {
+ return (
+ <CommandPaletteIssues
+ heading={loadingHeading}
+ hits={[]}
+ fetching={fetching}
+ valueOffset={1000}
+ onOpenIssue={onOpenIssue}
+ />
+ );
+ }
+ const groups = new Map<number, CrossProjectIssueHit[]>();
+ for (const hit of hits) {
+ const group = groups.get(hit.projectId);
+ if (group) group.push(hit);
+ else groups.set(hit.projectId, [hit]);
+ }
+ let offset = 1000;
+ return [...groups.values()].map((group) => {
+ const [first] = group;
+ const valueOffset = offset;
+ offset += group.length;
+ return (
+ <CommandPaletteIssues
+ key={first!.projectId}
+ heading={
+ <span className="flex items-center gap-2">
+ <span className="min-w-0 flex-1 truncate">
+ {first!.teamName} / {first!.projectName}
+ </span>
+ <span className="shrink-0 font-mono">{first!.projectKey}</span>
+ </span>
+ }
+ hits={group}
+ fetching={false}
+ valueOffset={valueOffset}
+ onOpenIssue={onOpenIssue}
+ />
+ );
+ });
+}
diff --git a/apps/web/src/components/layout/CommandPaletteScope.test.tsx b/apps/web/src/components/layout/CommandPaletteScope.test.tsx
new file mode 100644
index 00000000..f868841f
--- /dev/null
+++ b/apps/web/src/components/layout/CommandPaletteScope.test.tsx
@@ -0,0 +1,156 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import palette from '../../../messages/en/palette.json';
+import type { PaletteSearchScope } from './hooks/usePaletteSearchScope';
+
+const replaced = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'Event',
+ 'MouseEvent',
+ 'KeyboardEvent',
+ 'MutationObserver',
+ 'ResizeObserver',
+ 'requestAnimationFrame',
+ 'cancelAnimationFrame',
+ 'IS_REACT_ACT_ENVIRONMENT',
+];
+
+let dom: JSDOM;
+let root: Root;
+let chosen: PaletteSearchScope[];
+let ran: string[];
+let descriptors: Map<string, PropertyDescriptor | undefined>;
+
+// The switch sits inside the palette's cmdk root, next to a selected command.
+async function render(scope: PaletteSearchScope) {
+ const { Command, CommandItem, CommandList } = await import('@/components/ui/command');
+ const { default: CommandPaletteScope } = await import('./CommandPaletteScope');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ palette }} timeZone="UTC">
+ <Command>
+ <CommandPaletteScope scope={scope} onChange={(next) => chosen.push(next)} />
+ <CommandList>
+ <CommandItem value="new-issue" onSelect={() => ran.push('new-issue')}>
+ New issue
+ </CommandItem>
+ </CommandList>
+ </Command>
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+async function key(target: HTMLElement, value: string) {
+ await act(async () => {
+ target.dispatchEvent(
+ new KeyboardEvent('keydown', { key: value, bubbles: true, cancelable: true }),
+ );
+ // Radix moves the focus between triggers on the next tick.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+function trigger(text: string) {
+ const found = [...document.querySelectorAll<HTMLElement>('[role="tab"]')].find(
+ (tab) => tab.textContent === text,
+ );
+ assert.ok(found, text);
+ return found;
+}
+
+beforeEach(async () => {
+ descriptors = new Map(
+ replaced.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<div id="root"></div>', { pretendToBeVisual: true });
+ for (const name of replaced) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ chosen = [];
+ ran = [];
+ Object.defineProperties(globalThis, {
+ requestAnimationFrame: {
+ configurable: true,
+ value: dom.window.requestAnimationFrame.bind(dom.window),
+ },
+ cancelAnimationFrame: {
+ configurable: true,
+ value: dom.window.cancelAnimationFrame.bind(dom.window),
+ },
+ });
+ Object.defineProperty(globalThis, 'ResizeObserver', {
+ configurable: true,
+ value: class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ });
+ window.HTMLElement.prototype.scrollIntoView = () => {};
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of descriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+it('marks the chosen scope and reports a click on the other one', async () => {
+ await render('all');
+ assert.equal(trigger('All projects').getAttribute('aria-selected'), 'true');
+ assert.equal(trigger('This project').getAttribute('aria-selected'), 'false');
+
+ await act(async () => trigger('This project').click());
+ assert.deepEqual(chosen, ['current']);
+});
+
+it('keeps the focus where it is when a scope is pressed', async () => {
+ await render('all');
+ const press = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
+ await act(async () => trigger('This project').dispatchEvent(press));
+ assert.equal(press.defaultPrevented, true);
+});
+
+it('switches with the arrow keys', async () => {
+ await render('all');
+ const all = trigger('All projects');
+ await act(async () => all.focus());
+ await key(all, 'ArrowLeft');
+ assert.equal(document.activeElement, trigger('This project'));
+ assert.deepEqual(chosen, ['current']);
+});
+
+it("selects a scope with Enter and leaves the palette's command alone", async () => {
+ await render('all');
+ assert.equal(document.querySelector('[cmdk-item]')!.getAttribute('aria-selected'), 'true');
+ const current = trigger('This project');
+ await act(async () => current.focus());
+ chosen = [];
+ await key(current, 'Enter');
+ assert.deepEqual(chosen, ['current']);
+ assert.deepEqual(ran, []);
+});
diff --git a/apps/web/src/components/layout/CommandPaletteScope.tsx b/apps/web/src/components/layout/CommandPaletteScope.tsx
new file mode 100644
index 00000000..29d20557
--- /dev/null
+++ b/apps/web/src/components/layout/CommandPaletteScope.tsx
@@ -0,0 +1,45 @@
+import { useTranslations } from 'next-intl';
+import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import type { PaletteSearchScope } from './hooks/usePaletteSearchScope';
+
+const SCOPES: { value: PaletteSearchScope; label: 'scopeCurrent' | 'scopeAll' }[] = [
+ { value: 'current', label: 'scopeCurrent' },
+ { value: 'all', label: 'scopeAll' },
+];
+
+// The palette's search scope switch. A trigger takes no focus on press, so the
+// search input keeps it and the arrow keys keep moving through the results; Radix
+// skips its own press handler then, so the click selects. A focused trigger keeps
+// Enter from the palette, which would otherwise run the selected command.
+export default function CommandPaletteScope({
+ scope,
+ onChange,
+}: {
+ scope: PaletteSearchScope;
+ onChange: (scope: PaletteSearchScope) => void;
+}) {
+ const t = useTranslations('palette');
+ return (
+ <div className="flex items-center gap-2 border-b px-3 py-1.5 text-xs text-muted-foreground">
+ <span>{t('searchScope')}</span>
+ <Tabs value={scope} onValueChange={(next) => onChange(next as PaletteSearchScope)}>
+ <TabsList aria-label={t('searchScope')} className="h-7">
+ {SCOPES.map(({ value, label }) => (
+ <TabsTrigger
+ key={value}
+ value={value}
+ className="px-2.5 text-xs"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => onChange(value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.stopPropagation();
+ }}
+ >
+ {t(label)}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/layout/hooks/usePaletteSearchScope.test.tsx b/apps/web/src/components/layout/hooks/usePaletteSearchScope.test.tsx
new file mode 100644
index 00000000..07ea7183
--- /dev/null
+++ b/apps/web/src/components/layout/hooks/usePaletteSearchScope.test.tsx
@@ -0,0 +1,86 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { JSDOM } from 'jsdom';
+import { usePaletteSearchScope } from './usePaletteSearchScope';
+
+const STORAGE_KEY = 'command-palette:search-scope';
+const replaced = ['window', 'document', 'navigator', 'localStorage', 'IS_REACT_ACT_ENVIRONMENT'];
+
+let dom: JSDOM;
+let root: Root;
+let result: ReturnType<typeof usePaletteSearchScope>;
+let descriptors: Map<string, PropertyDescriptor | undefined>;
+
+function Harness() {
+ result = usePaletteSearchScope();
+ return null;
+}
+
+async function render() {
+ await act(async () => root.render(<Harness />));
+}
+
+beforeEach(async () => {
+ descriptors = new Map(
+ replaced.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<div id="root"></div>', { url: 'https://example.test/' });
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ localStorage: { configurable: true, value: dom.window.localStorage },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of descriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+it('searches all projects until the browser stored a choice', async () => {
+ await render();
+ assert.equal(result.scope, 'all');
+});
+
+it('reads the stored choice and falls back to all projects for an unknown value', async () => {
+ localStorage.setItem(STORAGE_KEY, 'current');
+ await render();
+ assert.equal(result.scope, 'current');
+
+ act(() => root.unmount());
+ localStorage.setItem(STORAGE_KEY, 'legacy');
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+ await render();
+ assert.equal(result.scope, 'all');
+});
+
+it('stores a new choice', async () => {
+ await render();
+ await act(async () => result.setScope('current'));
+ assert.equal(result.scope, 'current');
+ assert.equal(localStorage.getItem(STORAGE_KEY), 'current');
+});
+
+it('still switches when browser storage is unavailable', async () => {
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ get() {
+ throw new Error('SecurityError');
+ },
+ });
+ await render();
+ assert.equal(result.scope, 'all');
+ await act(async () => result.setScope('current'));
+ assert.equal(result.scope, 'current');
+});
diff --git a/apps/web/src/components/layout/hooks/usePaletteSearchScope.ts b/apps/web/src/components/layout/hooks/usePaletteSearchScope.ts
new file mode 100644
index 00000000..c2638ccd
--- /dev/null
+++ b/apps/web/src/components/layout/hooks/usePaletteSearchScope.ts
@@ -0,0 +1,31 @@
+import { useEffect, useState } from 'react';
+
+export type PaletteSearchScope = 'current' | 'all';
+
+const STORAGE_KEY = 'command-palette:search-scope';
+
+// Which projects the palette searches while a project is open, remembered for this
+// browser. Read in an effect: the initializer also runs in the server render, where
+// there is no localStorage.
+export function usePaletteSearchScope() {
+ const [scope, setStoredScope] = useState<PaletteSearchScope>('all');
+
+ useEffect(() => {
+ try {
+ setStoredScope(localStorage.getItem(STORAGE_KEY) === 'current' ? 'current' : 'all');
+ } catch {
+ setStoredScope('all');
+ }
+ }, []);
+
+ function setScope(next: PaletteSearchScope) {
+ setStoredScope(next);
+ try {
+ localStorage.setItem(STORAGE_KEY, next);
+ } catch {
+ // The choice still applies when browser storage is unavailable.
+ }
+ }
+
+ return { scope, setScope };
+}
diff --git a/apps/web/src/lib/api/endpoints/issues.ts b/apps/web/src/lib/api/endpoints/issues.ts
index 68be9864..065e2968 100644
--- a/apps/web/src/lib/api/endpoints/issues.ts
+++ b/apps/web/src/lib/api/endpoints/issues.ts
@@ -97,6 +97,14 @@ export interface IssueSearchHit {
archived: boolean;
}
+export interface CrossProjectIssueHit extends IssueSearchHit {
+ projectId: number;
+ projectRef: string;
+ projectKey: string;
+ projectName: string;
+ teamName: string;
+}
+
export interface IssueFieldValue {
fieldId: number;
name: string;
@@ -378,6 +386,19 @@ export const searchIssues = (projectKey: string, params: { q?: string; limit?: n
return request<IssueSearchHit[]>(`/projects/${projectKey}/issues/search?${qs.toString()}`);
};
+export const searchAllIssues = (params: {
+ q: string;
+ limit?: number;
+ perProjectLimit?: number;
+ excludeProjectId?: number;
+}) => {
+ const qs = new URLSearchParams({ q: params.q });
+ if (params.limit != null) qs.set('limit', String(params.limit));
+ if (params.perProjectLimit != null) qs.set('perProjectLimit', String(params.perProjectLimit));
+ if (params.excludeProjectId != null) qs.set('excludeProjectId', String(params.excludeProjectId));
+ return request<CrossProjectIssueHit[]>(`/issues/search?${qs.toString()}`);
+};
+
// Relations between issues. The relation reads from the issue in the path: it
// blocks / relates to / duplicates targetIssueId. Both ends show it.
export const linkIssues = (issueId: number, targetIssueId: number, kind: IssueLinkInputKind) =>
diff --git a/apps/web/src/services/issues.service.test.tsx b/apps/web/src/services/issues.service.test.tsx
new file mode 100644
index 00000000..e19cdabb
--- /dev/null
+++ b/apps/web/src/services/issues.service.test.tsx
@@ -0,0 +1,175 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { JSDOM } from 'jsdom';
+import { useOtherProjectIssueSearch } from './issues.service';
+import { qk } from './queryKeys';
+import type { CrossProjectIssueHit } from '@/lib/api/endpoints/issues';
+
+let root: Root;
+let dom: JSDOM;
+let client: QueryClient;
+let result: ReturnType<typeof useOtherProjectIssueSearch>;
+let requests: URL[];
+let held: Promise<void> | null;
+let descriptors: Map<string, PropertyDescriptor | undefined>;
+
+function hit(id: number, projectKey: string): CrossProjectIssueHit {
+ return {
+ id,
+ sequenceNumber: id,
+ identifier: `${projectKey}-${id}`,
+ title: 'Launch',
+ columnId: 1,
+ typeId: null,
+ initiativeId: null,
+ cycleId: null,
+ parentId: null,
+ assigneeUserId: null,
+ delegateUserId: null,
+ priority: null,
+ dueDate: null,
+ labelIds: [],
+ archived: false,
+ projectId: projectKey === 'MKT' ? 1 : 2,
+ projectRef: `eng.${projectKey}`,
+ projectKey,
+ projectName: projectKey,
+ teamName: 'Engineering',
+ };
+}
+
+function Harness({
+ q,
+ current,
+ enabled,
+}: {
+ q: string;
+ current: { key: string | null; id: number | null };
+ enabled: boolean;
+}) {
+ result = useOtherProjectIssueSearch(q, current, { enabled });
+ return null;
+}
+
+async function render(
+ current: { key: string | null; id: number | null },
+ q = 'launch',
+ enabled = true,
+) {
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <Harness q={q} current={current} enabled={enabled} />
+ </QueryClientProvider>,
+ );
+ });
+ // Let the request resolve and its result render.
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 20)));
+}
+
+beforeEach(async () => {
+ descriptors = new Map(
+ ['window', 'document', 'navigator', 'IS_REACT_ACT_ENVIRONMENT', 'fetch'].map((name) => [
+ name,
+ Object.getOwnPropertyDescriptor(globalThis, name),
+ ]),
+ );
+ dom = new JSDOM('<div id="root"></div>');
+ requests = [];
+ held = null;
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ fetch: {
+ configurable: true,
+ value: async (input: string | URL) => {
+ requests.push(new URL(String(input)));
+ await held;
+ return Response.json([hit(3, 'OPS')]);
+ },
+ },
+ });
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+});
+
+afterEach(async () => {
+ act(() => root.unmount());
+ client.clear();
+ dom.window.close();
+ for (const [name, descriptor] of descriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+it('waits for the current project to load before searching the other projects', async () => {
+ // A search from a page with no project, which includes MKT's issues.
+ client.setQueryData(qk.issueSearchAll('launch', null), [hit(1, 'MKT'), hit(3, 'OPS')]);
+
+ await render({ key: 'eng.MKT', id: null });
+ assert.equal(result.hits.length, 0);
+ assert.equal(requests.length, 0);
+
+ let release!: () => void;
+ held = new Promise((resolve) => (release = resolve));
+ await render({ key: 'eng.MKT', id: 1 });
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0]!.searchParams.get('excludeProjectId'), '1');
+ assert.equal(result.fetching, true);
+ assert.equal(result.hits.length, 0);
+
+ await act(async () => {
+ release();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ assert.deepEqual(
+ result.hits.map((h) => h.identifier),
+ ['OPS-3'],
+ );
+});
+
+it('searches every project when no project is open', async () => {
+ await render({ key: null, id: null });
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0]!.searchParams.has('excludeProjectId'), false);
+ assert.deepEqual(
+ result.hits.map((h) => h.identifier),
+ ['OPS-3'],
+ );
+});
+
+it('keeps the previous hits while a changed term is searched', async () => {
+ await render({ key: 'eng.MKT', id: 1 });
+ held = new Promise(() => {});
+ await render({ key: 'eng.MKT', id: 1 }, 'launc');
+ assert.equal(result.fetching, true);
+ assert.deepEqual(
+ result.hits.map((h) => h.identifier),
+ ['OPS-3'],
+ );
+});
+
+it('shows no cached hits while disabled, as when the search is narrowed to the project', async () => {
+ client.setQueryData(qk.issueSearchAll('launch', 1), [hit(3, 'OPS')]);
+
+ await render({ key: 'eng.MKT', id: 1 }, 'launch', false);
+ assert.equal(requests.length, 0);
+ assert.equal(result.hits.length, 0);
+});
+
+it('stops reporting a search in flight once disabled', async () => {
+ held = new Promise(() => {});
+ await render({ key: 'eng.MKT', id: 1 });
+ assert.equal(result.fetching, true);
+
+ await render({ key: 'eng.MKT', id: 1 }, 'launch', false);
+ assert.equal(result.fetching, false);
+ assert.equal(result.hits.length, 0);
+});
diff --git a/apps/web/src/services/issues.service.ts b/apps/web/src/services/issues.service.ts
index ae502c94..cbfb99f5 100644
--- a/apps/web/src/services/issues.service.ts
+++ b/apps/web/src/services/issues.service.ts
@@ -28,6 +28,7 @@ import {
listIssueCycles,
getIssueBySeq,
searchIssues,
+ searchAllIssues,
updateIssue,
deleteIssue,
moveIssue,
@@ -169,6 +170,38 @@ export function useIssueSearchQuery(
});
}
+// The palette's search in every project the user can read. It leaves out the
+// current project, whose own group lists its matches above.
+// While that project is still loading its id is unknown, so nothing is searched or
+// shown: a search without the id, or one cached from a page with no project, would
+// list its issues here too. Disabled, it shows no cached hits either.
+export function useOtherProjectIssueSearch(
+ q: string,
+ current: { key: string | null; id: number | null },
+ opts: { enabled: boolean },
+) {
+ const term = q.trim();
+ const active = opts.enabled && (current.key === null || current.id !== null);
+ const search = useQuery({
+ queryKey: qk.issueSearchAll(term, current.id),
+ queryFn: () =>
+ searchAllIssues({
+ q: term,
+ limit: 50,
+ perProjectLimit: 5,
+ excludeProjectId: current.id ?? undefined,
+ }),
+ enabled: active && term.length > 0,
+ // Only the term changed: the previous hits leave out the same project.
+ placeholderData: (previous, previousQuery) =>
+ previousQuery?.queryKey[2] === current.id ? previous : undefined,
+ });
+ return {
+ hits: active ? (search.data ?? []) : [],
+ fetching: active && search.isFetching,
+ };
+}
+
// Updating an issue (drag/drop move, or an inline field edit). When `projectKey` is
// given the project detail is patched optimistically so the change shows before the
// request resolves, then reconciled on settle. Issue detail, comments and
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 99bf8782..ac77b837 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -66,6 +66,8 @@ export const qk = {
archivedIssues: (projectKey: string) => ['archivedIssues', projectKey] as const,
// Command-palette issue search, scoped to a project and the search term.
issueSearch: (projectKey: string, q: string) => ['issueSearch', projectKey, q] as const,
+ issueSearchAll: (q: string, excludeProjectId: number | null) =>
+ ['issueSearchAll', q, excludeProjectId] as const,
// The project's auto-archive thresholds and subtask automations (the
// Configuration settings section).
autoArchive: (projectKey: string) => ['autoArchive', projectKey] as const,