⭐️⭐️⭐️ 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.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
improvement: page and search the team roles and projects lists (#339)
Croff39f7cbf3361b
diff --git a/apps/api/src/__tests__/helpers/roles.ts b/apps/api/src/__tests__/helpers/roles.tsindex 8890cafd..926d0379 100644--- a/apps/api/src/__tests__/helpers/roles.ts+++ b/apps/api/src/__tests__/helpers/roles.ts@@ -7,9 +7,10 @@ export async function teamIdOf(api: Api, projectKey: string): Promise<number> {return projects.data!.find((p) => p.key === projectKey)!.teamId;}-// The roles a project assigns from, through the team that owns it.+// The roles a project assigns from, through the team that owns it. Read whole, the+// way the pickers do.export async function listProjectRoles(api: Api, projectKey: string) {- return api.teams({ teamId: await teamIdOf(api, projectKey) }).roles.get();+ return api.teams({ teamId: await teamIdOf(api, projectKey) }).roles.options.get();}// Creates a role for a project through the team that owns it.diff --git a/apps/api/src/modules/roles/__tests__/integration/roles.test.ts b/apps/api/src/modules/roles/__tests__/integration/roles.test.tsindex d575935c..da5a0f32 100644--- a/apps/api/src/modules/roles/__tests__/integration/roles.test.ts+++ b/apps/api/src/modules/roles/__tests__/integration/roles.test.ts@@ -87,13 +87,13 @@ describe('roles', () => {const res = await owner.api.teams({ teamId: owner.teamId }).roles.get();expect(res.status).toBe(200);- expect(res.data).toHaveLength(1);- expect(res.data?.[0]).toMatchObject({ name: 'Member', isDefault: true });+ expect(res.data?.items).toHaveLength(1);+ expect(res.data?.items[0]).toMatchObject({ name: 'Member', isDefault: true });// The default role carries a normalized matrix: full work_items, the member// list readable, no member management.- expect(res.data?.[0].permissions.work_items.create).toBe(true);- expect(res.data?.[0].permissions.members_manage.read).toBe(true);- expect(res.data?.[0].permissions.members_manage.create).toBe(false);+ expect(res.data?.items[0].permissions.work_items.create).toBe(true);+ expect(res.data?.items[0].permissions.members_manage.read).toBe(true);+ expect(res.data?.items[0].permissions.members_manage.create).toBe(false);});it('lists roles ordered by id, default first', async () => {@@ -110,7 +110,37 @@ describe('roles', () => {const res = await owner.api.teams({ teamId: owner.teamId }).roles.get();expect(res.status).toBe(200);- expect(res.data?.map((r) => r.name)).toEqual(['Member', 'Editor', 'Viewer']);+ expect(res.data?.items.map((r) => r.name)).toEqual(['Member', 'Editor', 'Viewer']);+ });++ it('pages the list, counting every role of the team', async () => {+ const owner = await setupOwner();+ await owner.api+ .teams({ teamId: owner.teamId })+ .roles.post({ name: 'Editor', permissions: {} });++ const res = await owner.api+ .teams({ teamId: owner.teamId })+ .roles.get({ query: { page: 2, pageSize: 1 } });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ total: 2, page: 2, pageSize: 1 });+ expect(res.data?.items.map((r) => r.name)).toEqual(['Editor']);+ });++ it('searches the roles by name', async () => {+ const owner = await setupOwner();+ await owner.api+ .teams({ teamId: owner.teamId })+ .roles.post({ name: 'Editor', permissions: {} });++ const res = await owner.api+ .teams({ teamId: owner.teamId })+ .roles.get({ query: { search: 'edit' } });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ total: 1 });+ expect(res.data?.items.map((r) => r.name)).toEqual(['Editor']);});it('is readable by a plain member of the team', async () => {@@ -120,7 +150,7 @@ describe('roles', () => {const res = await member.api.teams({ teamId: owner.teamId }).roles.get();expect(res.status).toBe(200);- expect(res.data?.map((r) => r.name)).toEqual(['Member']);+ expect(res.data?.items.map((r) => r.name)).toEqual(['Member']);});it('denies someone outside the team with 404', async () => {@@ -139,6 +169,29 @@ describe('roles', () => {});});+ describe('options — GET /teams/:teamId/roles/options', () => {+ it('answers with every role of the team, matrices included', async () => {+ const owner = await setupOwner();+ await owner.api+ .teams({ teamId: owner.teamId })+ .roles.post({ name: 'Editor', permissions: { work_items: { edit: true } } });++ const res = await owner.api.teams({ teamId: owner.teamId }).roles.options.get();++ expect(res.status).toBe(200);+ expect(res.data?.map((r) => r.name)).toEqual(['Member', 'Editor']);+ expect(res.data?.[1].permissions.work_items.edit).toBe(true);+ });++ it('denies someone outside the team with 404', async () => {+ const owner = await setupOwner();+ const outsider = authedApi((await signUpTestUser()).cookie);++ const res = await outsider.teams({ teamId: owner.teamId }).roles.options.get();+ expect(res.status).toBe(404);+ });+ });+describe('create — POST /teams/:teamId/roles', () => {it('creates a non-default role, sanitizing the permission matrix', async () => {const owner = await setupOwner();@@ -272,7 +325,7 @@ describe('roles', () => {it('can rename the default role', async () => {const owner = await setupOwner();const list = await owner.api.teams({ teamId: owner.teamId }).roles.get();- const defaultId = list.data!.find((r) => r.isDefault)!.id;+ const defaultId = list.data!.items.find((r) => r.isDefault)!.id;const res = await owner.api.teams({ teamId: owner.teamId })@@ -423,7 +476,7 @@ describe('roles', () => {expect(res.status).toBe(204);const list = await owner.api.teams({ teamId: owner.teamId }).roles.get();- expect(list.data?.map((r) => r.id)).not.toContain(roleId);+ expect(list.data?.items.map((r) => r.id)).not.toContain(roleId);});// Puts a fresh member of MKT on the role, so it counts as in use.@@ -445,7 +498,7 @@ describe('roles', () => {expect(res.status).toBe(400);const after = await owner.api.teams({ teamId: owner.teamId }).roles.get();- expect(after.data?.map((r) => r.id)).toContain(roleId);+ expect(after.data?.items.map((r) => r.id)).toContain(roleId);});it('moves the members on the role to the target role and deletes it', async () => {@@ -496,7 +549,7 @@ describe('roles', () => {it('returns 400 when deleting the default role', async () => {const owner = await setupOwner();const list = await owner.api.teams({ teamId: owner.teamId }).roles.get();- const defaultId = list.data!.find((r) => r.isDefault)!.id;+ const defaultId = list.data!.items.find((r) => r.isDefault)!.id;const res = await owner.api.teams({ teamId: owner.teamId })@@ -506,7 +559,7 @@ describe('roles', () => {// The default role is still there.const after = await owner.api.teams({ teamId: owner.teamId }).roles.get();- expect(after.data?.map((r) => r.id)).toContain(defaultId);+ expect(after.data?.items.map((r) => r.id)).toContain(defaultId);});it('returns 404 for a role that does not exist', async () => {diff --git a/apps/api/src/modules/roles/index.ts b/apps/api/src/modules/roles/index.tsindex 4c6c74cc..45e42958 100644--- a/apps/api/src/modules/roles/index.ts+++ b/apps/api/src/modules/roles/index.ts@@ -2,11 +2,13 @@ import { Elysia, t } from 'elysia';import { mcpTool } from '#mcp/generate';import { noContent } from '#shared/http';import { guards } from '#shared/guards';+import { paginate } from '#shared/pagination';import { HttpError, rethrowDuplicate } from '#shared/lib';import { PERMISSION_RESOURCES, PERMISSION_ACTIONS, resourceActions } from '#shared/permissions';import { accessErrors, commonErrors, errors } from '#shared/responses';import {listRoles,+ listRolesPage,getRole,getRoleUsage,isRoleInUse,@@ -16,10 +18,12 @@ import {} from './service';import {PermissionCatalogResponse,+ RolePageResponse,RoleResponse,RoleUsageResponse,createRoleBody,deleteRoleQuery,+ roleListQuery,roleParams,teamParams,updateRoleBody,@@ -54,14 +58,42 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']},)- // The roles of a team, read by any of its members: the projects assign from this- // one list, so it is what a member list, an add-member dialog and an agent's role- // picker all name their options from.- .get('/teams/:teamId/roles', ({ membership }) => listRoles(membership.teamId), {+ // One page of the roles of a team, read by any of its members.+ .get(+ '/teams/:teamId/roles',+ ({ membership, query }) =>+ paginate(query, (window) =>+ listRolesPage(membership.teamId, { search: query.search, ...window }),+ ),+ {+ params: teamParams,+ query: roleListQuery,+ teamMember: true,+ response: { 200: RolePageResponse, ...accessErrors },+ detail: {+ summary: "List a team's roles",+ description:+ 'One page of the roles a team offers, oldest first. `search` matches the name. ' ++ 'Use list_role_options to read every one of them.',+ ...mcpTool('list_roles'),+ },+ },+ )++ // The projects assign from this one list, so a member list, an add-member dialog+ // and an agent's role picker all name their options from it. The matrices come+ // along: the roles are exported to the clipboard from here as well.+ .get('/teams/:teamId/roles/options', ({ membership }) => listRoles(membership.teamId), {params: teamParams,teamMember: true,response: { 200: t.Array(RoleResponse), ...accessErrors },- detail: { summary: "List a team's roles", ...mcpTool('list_roles') },+ detail: {+ summary: "List a team's role options",+ description:+ 'Every role of the team, with its permission matrix, for the pickers that assign one. ' ++ 'Use list_roles to read them a page at a time.',+ ...mcpTool('list_role_options'),+ },}).post(diff --git a/apps/api/src/modules/roles/model.ts b/apps/api/src/modules/roles/model.tsindex 7d9f4356..b3dc7de4 100644--- a/apps/api/src/modules/roles/model.ts+++ b/apps/api/src/modules/roles/model.ts@@ -1,4 +1,5 @@import { t } from 'elysia';+import { pageQueryFields, pageResponse } from '#shared/pagination';import { PermissionMatrixSchema } from '#shared/permissions';export const teamParams = t.Object({ teamId: t.Numeric() });@@ -33,6 +34,13 @@ export const RoleResponse = t.Object({createdAt: t.String(),});+export const roleListQuery = t.Object({+ search: t.Optional(t.String({ description: 'Matches the name.' })),+ ...pageQueryFields,+});++export const RolePageResponse = pageResponse(RoleResponse);+export const RoleUsageResponse = t.Object({members: t.Number(),agents: t.Number(),diff --git a/apps/api/src/modules/roles/service.ts b/apps/api/src/modules/roles/service.tsindex df51c8f0..7148144f 100644--- a/apps/api/src/modules/roles/service.ts+++ b/apps/api/src/modules/roles/service.ts@@ -1,5 +1,5 @@import { db, teamRole, projectMember, aiAgent, teamInvite, scimGroupMapping } from '@repo/db';-import { and, asc, count, eq, isNull } from 'drizzle-orm';+import { and, asc, count, eq, ilike, isNull, sql } from 'drizzle-orm';import { iso } from '#shared/lib';import { normalizePermissions, type Permissions } from '#shared/permissions';@@ -26,6 +26,40 @@ function mapRole(row: typeof teamRole.$inferSelect): RoleRow {};}+export interface RolePage {+ items: RoleRow[];+ total: number;+}++// One page of the team's roles, oldest first, with how many match in all. The search+// matches the name.+export async function listRolesPage(+ teamId: number,+ options: { search?: string; limit: number; offset: number },+): Promise<RolePage> {+ const term = options.search?.trim();+ const where = and(+ eq(teamRole.teamId, teamId),+ term ? ilike(teamRole.name, `%${term}%`) : undefined,+ );+ const [rows, counted] = await Promise.all([+ db+ .select()+ .from(teamRole)+ .where(where)+ .orderBy(asc(teamRole.id))+ .limit(options.limit)+ .offset(options.offset),+ db+ .select({ count: sql<number>`count(*)::int` })+ .from(teamRole)+ .where(where),+ ]);+ return { items: rows.map(mapRole), total: counted[0]?.count ?? 0 };+}++// Every role of the team. Read by the pickers that assign one, and by the clipboard+// export, which carries the matrices of all of them.export async function listRoles(teamId: number): Promise<RoleRow[]> {const rows = await db.select()diff --git a/apps/api/src/modules/teams/__tests__/integration/teams.test.ts b/apps/api/src/modules/teams/__tests__/integration/teams.test.tsindex 5a8f9430..20a5b357 100644--- a/apps/api/src/modules/teams/__tests__/integration/teams.test.ts+++ b/apps/api/src/modules/teams/__tests__/integration/teams.test.ts@@ -156,7 +156,7 @@ describe('teams', () => {expect(members.data?.items).toMatchObject([{ email: user.email, role: 'owner' }]);const projects = await api.teams({ teamId }).projects.get();- expect(projects.data).toMatchObject([+ expect(projects.data?.items).toMatchObject([{ key: 'MKT', name: 'Marketing', memberCount: 1, isMember: true },]);});@@ -207,14 +207,61 @@ describe('teams', () => {.members.post({ userId: member.user.userId, role: 'member' });const mine = await member.api.teams({ teamId }).projects.get();- expect(mine.data?.map((p) => p.key)).toEqual(['MKT']);+ expect(mine.data?.items.map((p) => p.key)).toEqual(['MKT']);expect((await member.api.teams.get()).data?.[0]).toMatchObject({ projectCount: 1 });const all = await manager.api.teams({ teamId }).projects.get();- expect(all.data?.map((p) => p.key)).toEqual(['MKT', 'OPS']);+ expect(all.data?.items.map((p) => p.key)).toEqual(['MKT', 'OPS']);expect((await manager.api.teams.get()).data?.[0]).toMatchObject({ projectCount: 2 });});+ it('pages the project list, counting every project the caller reads', async () => {+ const { api } = await signUpClient();+ const teamId = (await api.teams.get()).data![0].id;+ await api.teams({ teamId }).projects.post({ key: 'MKT', name: 'Marketing' });+ await api.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });++ const res = await api.teams({ teamId }).projects.get({ query: { page: 2, pageSize: 1 } });++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ total: 2, page: 2, pageSize: 1 });+ expect(res.data?.items.map((p) => p.key)).toEqual(['OPS']);+ });++ it('searches the projects by key and by name', async () => {+ const { api } = await signUpClient();+ const teamId = (await api.teams.get()).data![0].id;+ await api.teams({ teamId }).projects.post({ key: 'MKT', name: 'Marketing' });+ await api.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });++ const byName = await api.teams({ teamId }).projects.get({ query: { search: 'market' } });+ expect(byName.data).toMatchObject({ total: 1 });+ expect(byName.data?.items.map((p) => p.key)).toEqual(['MKT']);++ const byKey = await api.teams({ teamId }).projects.get({ query: { search: 'ops' } });+ expect(byKey.data?.items.map((p) => p.key)).toEqual(['OPS']);+ });++ it('answers the options route with every project the caller reads', async () => {+ const { api } = await signUpClient();+ const teamId = (await api.teams.get()).data![0].id;+ await api.teams({ teamId }).projects.post({ key: 'MKT', name: 'Marketing' });+ await api.teams({ teamId }).projects.post({ key: 'OPS', name: 'Operations' });+ const member = await addTeamMember({ api }, teamId);+ await api+ .projects({ projectKey: 'MKT' })+ .members.post({ userId: member.user.userId, role: 'member' });++ const all = await api.teams({ teamId }).projects.options.get();+ expect(all.data).toMatchObject([+ { key: 'MKT', mcpEnabled: true },+ { key: 'OPS', mcpEnabled: true },+ ]);++ const mine = await member.api.teams({ teamId }).projects.options.get();+ expect(mine.data?.map((p) => p.key)).toEqual(['MKT']);+ });+it('hides a project detail from a member who did not join it', async () => {const { api } = await signUpClient();const teamId = (await api.teams.get()).data![0].id;@@ -447,7 +494,7 @@ describe('teams', () => {expect(created.data).toMatchObject({ key: 'MKT', teamId, teamName: user.username });const projects = await api.teams({ teamId }).projects.get();- expect(projects.data).toMatchObject([{ key: 'MKT', isMember: true }]);+ expect(projects.data?.items).toMatchObject([{ key: 'MKT', isMember: true }]);});it('rejects a duplicate project key', async () => {@@ -468,9 +515,9 @@ describe('teams', () => {.teams({ teamId: otherTeamId }).projects.post({ key: 'MKT', name: 'Marketing' });expect(created.status).toBe(404);- expect((await other.api.teams({ teamId: otherTeamId }).projects.get()).data).toHaveLength(- 0,- );+ expect(+ (await other.api.teams({ teamId: otherTeamId }).projects.get()).data?.items,+ ).toHaveLength(0);});});@@ -522,7 +569,7 @@ describe('teams', () => {expect(updated.data).toMatchObject({ key: 'MKT', name: 'Growth' });const projects = await api.teams({ teamId }).projects.get();- expect(projects.data).toMatchObject([+ expect(projects.data?.items).toMatchObject([{ key: 'MKT', name: 'Growth', description: 'What we ship' },]);});@@ -569,7 +616,7 @@ describe('teams', () => {.projects({ projectId: project.data!.id }).delete();expect(deleted.status).toBe(204);- expect((await api.teams({ teamId }).projects.get()).data).toHaveLength(0);+ expect((await api.teams({ teamId }).projects.get()).data?.items).toHaveLength(0);expect((await api.projects.get()).data).toHaveLength(0);});@@ -600,7 +647,7 @@ describe('teams', () => {const project = (await api.projects.post({ key: 'MKT', name: 'Marketing' })).data!;expect((await api.teams.get()).data?.[0]).toMatchObject({ mcpEnabled: true });- expect((await api.teams({ teamId }).projects.get()).data).toMatchObject([+ expect((await api.teams({ teamId }).projects.get()).data?.items).toMatchObject([{ id: project.id, mcpEnabled: true },]);});@@ -644,9 +691,9 @@ describe('teams', () => {// The other team's own project keeps its reach.const otherTeamId = (await other.api.teams.get()).data![0].id;- expect((await other.api.teams({ teamId: otherTeamId }).projects.get()).data).toMatchObject([- { id: foreign.id, mcpEnabled: true },- ]);+ expect(+ (await other.api.teams({ teamId: otherTeamId }).projects.get()).data?.items,+ ).toMatchObject([{ id: foreign.id, mcpEnabled: true }]);});it('lets a manager write the settings', async () => {@@ -669,7 +716,7 @@ describe('teams', () => {await owner.api.projects.post({ key: 'MKT', name: 'Marketing' });const member = await addProjectMember(owner.api, 'MKT');- expect((await member.teams({ teamId }).projects.get()).data).toMatchObject([+ expect((await member.teams({ teamId }).projects.get()).data?.items).toMatchObject([{ key: 'MKT', mcpEnabled: true },]);expect((await member.teams({ teamId }).mcp.patch({ enabled: false })).status).toBe(403);diff --git a/apps/api/src/modules/teams/index.ts b/apps/api/src/modules/teams/index.tsindex f8a1524a..f320dbeb 100644--- a/apps/api/src/modules/teams/index.ts+++ b/apps/api/src/modules/teams/index.ts@@ -23,12 +23,14 @@ import {TeamMemberPageResponse,TeamProjectDetailResponse,TeamProjectMemberPageResponse,- TeamProjectListResponse,+ TeamProjectOptionListResponse,+ TeamProjectPageResponse,TeamResponse,createTeamBody,setTeamMemberRoleBody,teamMemberParams,teamParams,+ teamProjectListQuery,teamProjectParams,memberListQuery,updateTeamBody,@@ -41,6 +43,7 @@ import {leaveTeam,listTeamMembers,listTeamProjectMembers,+ listTeamProjectOptions,listTeamProjects,listTeams,removeTeamMember,@@ -128,16 +131,40 @@ export const teamRoutes = new Elysia({ name: 'teams', detail: { tags: ['Teams'].get('/teams/:teamId/projects',- ({ membership }) => listTeamProjects(membership.teamId, membership.userId, membership.role),+ ({ membership, query }) =>+ paginate(query, (window) =>+ listTeamProjects(membership.teamId, membership.userId, membership.role, {+ search: query.search,+ ...window,+ }),+ ),{teamMember: true,params: teamParams,- response: { 200: TeamProjectListResponse, ...errors(401, 404) },+ query: teamProjectListQuery,+ response: { 200: TeamProjectPageResponse, ...errors(401, 404) },detail: {summary: 'List team projects',description:- 'The projects a team owns. An owner or a manager sees them all; anyone else only ' +- 'the ones they belong to.',+ 'One page of the projects a team owns, by key. `search` matches the key or the ' ++ 'name. An owner or a manager sees them all; anyone else only the ones they belong to.',+ },+ },+ )++ // Fills the project picker on an agent and the MCP switches, which act on every+ // project of the team rather than on a page of them.+ .get(+ '/teams/:teamId/projects/options',+ ({ membership }) =>+ listTeamProjectOptions(membership.teamId, membership.userId, membership.role),+ {+ teamMember: true,+ params: teamParams,+ response: { 200: TeamProjectOptionListResponse, ...errors(401, 404) },+ detail: {+ summary: 'List team project options',+ description: 'Every project the reader has in the team: id, key, name and MCP reach.',},},)diff --git a/apps/api/src/modules/teams/model.ts b/apps/api/src/modules/teams/model.tsindex 63e7da0c..5e05b6b3 100644--- a/apps/api/src/modules/teams/model.ts+++ b/apps/api/src/modules/teams/model.ts@@ -1,5 +1,5 @@import { t } from 'elysia';-import { pageResponse } from '#shared/pagination';+import { pageQueryFields, pageResponse } from '#shared/pagination';import { PermissionMatrixSchema } from '#shared/permissions';import { StatsDto } from '#modules/analytics/model';@@ -93,7 +93,12 @@ export const TeamMemberPageResponse = pageResponse(}),);-export const TeamProjectListResponse = t.Array(+export const teamProjectListQuery = t.Object({+ search: t.Optional(t.String({ description: 'Matches the key or the name.' })),+ ...pageQueryFields,+});++export const TeamProjectPageResponse = pageResponse(t.Object({id: t.Number(),key: t.String(),@@ -114,6 +119,17 @@ export const TeamProjectListResponse = t.Array(}),);+// Every project the reader has, for the pickers that need them all: the projects an+// agent is attached to, and the MCP switch each project carries.+export const TeamProjectOptionListResponse = t.Array(+ t.Object({+ id: t.Number(),+ key: t.String(),+ name: t.String(),+ mcpEnabled: t.Boolean(),+ }),+);+// One project the team owns: how its issues stand, and where the reader stands in it.export const TeamProjectDetailResponse = t.Object({lastActivityAt: t.Nullable(t.String()),diff --git a/apps/api/src/modules/teams/service.ts b/apps/api/src/modules/teams/service.tsindex 2f426755..98560b5b 100644--- a/apps/api/src/modules/teams/service.ts+++ b/apps/api/src/modules/teams/service.ts@@ -14,7 +14,7 @@ import {teamRole,user,} from '@repo/db';-import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm';+import { and, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';import { HttpError, iso } from '#shared/lib';import { getLimits } from '#shared/limits';import { defaultMemberPermissions, fullPermissions, type Permissions } from '#shared/permissions';@@ -105,6 +105,20 @@ export interface TeamProjectRow {createdAt: string;}+// One page of the team's projects, with how many the caller reads in all.+export interface TeamProjectPage {+ items: TeamProjectRow[];+ total: number;+}++// A project as a picker reads it, plus the MCP reach the team's switches set.+export interface TeamProjectOption {+ id: number;+ key: string;+ name: string;+ mcpEnabled: boolean;+}+// One member of a project the team owns. The access their membership resolves to is// not carried here: it is the matrix of the role they hold, which the reader already// has from the team's roles.@@ -445,14 +459,36 @@ export async function listTeamMembers(};}-// The projects the team owns, with the caller's own access to each. Owners and-// managers see every project of the team; everyone else only the ones they joined.+// The projects of the team a caller reads: owners and managers see every one of them,+// everyone else only the ones they joined. The search matches the key or the name.+function visibleTeamProjects(+ teamId: number,+ userId: string,+ standing: TeamStanding,+ search?: string,+) {+ const term = search?.trim();+ return and(+ eq(project.teamId, teamId),+ runsTeam(standing)+ ? undefined+ : sql`exists (select 1 from ${projectMember} where ${projectMember.projectId} = ${project.id}+ and ${projectMember.userId} = ${userId})`,+ term ? or(ilike(project.key, `%${term}%`), ilike(project.name, `%${term}%`)) : undefined,+ );+}++// One page of the projects the team owns, with the caller's own access to each. The+// window runs in the database, so a team with many projects is never loaded whole;+// the owners are read for the page, not for every project.export async function listTeamProjects(teamId: number,userId: string,standing: TeamStanding,-): Promise<TeamProjectRow[]> {- const [projects, projectOwners] = await Promise.all([+ options: { search?: string; limit: number; offset: number },+): Promise<TeamProjectPage> {+ const where = visibleTeamProjects(teamId, userId, standing, options.search);+ const [projects, counted] = await Promise.all([db.select({id: project.id,@@ -466,23 +502,39 @@ export async function listTeamProjects(}).from(project).leftJoin(projectMember, eq(projectMember.projectId, project.id))- .where(eq(project.teamId, teamId))+ .where(where).groupBy(project.id)- .orderBy(project.key),+ .orderBy(project.key)+ .limit(options.limit)+ .offset(options.offset),db- .select({- projectId: projectMember.projectId,- userId: user.id,- name: user.name,- image: user.image,- })- .from(projectMember)- .innerJoin(project, eq(project.id, projectMember.projectId))- .innerJoin(user, eq(user.id, projectMember.userId))- .where(and(eq(project.teamId, teamId), eq(projectMember.role, 'owner')))- .orderBy(user.name),+ .select({ count: sql<number>`count(*)::int` })+ .from(project)+ .where(where),]);+ const projectOwners = projects.length+ ? await db+ .select({+ projectId: projectMember.projectId,+ userId: user.id,+ name: user.name,+ image: user.image,+ })+ .from(projectMember)+ .innerJoin(user, eq(user.id, projectMember.userId))+ .where(+ and(+ inArray(+ projectMember.projectId,+ projects.map((p) => p.id),+ ),+ eq(projectMember.role, 'owner'),+ ),+ )+ .orderBy(user.name)+ : [];+const ownersByProject = new Map<number, TeamProjectRow['owners']>();for (const o of projectOwners) {const owners = ownersByProject.get(o.projectId) ?? [];@@ -490,19 +542,39 @@ export async function listTeamProjects(ownersByProject.set(o.projectId, owners);}- const visible = runsTeam(standing) ? projects : projects.filter((p) => p.isMember);-- return visible.map((p) => ({- id: p.id,- key: p.key,- name: p.name,- description: p.description,- mcpEnabled: p.mcpEnabled,- memberCount: p.memberCount,- owners: ownersByProject.get(p.id) ?? [],- isMember: p.isMember ?? false,- createdAt: iso(p.createdAt),- }));+ return {+ items: projects.map((p) => ({+ id: p.id,+ key: p.key,+ name: p.name,+ description: p.description,+ mcpEnabled: p.mcpEnabled,+ memberCount: p.memberCount,+ owners: ownersByProject.get(p.id) ?? [],+ isMember: p.isMember ?? false,+ createdAt: iso(p.createdAt),+ })),+ total: counted[0]?.count ?? 0,+ };+}++// Every project the caller reads, as id, key, name and MCP reach: the picker on an+// agent and the team's MCP switches, which need them all rather than a page.+export async function listTeamProjectOptions(+ teamId: number,+ userId: string,+ standing: TeamStanding,+): Promise<TeamProjectOption[]> {+ return db+ .select({+ id: project.id,+ key: project.key,+ name: project.name,+ mcpEnabled: project.mcpEnabled,+ })+ .from(project)+ .where(visibleTeamProjects(teamId, userId, standing))+ .orderBy(project.key);}// When the project's issue feed last moved. Read as the newest row rather than adiff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.jsonindex 6ecff313..64c36f6b 100644--- a/apps/web/messages/ar/teams.json+++ b/apps/web/messages/ar/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "يمكن لمالك الفريق أو مديره فقط إدارة الأدوار.","empty": "مفيش أدوار لسه. اعمل دور عشان تدّي صلاحيات محدودة.",+ "search": "البحث عن الأدوار",+ "noMatches": "لا توجد أدوار تطابق “{query}”.","default": "افتراضي","editAction": "تعديل الدور","deleteAction": "حذف الدور",@@ -164,6 +166,8 @@"created": "أُنشئ في {date}","newProject": "مشروع جديد","noProjects": "لا توجد مشاريع في هذا الفريق بعد.",+ "searchProjects": "البحث عن المشاريع",+ "noProjectsMatch": "لا توجد مشاريع تطابق “{query}”.","projectMembers": "أعضاء المشروع","owners": "المالكون: {names}","openProject": "فتح المشروع",diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.jsonindex efa18ca3..bc594233 100644--- a/apps/web/messages/en/teams.json+++ b/apps/web/messages/en/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "Only a team owner or manager can manage roles.","empty": "No roles yet. Create one to grant scoped access.",+ "search": "Search roles",+ "noMatches": "No role matches “{query}”.","default": "Default","editAction": "Edit role","deleteAction": "Delete role",@@ -164,6 +166,8 @@"created": "Created {date}","newProject": "New project","noProjects": "This team has no projects yet.",+ "searchProjects": "Search projects",+ "noProjectsMatch": "No project matches “{query}”.","projectMembers": "Project members","owners": "Owners: {names}","openProject": "Open project",diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.jsonindex 496478f0..6b675788 100644--- a/apps/web/messages/fr/teams.json+++ b/apps/web/messages/fr/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "Seul un propriétaire ou un responsable de l'équipe peut gérer les rôles.","empty": "Aucun rôle pour l'instant. Créez-en un pour accorder un accès restreint.",+ "search": "Rechercher des rôles",+ "noMatches": "Aucun rôle ne correspond à « {query} ».","default": "Par défaut","editAction": "Modifier le rôle","deleteAction": "Supprimer le rôle",@@ -164,6 +166,8 @@"created": "Créé {date}","newProject": "Nouveau projet","noProjects": "Cette équipe n'a encore aucun projet.",+ "searchProjects": "Rechercher des projets",+ "noProjectsMatch": "Aucun projet ne correspond à « {query} ».","projectMembers": "Membres du projet","owners": "Propriétaires : {names}","openProject": "Ouvrir le projet",diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.jsonindex b21f96e3..6fbb60ab 100644--- a/apps/web/messages/pt-BR/teams.json+++ b/apps/web/messages/pt-BR/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "Só um dono ou gerente do time pode gerenciar funções.","empty": "Nenhuma função ainda. Crie uma para conceder acesso com escopo.",+ "search": "Buscar funções",+ "noMatches": "Nenhuma função corresponde a “{query}”.","default": "Padrão","editAction": "Editar função","deleteAction": "Excluir função",@@ -164,6 +166,8 @@"created": "Criado em {date}","newProject": "Novo projeto","noProjects": "Este time ainda não tem projetos.",+ "searchProjects": "Buscar projetos",+ "noProjectsMatch": "Nenhum projeto corresponde a “{query}”.","projectMembers": "Membros do projeto","owners": "Donos: {names}","openProject": "Abrir projeto",diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.jsonindex ed19eb26..1a9c8402 100644--- a/apps/web/messages/ru/teams.json+++ b/apps/web/messages/ru/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "Ролями управляют только владелец или менеджер команды.","empty": "Ролей пока нет. Создайте роль, чтобы выдать ограниченный доступ.",+ "search": "Поиск ролей",+ "noMatches": "Нет ролей по запросу «{query}».","default": "По умолчанию","editAction": "Редактировать роль","deleteAction": "Удалить роль",@@ -164,6 +166,8 @@"created": "Создан {date}","newProject": "Новый проект","noProjects": "У этой команды пока нет проектов.",+ "searchProjects": "Поиск проектов",+ "noProjectsMatch": "Нет проектов по запросу «{query}».","projectMembers": "Участники проекта","owners": "Владельцы: {names}","openProject": "Открыть проект",diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.jsonindex 6a98501c..a5a633d7 100644--- a/apps/web/messages/uk/teams.json+++ b/apps/web/messages/uk/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "Ролями керують лише власник або менеджер команди.","empty": "Ролей поки немає. Створіть роль, щоб надати обмежений доступ.",+ "search": "Пошук ролей",+ "noMatches": "Немає ролей за запитом «{query}».","default": "За замовчуванням","editAction": "Редагувати роль","deleteAction": "Видалити роль",@@ -164,6 +166,8 @@"created": "Створено {date}","newProject": "Новий проєкт","noProjects": "Ця команда ще не має проєктів.",+ "searchProjects": "Пошук проєктів",+ "noProjectsMatch": "Немає проєктів за запитом «{query}».","projectMembers": "Учасники проєкту","owners": "Власники: {names}","openProject": "Відкрити проєкт",diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.jsonindex 51376bc6..153d1d92 100644--- a/apps/web/messages/zh-CN/teams.json+++ b/apps/web/messages/zh-CN/teams.json@@ -108,6 +108,8 @@"roles": {"ownerOnly": "只有团队所有者或管理者可以管理角色。","empty": "暂无角色。创建一个角色以授予有限访问权限。",+ "search": "搜索角色",+ "noMatches": "没有与“{query}”匹配的角色。","default": "默认","editAction": "编辑角色","deleteAction": "删除角色",@@ -164,6 +166,8 @@"created": "创建于 {date}","newProject": "新建项目","noProjects": "该团队还没有项目。",+ "searchProjects": "搜索项目",+ "noProjectsMatch": "没有与“{query}”匹配的项目。","projectMembers": "项目成员","owners": "所有者:{names}","openProject": "打开项目",diff --git a/apps/web/src/features/members/components/members/MemberAddDialog.tsx b/apps/web/src/features/members/components/members/MemberAddDialog.tsxindex 2478e08a..1ebc1105 100644--- a/apps/web/src/features/members/components/members/MemberAddDialog.tsx+++ b/apps/web/src/features/members/components/members/MemberAddDialog.tsx@@ -19,7 +19,7 @@ import {useInvitesQuery,useMemberCandidatesQuery,} from '@/services/members.service';-import { useTeamRolesQuery } from '@/services/roles.service';+import { useTeamRoleOptionsQuery } from '@/services/roles.service';import MemberPicker, { type MemberOption } from './MemberPicker';// The message for each refusal the API can answer with; any other error falls back@@ -72,7 +72,7 @@ export default function MemberAddDialog({const [roleValue, setRoleValue] = useState('');const [refusal, setRefusal] = useState<string | null>(null);const candidatesQuery = useMemberCandidatesQuery(projectKey, canAdd);- const rolesQuery = useTeamRolesQuery(teamId);+ const rolesQuery = useTeamRoleOptionsQuery(teamId);const addMember = useAddMember(projectKey);const createInvite = useCreateInvite(projectKey);const invitesQuery = useInvitesQuery(projectKey, canInvite && canReadInvites);diff --git a/apps/web/src/features/members/components/members/MembersList.tsx b/apps/web/src/features/members/components/members/MembersList.tsxindex f03071f7..31cc24ee 100644--- a/apps/web/src/features/members/components/members/MembersList.tsx+++ b/apps/web/src/features/members/components/members/MembersList.tsx@@ -11,7 +11,7 @@ import SearchInput from '@/components/common/SearchInput';import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { useMembersQuery, useRemoveMember } from '@/services/members.service';-import { useTeamRolesQuery } from '@/services/roles.service';+import { useTeamRoleOptionsQuery } from '@/services/roles.service';import { useSearchTerm } from '@/hooks/useSearchTerm';import { usePermissions } from '@/hooks/usePermissions';import { useSession } from '@/lib/auth-client';@@ -42,7 +42,7 @@ export default function MembersList({// Roles feed the per-member role select, so the list is only fetched for a reader// who gets one.const canEdit = can('members_manage', 'edit') || isAdmin;- const rolesQuery = useTeamRolesQuery(canEdit ? teamId : null);+ const rolesQuery = useTeamRoleOptionsQuery(canEdit ? teamId : null);const router = useRouter();const [target, setTarget] = useState<Member | null>(null);diff --git a/apps/web/src/features/teams/components/ai-agents/AgentProjectsSection.tsx b/apps/web/src/features/teams/components/ai-agents/AgentProjectsSection.tsxindex a449be96..d6663b13 100644--- a/apps/web/src/features/teams/components/ai-agents/AgentProjectsSection.tsx+++ b/apps/web/src/features/teams/components/ai-agents/AgentProjectsSection.tsx@@ -1,5 +1,5 @@import { FolderKanban } from 'lucide-react';-import type { TeamProject } from '@/lib/api';+import type { TeamProjectOption } from '@/lib/api';import type { AgentFormValue } from '../../utils/agentForm';import { AgentCapabilityList } from './AgentCapabilityList';import { AgentEmptyNotice } from './AgentEmptyNotice';@@ -20,7 +20,7 @@ export default function AgentProjectsSection({onOpenChange: (open: boolean) => void;value: AgentFormValue;onChange: (patch: Partial<AgentFormValue>) => void;- projects: TeamProject[];+ projects: TeamProjectOption[];}) {const t = useTranslations('teams.agents');diff --git a/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx b/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsxindex 01ed5b2b..4c5b8ba5 100644--- a/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx+++ b/apps/web/src/features/teams/components/ai-agents/AgentSheetForm.tsx@@ -12,7 +12,7 @@ import {useIntegrationModelsQuery,useIntegrationOptionsQuery,} from '@/services/integrations.service';-import { useTeamProjectsQuery, useTeamQuery } from '@/services/teams.service';+import { useTeamProjectOptionsQuery, useTeamQuery } from '@/services/teams.service';import {useSkillOptionsQuery,useAgentSkillsQuery,@@ -77,7 +77,7 @@ export function AgentSheetForm({const canManageSkills = team?.permissions.agent_skills.edit ?? false;const canManageTools = team?.permissions.agent_tools.edit ?? false;- const projects = useTeamProjectsQuery(teamId).data ?? [];+ const projects = useTeamProjectOptionsQuery(teamId).data ?? [];const toolsQuery = useAgentToolsQuery(teamId);const catalogQuery = useIntegrationCatalogQuery(teamId);const catalog = catalogQuery.data ?? [];diff --git a/apps/web/src/features/teams/components/ai-agents/AgentTriggersSection.tsx b/apps/web/src/features/teams/components/ai-agents/AgentTriggersSection.tsxindex ddd77f1e..d5f2b22e 100644--- a/apps/web/src/features/teams/components/ai-agents/AgentTriggersSection.tsx+++ b/apps/web/src/features/teams/components/ai-agents/AgentTriggersSection.tsx@@ -1,7 +1,7 @@import { Fragment } from 'react';import { Zap } from 'lucide-react';import { useQueries } from '@tanstack/react-query';-import type { CustomField, TeamProject } from '@/lib/api';+import type { CustomField, TeamProjectOption } from '@/lib/api';import { api } from '@/lib/api';import { qk } from '@/services/queryKeys';import { Switch } from '@/components/ui/switch';@@ -13,7 +13,7 @@ import { useTranslations } from 'next-intl';// A member field an agent can be set into, with the project it belongs to: an agent// works in several projects of its team, and each has its own fields.-type ProjectField = { field: CustomField; project: TeamProject };+type ProjectField = { field: CustomField; project: TeamProjectOption };// What starts a run: a mention in a comment, being made an issue's delegate, or being// set into a member custom field that holds agents. Every trigger but the mention@@ -32,7 +32,7 @@ export default function AgentTriggersSection({onChange: (patch: Partial<AgentFormValue>) => void;// The projects of the team, of which the agent works in the ones it is attached to.// Only those carry fields it can be set into.- projects: TeamProject[];+ projects: TeamProjectOption[];}) {const t = useTranslations('teams.agents');const attached = projects.filter((project) => value.projectIds.includes(project.id));diff --git a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentFields.tsx b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentFields.tsxindex 03972bfa..c0c8bc80 100644--- a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentFields.tsx+++ b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentFields.tsx@@ -6,7 +6,7 @@ import type {IntegrationMeta,IntegrationOption,ProviderModel,- TeamProject,+ TeamProjectOption,} from '@/lib/api';import { Input } from '@/components/ui/input';import { Checkbox } from '@/components/ui/checkbox';@@ -61,7 +61,7 @@ export default function TeamAiAgentFields({onChange: (patch: Partial<AgentFormValue>) => void;// The projects of the team, which the Projects section attaches the agent to and the// Triggers section reads the member fields of.- projects: TeamProject[];+ projects: TeamProjectOption[];tools: AgentTool[];toolsLoading: boolean;kindLocked: boolean;diff --git a/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsx b/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsxindex 591aad92..355faa6b 100644--- a/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsx+++ b/apps/web/src/features/teams/components/mcp/TeamMcpSection.tsx@@ -2,7 +2,7 @@import { useTranslations } from 'next-intl';import { Check, Minus } from 'lucide-react';-import { useTeam, useTeamProjectsQuery, useUpdateTeamMcp } from '@/services/teams.service';+import { useTeam, useTeamProjectOptionsQuery, useUpdateTeamMcp } from '@/services/teams.service';import SectionPageView from '@/components/common/page/SectionPageView';import ListSkeleton from '@/components/common/skeleton/ListSkeleton';import { Switch } from '@/components/ui/switch';@@ -25,7 +25,7 @@ function McpStatus({ on }: { on: boolean }) {export default function TeamMcpSection({ teamId }: { teamId: number }) {const t = useTranslations('teams.mcp');const team = useTeam(teamId);- const { data: projects } = useTeamProjectsQuery(teamId);+ const { data: projects } = useTeamProjectOptionsQuery(teamId);const update = useUpdateTeamMcp(teamId);const canManage = team != null && team.role !== 'member';diff --git a/apps/web/src/features/teams/components/projects/TeamProjectMembers.tsx b/apps/web/src/features/teams/components/projects/TeamProjectMembers.tsxindex 058760f2..0b41cf4e 100644--- a/apps/web/src/features/teams/components/projects/TeamProjectMembers.tsx+++ b/apps/web/src/features/teams/components/projects/TeamProjectMembers.tsx@@ -6,7 +6,7 @@ import { useTranslations } from 'next-intl';import type { MemberKind } from '@/lib/api';import { useSearchTerm } from '@/hooks/useSearchTerm';import { useTeamProjectMembersQuery } from '@/services/teams.service';-import { usePermissionCatalogQuery, useTeamRolesQuery } from '@/services/roles.service';+import { usePermissionCatalogQuery, useTeamRoleOptionsQuery } from '@/services/roles.service';import ListSkeleton from '@/components/common/skeleton/ListSkeleton';import { EmptyState } from '@/components/common/page/EmptyState';import RowAction from '@/components/common/RowAction';@@ -63,7 +63,7 @@ export default function TeamProjectMembers({const membersQuery = useTeamProjectMembersQuery(teamId, projectId, { search: term, kind });// The roles carry the matrix each membership resolves to, so they are fetched for// every reader of the panel, not only the one who may reassign them.- const rolesQuery = useTeamRolesQuery(teamId);+ const rolesQuery = useTeamRoleOptionsQuery(teamId);const catalogQuery = usePermissionCatalogQuery();const members = membersQuery.data?.pages.flatMap((page) => page.items) ?? [];diff --git a/apps/web/src/features/teams/components/projects/TeamProjectsSection.tsx b/apps/web/src/features/teams/components/projects/TeamProjectsSection.tsxindex 904cc097..1b675369 100644--- a/apps/web/src/features/teams/components/projects/TeamProjectsSection.tsx+++ b/apps/web/src/features/teams/components/projects/TeamProjectsSection.tsx@@ -8,6 +8,10 @@ import { projectPath } from '@/utils/paths';import { useTeam, useTeamProjectsQuery } from '@/services/teams.service';import SectionPageView from '@/components/common/page/SectionPageView';import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import ListPager from '@/components/common/ListPager';+import SearchInput from '@/components/common/SearchInput';+import { usePaging } from '@/hooks/usePaging';+import { useSearchTerm } from '@/hooks/useSearchTerm';import { Button } from '@/components/ui/button';import NewProjectModal from '@/components/layout/NewProjectModal';import TeamProjectPanel from './TeamProjectPanel';@@ -19,14 +23,22 @@ export default function TeamProjectsSection({ teamId }: { teamId: number }) {const t = useTranslations('teams');const router = useRouter();const team = useTeam(teamId);- const { data } = useTeamProjectsQuery(teamId);+ const paging = usePaging();+ const { search, setSearch, term } = useSearchTerm();+ const { data } = useTeamProjectsQuery(teamId, { search: term, ...paging.params });const [creating, setCreating] = useState(false);const [selectedId, setSelectedId] = useState<number | null>(null);const canCreate = team != null && team.role !== 'member';- const projects = data ?? [];+ const projects = data?.items ?? [];+ const total = data?.total ?? 0;const selected = projects.find((project) => project.id === selectedId) ?? null;+ function onSearchChange(next: string) {+ setSearch(next);+ paging.reset();+ }+return (<SectionPageViewtitle={t('sections.projects.title')}@@ -41,13 +53,29 @@ export default function TeamProjectsSection({ teamId }: { teamId: number }) {) : undefined}>- {!data ? (- <ListSkeleton rows={4} rowClassName="h-12" />- ) : projects.length === 0 ? (- <p className="text-sm text-muted-foreground">{t('panel.noProjects')}</p>- ) : (- <TeamProjectsTable projects={projects} onSelect={setSelectedId} />- )}+ <div className="space-y-4">+ <div className="flex justify-end">+ <SearchInput+ value={search}+ onChange={onSearchChange}+ placeholder={t('panel.searchProjects')}+ className="w-60"+ />+ </div>++ {!data ? (+ <ListSkeleton rows={4} rowClassName="h-12" />+ ) : projects.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {term === undefined+ ? t('panel.noProjects')+ : t('panel.noProjectsMatch', { query: term })}+ </p>+ ) : (+ <TeamProjectsTable projects={projects} onSelect={setSelectedId} />+ )}+ {total > 0 && <ListPager paging={paging} total={total} />}+ </div>{creating && (<NewProjectModaldiff --git a/apps/web/src/features/teams/components/roles/TeamRolesList.tsx b/apps/web/src/features/teams/components/roles/TeamRolesList.tsxindex e377ec89..00598c64 100644--- a/apps/web/src/features/teams/components/roles/TeamRolesList.tsx+++ b/apps/web/src/features/teams/components/roles/TeamRolesList.tsx@@ -22,20 +22,25 @@ import DeleteRoleDialog from './DeleteRoleDialog';// The team's roles, one row each: what it grants, and the actions to edit or delete// it. Deleting is the owner's, so a manager gets the row without that action. The// default role cannot be deleted; deleting any other one moves what is on it to a-// role the dialog asks for.+// role the dialog asks for, which is why it is handed every role of the team and not+// only the page on screen.export default function TeamRolesList({teamId,roles,+ allRoles,pending,canEdit,canDelete,+ searchTerm,onEdit,}: {teamId: number;roles: Role[];+ allRoles: Role[];pending: boolean;canEdit: boolean;canDelete: boolean;+ searchTerm: string | undefined;onEdit: (role: Role) => void;}) {const t = useTranslations('teams');@@ -44,7 +49,11 @@ export default function TeamRolesList({if (pending) return <ListSkeleton rows={2} rowClassName="h-12" />;if (roles.length === 0)- return <p className="text-sm text-muted-foreground">{t('roles.empty')}</p>;+ return (+ <p className="text-sm text-muted-foreground">+ {searchTerm === undefined ? t('roles.empty') : t('roles.noMatches', { query: searchTerm })}+ </p>+ );return (<div className="overflow-x-auto">@@ -137,7 +146,7 @@ export default function TeamRolesList({<DeleteRoleDialogteamId={teamId}role={deleting}- roles={roles}+ roles={allRoles}onClose={() => setDeleting(null)}/>)}diff --git a/apps/web/src/features/teams/components/roles/TeamRolesSection.tsx b/apps/web/src/features/teams/components/roles/TeamRolesSection.tsxindex 82fbae3c..c40fc625 100644--- a/apps/web/src/features/teams/components/roles/TeamRolesSection.tsx+++ b/apps/web/src/features/teams/components/roles/TeamRolesSection.tsx@@ -3,10 +3,18 @@import { useState } from 'react';import { useTranslations } from 'next-intl';import type { Role } from '@/lib/api';-import { usePermissionCatalogQuery, useTeamRolesQuery } from '@/services/roles.service';+import {+ usePermissionCatalogQuery,+ useTeamRoleOptionsQuery,+ useTeamRolesQuery,+} from '@/services/roles.service';import { useTeam } from '@/services/teams.service';import SectionPageView from '@/components/common/page/SectionPageView';import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import ListPager from '@/components/common/ListPager';+import SearchInput from '@/components/common/SearchInput';+import { usePaging } from '@/hooks/usePaging';+import { useSearchTerm } from '@/hooks/useSearchTerm';import RoleEditorPanel from './RoleEditorPanel';import TeamRolesList from './TeamRolesList';import TeamRolesToolbar from './TeamRolesToolbar';@@ -19,15 +27,29 @@ export default function TeamRolesSection({ teamId }: { teamId: number }) {const t = useTranslations('teams');const team = useTeam(teamId);const canManage = team?.role === 'owner' || team?.role === 'manager';- const rolesQuery = useTeamRolesQuery(canManage ? teamId : null);+ const paging = usePaging();+ const { search, setSearch, term } = useSearchTerm();+ const rolesQuery = useTeamRolesQuery(canManage ? teamId : null, {+ search: term,+ ...paging.params,+ });+ // The clipboard actions carry every role of the team, and the delete dialog moves a+ // role's members to one of them, so both read the whole list rather than the page.+ const allRoles = useTeamRoleOptionsQuery(canManage ? teamId : null).data ?? [];const catalogQuery = usePermissionCatalogQuery();const [creating, setCreating] = useState(false);const [editing, setEditing] = useState<Role | null>(null);- const roles = rolesQuery.data ?? [];+ const roles = rolesQuery.data?.items ?? [];+ const total = rolesQuery.data?.total ?? 0;const catalog = catalogQuery.data ?? null;const editorOpen = creating || editing !== null;+ function onSearchChange(next: string) {+ setSearch(next);+ paging.reset();+ }+return (<SectionPageViewtitle={t('sections.roles.title')}@@ -37,7 +59,7 @@ export default function TeamRolesSection({ teamId }: { teamId: number }) {canManage ? (<TeamRolesToolbarteamId={teamId}- roles={roles}+ roles={allRoles}catalog={catalog}onCreate={() => setCreating(true)}/>@@ -49,14 +71,28 @@ export default function TeamRolesSection({ teamId }: { teamId: number }) {) : !canManage ? (<p className="text-sm text-muted-foreground">{t('roles.ownerOnly')}</p>) : (- <TeamRolesList- teamId={teamId}- roles={roles}- pending={rolesQuery.isPending}- canEdit={catalog !== null}- canDelete={team.role === 'owner'}- onEdit={setEditing}- />+ <div className="space-y-4">+ <div className="flex justify-end">+ <SearchInput+ value={search}+ onChange={onSearchChange}+ placeholder={t('roles.search')}+ className="w-60"+ />+ </div>++ <TeamRolesList+ teamId={teamId}+ roles={roles}+ allRoles={allRoles}+ pending={rolesQuery.isPending}+ canEdit={catalog !== null}+ canDelete={team.role === 'owner'}+ searchTerm={term}+ onEdit={setEditing}+ />+ {total > 0 && <ListPager paging={paging} total={total} />}+ </div>)}{editorOpen && catalog && (diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 52f99cb9..8eec33ac 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -200,6 +200,20 @@ export interface TeamProject {createdAt: string;}+// What a team's project list asks for: the window, and a search over the key and the+// name. The search runs on the server, so the page and the total agree.+export interface TeamProjectListParams extends PageParams {+ search?: string;+}++// A project as the pickers read it, plus the MCP reach the team's switches set.+export interface TeamProjectOption {+ id: number;+ key: string;+ name: string;+ mcpEnabled: boolean;+}+export interface TeamDetail extends Team {// What the caller may do with the resources the team holds for all its projects.// Owners and managers get the full matrix; a member gets the permissions of their@@ -2902,6 +2916,11 @@ export interface Role {createdAt: string;}+// What a role list asks for: the window, and a search over the name.+export interface RoleListParams extends PageParams {+ search?: string;+}+// What a role is assigned to. Everything counted here is moved to another role// before the role can be deleted.export interface RoleUsage {@@ -3130,7 +3149,15 @@ export const api = {// handle.listTeamMembers: (teamId: number, params: MemberListParams) =>request<Page<TeamMember>>(`/teams/${teamId}/members${memberListQuery(params)}`),- listTeamProjects: (teamId: number) => request<TeamProject[]>(`/teams/${teamId}/projects`),+ // One page of the projects the team owns. `search` matches the key or the name.+ listTeamProjects: (teamId: number, params: TeamProjectListParams) =>+ request<Page<TeamProject>>(+ `/teams/${teamId}/projects${pageQuery(params, { search: params.search })}`,+ ),+ // Every project the reader has in the team, for the agent's project picker and the+ // MCP switches.+ listTeamProjectOptions: (teamId: number) =>+ request<TeamProjectOption[]>(`/teams/${teamId}/projects/options`),getTeamProject: (teamId: number, projectId: number) =>request<TeamProjectDetail>(`/teams/${teamId}/projects/${projectId}`),// One page of a project's members. `search` matches the name, the address or the@@ -4114,7 +4141,12 @@ export const api = {// belong to the team, so one list serves every project it owns; an owner or a// manager of the team writes them, and only its owner deletes one.getPermissionCatalog: () => request<PermissionCatalog>('/permission-catalog'),- listTeamRoles: (teamId: number) => request<Role[]>(`/teams/${teamId}/roles`),+ // One page of the team's roles. `search` matches the name.+ listTeamRoles: (teamId: number, params: RoleListParams) =>+ request<Page<Role>>(`/teams/${teamId}/roles${pageQuery(params, { search: params.search })}`),+ // Every role of the team, with its matrix: what the role pickers assign from and+ // what the clipboard export carries.+ listTeamRoleOptions: (teamId: number) => request<Role[]>(`/teams/${teamId}/roles/options`),createRole: (teamId: number, input: { name: string; permissions: Permissions }) =>request<Role>(`/teams/${teamId}/roles`, { method: 'POST', body: JSON.stringify(input) }),updateRole: (diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex f24e3bd9..cc794d6f 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -7,9 +7,15 @@ export const qk = {// One team: its counters and what the caller may do with what it holds.team: (teamId: number) => ['team', teamId] as const,// The members of a team and the projects it owns, each read by its own section. A- // member page is scoped by the search term and the window it was read with.+ // page is scoped by the search term and the window it was read with.teamMembers: (teamId: number, params: unknown) => ['team', teamId, 'members', params] as const,- teamProjects: (teamId: number) => ['team', teamId, 'projects'] as const,+ teamProjects: (teamId: number, params: unknown) => ['team', teamId, 'projects', params] as const,+ // Every project of the team, for the pickers and the MCP switches that act on all+ // of them.+ teamProjectOptions: (teamId: number) => ['team', teamId, 'projects', 'options'] as const,+ // Every page of a team's projects and its options list, for a write that changes+ // what they show.+ anyTeamProjects: (teamId: number) => ['team', teamId, 'projects'] as const,// One project the team owns, loaded when its row is opened, and one page of its// members (the search term and the window scope the entry).teamProject: (teamId: number, projectId: number) =>@@ -99,7 +105,9 @@ export const qk = {anyTeamInvites: ['teamInvites'] as const,// The roles a team offers, which is what every project of it assigns from. The// permission catalog is app-static, so it is scoped to no team.- teamRoles: (teamId: number) => ['teamRoles', teamId] as const,+ teamRoles: (teamId: number, params: unknown) => ['teamRoles', teamId, params] as const,+ teamRoleOptions: (teamId: number) => ['teamRoles', teamId, 'options'] as const,+ anyTeamRoles: (teamId: number) => ['teamRoles', teamId] as const,roleUsage: (teamId: number, roleId: number) => ['roleUsage', teamId, roleId] as const,anyRoleUsage: ['roleUsage'] as const,permissionCatalog: ['permissionCatalog'] as const,diff --git a/apps/web/src/services/roles.service.ts b/apps/web/src/services/roles.service.tsindex cb7731ff..9691decf 100644--- a/apps/web/src/services/roles.service.ts+++ b/apps/web/src/services/roles.service.ts@@ -1,5 +1,5 @@-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { api, type Permissions } from '@/lib/api';+import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { api, type Permissions, type RoleListParams } from '@/lib/api';import { qk } from '@/services/queryKeys';// The resources and actions of the permission matrix. Static for the app's@@ -12,13 +12,23 @@ export function usePermissionCatalogQuery() {});}-// The roles a team offers, which is what every project of it assigns from. Readable-// by any member of the team; pass null where the caller has no use for the list, to-// skip the request.-export function useTeamRolesQuery(teamId: number | null) {+// One page of the team's roles, for the section that manages them. Pass null where+// the caller has no use for the list, to skip the request.+export function useTeamRolesQuery(teamId: number | null, params: RoleListParams) {return useQuery({- queryKey: qk.teamRoles(teamId ?? 0),- queryFn: () => api.listTeamRoles(teamId!),+ queryKey: qk.teamRoles(teamId ?? 0, params),+ queryFn: () => api.listTeamRoles(teamId!, params),+ enabled: teamId != null,+ placeholderData: keepPreviousData,+ });+}++// Every role of the team, with its matrix: what the role pickers assign from, what+// the delete dialog moves a role's members to, and what the clipboard export carries.+export function useTeamRoleOptionsQuery(teamId: number | null) {+ return useQuery({+ queryKey: qk.teamRoleOptions(teamId ?? 0),+ queryFn: () => api.listTeamRoleOptions(teamId!),enabled: teamId != null,});}@@ -42,7 +52,7 @@ function useRoleMutation<TInput, TResult>(return useMutation({mutationFn,onSuccess: () => {- qc.invalidateQueries({ queryKey: qk.teamRoles(teamId) });+ qc.invalidateQueries({ queryKey: qk.anyTeamRoles(teamId) });// The team list carries how many roles the team has.qc.invalidateQueries({ queryKey: qk.teams });qc.invalidateQueries({ queryKey: qk.anyRoleUsage });diff --git a/apps/web/src/services/teams.service.ts b/apps/web/src/services/teams.service.tsindex 871970d6..3f3a064e 100644--- a/apps/web/src/services/teams.service.ts+++ b/apps/web/src/services/teams.service.ts@@ -12,6 +12,7 @@ import {type MemberKind,type MemberListParams,type NotificationSettingsPatch,+ type TeamProjectListParams,type Team,type TeamRole,} from '@/lib/api';@@ -46,10 +47,23 @@ export function useTeamMembersQuery(teamId: number, params: MemberListParams) {});}-export function useTeamProjectsQuery(teamId: number) {+// One page of the projects the team owns. The search and the window run on the+// server, so the section never loads every project of the team; the previous page+// stays on screen while the next one loads.+export function useTeamProjectsQuery(teamId: number, params: TeamProjectListParams) {return useQuery({- queryKey: qk.teamProjects(teamId),- queryFn: () => api.listTeamProjects(teamId),+ queryKey: qk.teamProjects(teamId, params),+ queryFn: () => api.listTeamProjects(teamId, params),+ placeholderData: keepPreviousData,+ });+}++// Every project the reader has in the team: the projects an agent is attached to,+// and the MCP switches, both of which act on all of them rather than on a page.+export function useTeamProjectOptionsQuery(teamId: number) {+ return useQuery({+ queryKey: qk.teamProjectOptions(teamId),+ queryFn: () => api.listTeamProjectOptions(teamId),});}@@ -91,7 +105,7 @@ export function useUpdateTeamMcp(teamId: number) {}) => api.updateTeamMcp(teamId, patch),onSuccess: () => {void qc.invalidateQueries({ queryKey: qk.teams });- void qc.invalidateQueries({ queryKey: qk.teamProjects(teamId) });+ void qc.invalidateQueries({ queryKey: qk.anyTeamProjects(teamId) });void qc.invalidateQueries({ queryKey: qk.projects });// A project's own MCP page reads the state off the project scaffold, which is// cached per project key.