⭐️⭐️⭐️ 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
feat(god): teams directory with a team detail panel (#343)
Croffc0188de5bdd7
diff --git a/apps/api/src/modules/god/__tests__/integration/god-teams.test.ts b/apps/api/src/modules/god/__tests__/integration/god-teams.test.tsnew file mode 100644index 00000000..4ceccc38--- /dev/null+++ b/apps/api/src/modules/god/__tests__/integration/god-teams.test.ts@@ -0,0 +1,248 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { resetDb } from '#tests/helpers/db';+import { addUser, createAgentUser, setup, type Actor } from '../helpers';++// The instance team directory under god mode: listing every team on the instance with+// what it holds, and reading one with the projects it owns and everyone in it. These+// routes read teams the caller does not belong to, so they sit behind the god guard+// like the rest of the plugin.++const PAGE = { page: 1, pageSize: 50 };++// Every account is given a team at registration, so the actor's own team is its first.+async function ownTeamId(actor: Actor): Promise<number> {+ const teams = await actor.api.teams.get();+ return teams.data![0]!.id;+}++describe('god teams', () => {+ beforeEach(async () => {+ await resetDb();+ });++ describe('access', () => {+ it('refuses both routes for a user who is not the instance owner', async () => {+ await setup();+ const outsider = await addUser();+ const teamId = await ownTeamId(outsider);++ expect((await outsider.api.god.teams.get({ query: PAGE })).status).toBe(403);+ expect((await outsider.api.god.teams({ teamId }).get()).status).toBe(403);+ });+ });++ describe('list — GET /god/teams', () => {+ it('lists every team on the instance, including ones the owner is not in', async () => {+ const { god } = await setup();+ const alice = await addUser({ email: '[email protected]' });+ await alice.api.teams.post({ name: 'Alice Only' });++ const res = await god.api.god.teams.get({ query: PAGE });++ expect(res.status).toBe(200);+ // The god's own team, Alice's registration team, and the one she created.+ expect(res.data?.total).toBe(3);+ expect(res.data?.items.map((one) => one.name)).toContain('Alice Only');+ });++ it('counts what a team holds', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ const view = await god.api.projects({ projectKey: 'MKT' }).get();+ await god.api.projects({ projectKey: 'MKT' }).issues.post({+ title: 'First',+ columnId: view.data!.columns[0]!.id,+ });+ await createAgentUser(god, 'MKT');++ const res = await god.api.god.teams.get({ query: PAGE });+ const row = res.data!.items.find((one) => one.id === teamId)!;++ expect(row).toMatchObject({+ projectCount: 1,+ issueCount: 1,+ agentCount: 1,+ mcpEnabled: true,+ // The owner and the agent's bot user, which belongs to the team too.+ memberCount: 2,+ });+ });++ it('leaves an archived issue out of the count', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ const view = await god.api.projects({ projectKey: 'MKT' }).get();+ const created = await god.api.projects({ projectKey: 'MKT' }).issues.post({+ title: 'Old',+ columnId: view.data!.columns[0]!.id,+ });+ await god.api.issues({ issueId: created.data!.id }).archive.post();++ const res = await god.api.god.teams.get({ query: PAGE });++ expect(res.data!.items.find((one) => one.id === teamId)?.issueCount).toBe(0);+ });++ it('matches the search term against the name', async () => {+ const { god } = await setup();+ await god.api.teams.post({ name: 'Marketing' });+ await god.api.teams.post({ name: 'Engineering' });++ const match = await god.api.god.teams.get({ query: { ...PAGE, search: 'market' } });+ const noMatch = await god.api.god.teams.get({ query: { ...PAGE, search: 'nothing' } });++ expect(match.data?.items.map((one) => one.name)).toEqual(['Marketing']);+ expect(match.data?.total).toBe(1);+ expect(noMatch.data?.items).toEqual([]);+ expect(noMatch.data?.total).toBe(0);+ });++ it('pages with limit and offset while the total stays the full match count', async () => {+ const { god } = await setup();+ await god.api.teams.post({ name: 'One' });+ await god.api.teams.post({ name: 'Two' });++ const first = await god.api.god.teams.get({ query: { page: 1, pageSize: 2 } });+ const second = await god.api.god.teams.get({ query: { page: 2, pageSize: 2 } });++ // The two created teams plus the one the god account registered with.+ expect(first.data?.items).toHaveLength(2);+ expect(second.data?.items).toHaveLength(1);+ expect(first.data?.total).toBe(3);+ expect(new Set([...first.data!.items, ...second.data!.items].map((one) => one.id)).size).toBe(+ 3,+ );+ });++ it('rejects a page size outside the allowed range', async () => {+ const { god } = await setup();++ expect((await god.api.god.teams.get({ query: { ...PAGE, pageSize: 0 } })).status).toBe(400);+ expect((await god.api.god.teams.get({ query: { ...PAGE, pageSize: 500 } })).status).toBe(400);+ });+ });++ describe('detail — GET /god/teams/:teamId', () => {+ it('returns the counts of the team', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });++ const res = await god.api.god.teams({ teamId }).get();++ expect(res.status).toBe(200);+ expect(res.data).toMatchObject({ id: teamId, projectCount: 1, memberCount: 1 });+ });++ it('returns 404 for an unknown team and 400 for a non-numeric id', async () => {+ const { god } = await setup();++ expect((await god.api.god.teams({ teamId: 999999 }).get()).status).toBe(404);+ expect((await god.api.god.teams({ teamId: 'abc' }).get()).status).toBe(400);+ });+ });++ describe('projects — GET /god/teams/:teamId/projects', () => {+ it('lists the projects the team owns with what each holds', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ const view = await god.api.projects({ projectKey: 'MKT' }).get();+ await god.api.projects({ projectKey: 'MKT' }).issues.post({+ title: 'First',+ columnId: view.data!.columns[0]!.id,+ });++ const res = await god.api.god.teams({ teamId }).projects.get({ query: PAGE });++ expect(res.status).toBe(200);+ expect(res.data?.total).toBe(1);+ expect(res.data?.items[0]).toMatchObject({+ key: 'MKT',+ name: 'Marketing',+ memberCount: 1,+ issueCount: 1,+ });+ });++ it('matches the search term against the key or the name, and pages', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ await god.api.projects.post({ key: 'ENG', name: 'Engineering' });++ const byKey = await god.api.god+ .teams({ teamId })+ .projects.get({ query: { ...PAGE, search: 'mkt' } });+ const first = await god.api.god+ .teams({ teamId })+ .projects.get({ query: { page: 1, pageSize: 1 } });++ expect(byKey.data?.items.map((one) => one.key)).toEqual(['MKT']);+ expect(byKey.data?.total).toBe(1);+ // The window narrows, the total stays the full match count.+ expect(first.data?.items).toHaveLength(1);+ expect(first.data?.total).toBe(2);+ });++ it('refuses a user who is not the instance owner', async () => {+ await setup();+ const outsider = await addUser();+ const teamId = await ownTeamId(outsider);++ expect((await outsider.api.god.teams({ teamId }).projects.get({ query: PAGE })).status).toBe(+ 403,+ );+ });+ });++ describe('members — GET /god/teams/:teamId/members', () => {+ it('lists everyone in the team with their rank, and flags an agent', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);+ await god.api.projects.post({ key: 'MKT', name: 'Marketing' });+ const agentUserId = await createAgentUser(god, 'MKT');++ const res = await god.api.god.teams({ teamId }).members.get({ query: PAGE });++ expect(res.status).toBe(200);+ expect(res.data?.total).toBe(2);+ expect(res.data!.items.find((m) => m.userId === god.id)).toMatchObject({+ role: 'owner',+ isAgent: false,+ });+ expect(res.data!.items.find((m) => m.userId === agentUserId)).toMatchObject({+ role: 'agent',+ isAgent: true,+ });+ });++ it('matches the search term against the name or the address', async () => {+ const { god } = await setup();+ const teamId = await ownTeamId(god);++ const byEmail = await god.api.god+ .teams({ teamId })+ .members.get({ query: { ...PAGE, search: 'root@example' } });+ const noMatch = await god.api.god+ .teams({ teamId })+ .members.get({ query: { ...PAGE, search: 'nobody' } });++ expect(byEmail.data?.items.map((m) => m.userId)).toEqual([god.id]);+ expect(noMatch.data?.items).toEqual([]);+ expect(noMatch.data?.total).toBe(0);+ });++ it('refuses a user who is not the instance owner', async () => {+ await setup();+ const outsider = await addUser();+ const teamId = await ownTeamId(outsider);++ expect((await outsider.api.god.teams({ teamId }).members.get({ query: PAGE })).status).toBe(+ 403,+ );+ });+ });+});diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.tsindex cc43bc3c..59891a7e 100644--- a/apps/api/src/modules/god/index.ts+++ b/apps/api/src/modules/god/index.ts@@ -29,9 +29,13 @@ import { deleteProject } from '#modules/projects/service';import {deleteInstanceUser,getInstanceProject,+ getInstanceTeam,getInstanceUser,listInstanceProjects,listInstanceProjectOptions,+ listInstanceTeams,+ listInstanceTeamProjects,+ listInstanceTeamMembers,listInstanceUsers,listScimGroups,setScimGroupMappings,@@ -48,6 +52,10 @@ import {InstanceProjectDetailResponse,InstanceProjectOptionListResponse,InstanceProjectPageResponse,+ InstanceTeamMemberPageResponse,+ InstanceTeamPageResponse,+ InstanceTeamProjectPageResponse,+ InstanceTeamResponse,InstanceUserDetailResponse,InstanceUserPageResponse,OidcSettingsBody,@@ -61,10 +69,11 @@ import {TelegramSettingsBody,TelegramSettingsResponse,deleteUserQuery,- listProjectsQuery,listUsersQuery,projectParams,scimGroupParams,+ searchPageQuery,+ teamParams,userParams,} from './model';import { emailTestError } from './email-test';@@ -585,7 +594,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })({ query }) =>paginate(query, (window) => listInstanceProjects({ search: query.search, ...window })),{- query: listProjectsQuery,+ query: searchPageQuery,response: { 200: InstanceProjectPageResponse, ...errors(400, 401, 403) },detail: {summary: 'List instance projects',@@ -618,4 +627,69 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })'Get one project with what it holds and every member, with the permissions each membership resolves to.',},},+ )++ .get(+ '/god/teams',+ ({ query }) =>+ paginate(query, (window) => listInstanceTeams({ search: query.search, ...window })),+ {+ query: searchPageQuery,+ response: { 200: InstanceTeamPageResponse, ...errors(400, 401, 403) },+ detail: {+ summary: 'List instance teams',+ description: 'One page of teams with what each holds, plus how many match the search.',+ },+ },+ )++ .get(+ '/god/teams/:teamId',+ async ({ params }) => {+ const found = await getInstanceTeam(params.teamId);+ if (!found) throw new HttpError(404, 'Team not found');+ return found;+ },+ {+ params: teamParams,+ response: { 200: InstanceTeamResponse, ...commonErrors },+ detail: {+ summary: 'Get an instance team',+ description: 'Get one team with what it holds. Its projects and members are paged apart.',+ },+ },+ )++ .get(+ '/god/teams/:teamId/projects',+ ({ params, query }) =>+ paginate(query, (window) =>+ listInstanceTeamProjects(params.teamId, { search: query.search, ...window }),+ ),+ {+ params: teamParams,+ query: searchPageQuery,+ response: { 200: InstanceTeamProjectPageResponse, ...commonErrors },+ detail: {+ summary: "List a team's projects",+ description: 'One page of the projects a team owns, with what each holds.',+ },+ },+ )++ .get(+ '/god/teams/:teamId/members',+ ({ params, query }) =>+ paginate(query, (window) =>+ listInstanceTeamMembers(params.teamId, { search: query.search, ...window }),+ ),+ {+ params: teamParams,+ query: searchPageQuery,+ response: { 200: InstanceTeamMemberPageResponse, ...commonErrors },+ detail: {+ summary: "List a team's members",+ description: 'One page of the team members, people and agents alike, with their rank.',+ },+ },);diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.tsindex d4b46f34..c350e91a 100644--- a/apps/api/src/modules/god/model.ts+++ b/apps/api/src/modules/god/model.ts@@ -18,7 +18,9 @@ export const listUsersQuery = t.Object({...pageQueryFields,});-export const listProjectsQuery = t.Object({+// The query every searchable directory listing takes: the projects, the teams, and a+// team's own projects and members.+export const searchPageQuery = t.Object({search: t.Optional(t.String()),...pageQueryFields,});@@ -271,3 +273,45 @@ export const InstanceProjectPageResponse = pageResponse(InstanceProjectResponse)export const InstanceProjectOptionListResponse = t.Array(t.Object({ id: t.Number(), key: t.String(), name: t.String() }),);++export const teamParams = t.Object({ teamId: t.Numeric() });++export const InstanceTeamResponse = t.Object({+ id: t.Number(),+ name: t.String(),+ mcpEnabled: t.Boolean(),+ memberCount: t.Number(),+ projectCount: t.Number(),+ issueCount: t.Number(),+ agentCount: t.Number(),+ skillCount: t.Number(),+ toolCount: t.Number(),+ roleCount: t.Number(),+ createdAt: t.String(),+});++export const InstanceTeamPageResponse = pageResponse(InstanceTeamResponse);++export const InstanceTeamProjectPageResponse = pageResponse(+ t.Object({+ id: t.Number(),+ key: t.String(),+ name: t.String(),+ mcpEnabled: t.Boolean(),+ memberCount: t.Number(),+ issueCount: t.Number(),+ createdAt: t.String(),+ }),+);++export const InstanceTeamMemberPageResponse = pageResponse(+ t.Object({+ userId: t.String(),+ name: t.String(),+ email: t.String(),+ image: t.Nullable(t.String()),+ isAgent: t.Boolean(),+ role: t.UnionEnum(['owner', 'manager', 'member', 'agent']),+ joinedAt: t.String(),+ }),+);diff --git a/apps/api/src/modules/god/service.ts b/apps/api/src/modules/god/service.tsindex 2423d94b..e7048f1a 100644--- a/apps/api/src/modules/god/service.ts+++ b/apps/api/src/modules/god/service.ts@@ -12,6 +12,8 @@ import {project,projectDashboard,projectMember,+ team,+ teamMember,teamRole,projectView,scimGroup,@@ -44,6 +46,7 @@ import {} from '#shared/permissions';import { listAllMembers, listMemberContexts } from '#modules/members/service';import { listRoles } from '#modules/roles/service';+import type { TeamStanding } from '#modules/teams/service';// Data access for the instance directories (god mode): every account and every// project on this instance. It reads across the better-auth tables (user, session,@@ -370,19 +373,22 @@ async function countByTeamOfProject(return new Map(rows.map((r) => [r.projectId, r.count]));}-// How many rows each of the given projects has in a project-scoped table.-async function countByProject(+const countAt = (counts: Map<number, number>, id: number) => counts.get(id) ?? 0;++// How many rows each of the given owners has in a table that points at them, keyed by+// the owner id: a project-scoped table by project, a team-scoped one by team.+async function countByOwner(table: PgTable,- projectIdColumn: AnyPgColumn,- projectIds: number[],+ ownerIdColumn: AnyPgColumn,+ ownerIds: number[],extra?: SQL,): Promise<Map<number, number>> {const rows = await db- .select({ projectId: projectIdColumn, count: sql<number>`count(*)::int` })+ .select({ ownerId: ownerIdColumn, count: sql<number>`count(*)::int` }).from(table)- .where(and(inArray(projectIdColumn, projectIds), extra))- .groupBy(projectIdColumn);- return new Map(rows.map((r) => [r.projectId as number, r.count]));+ .where(and(inArray(ownerIdColumn, ownerIds), extra))+ .groupBy(ownerIdColumn);+ return new Map(rows.map((r) => [r.ownerId as number, r.count]));}type ProjectFacts = InstanceProjectCounts & { lastActivityAt: string | null };@@ -404,7 +410,6 @@ const EMPTY_FACTS: ProjectFacts = {// query and joined in memory, so the project query stays a plain select.async function loadProjectFacts(projectIds: number[]): Promise<(id: number) => ProjectFacts> {if (projectIds.length === 0) return () => EMPTY_FACTS;- const counts = (map: Map<number, number>, id: number) => map.get(id) ?? 0;const [members,@@ -418,15 +423,15 @@ async function loadProjectFacts(projectIds: number[]): Promise<(id: number) => Ptools,activityRows,] = await Promise.all([- countByProject(projectMember, projectMember.projectId, projectIds),- countByProject(issue, issue.projectId, projectIds, isNull(issue.archivedAt)),- countByProject(issue, issue.projectId, projectIds, isNotNull(issue.archivedAt)),- countByProject(initiative, initiative.projectId, projectIds),- countByProject(projectDashboard, projectDashboard.projectId, projectIds),- countByProject(projectView, projectView.projectId, projectIds),+ countByOwner(projectMember, projectMember.projectId, projectIds),+ countByOwner(issue, issue.projectId, projectIds, isNull(issue.archivedAt)),+ countByOwner(issue, issue.projectId, projectIds, isNotNull(issue.archivedAt)),+ countByOwner(initiative, initiative.projectId, projectIds),+ countByOwner(projectDashboard, projectDashboard.projectId, projectIds),+ countByOwner(projectView, projectView.projectId, projectIds),// An agent belongs to a team and works in the projects it is a member of, so the// count per project is its memberships, not its own rows.- countByProject(+ countByOwner(projectMember,projectMember.projectId,projectIds,@@ -453,15 +458,15 @@ async function loadProjectFacts(projectIds: number[]): Promise<(id: number) => Preturn (id: number): ProjectFacts => {const activeAt = lastActivity.get(id);return {- memberCount: counts(members, id),- issueCount: counts(issues, id),- archivedIssueCount: counts(archivedIssues, id),- initiativeCount: counts(initiatives, id),- dashboardCount: counts(dashboards, id),- viewCount: counts(views, id),- agentCount: counts(agents, id),- skillCount: counts(skills, id),- toolCount: counts(tools, id),+ memberCount: countAt(members, id),+ issueCount: countAt(issues, id),+ archivedIssueCount: countAt(archivedIssues, id),+ initiativeCount: countAt(initiatives, id),+ dashboardCount: countAt(dashboards, id),+ viewCount: countAt(views, id),+ agentCount: countAt(agents, id),+ skillCount: countAt(skills, id),+ toolCount: countAt(tools, id),lastActivityAt: activeAt ? iso(activeAt) : null,};};@@ -567,6 +572,253 @@ export async function getInstanceProject(projectId: number): Promise<InstancePro};}+// ── Team directory ───────────────────────────────────────────────────────────++// What a team holds, counted across the tables it owns and the projects it owns.+// Read for the list and the detail alike, so a row in the directory already carries+// everything.+export interface InstanceTeamCounts {+ memberCount: number;+ projectCount: number;+ issueCount: number;+ agentCount: number;+ skillCount: number;+ toolCount: number;+ roleCount: number;+}++export interface InstanceTeamRow extends InstanceTeamCounts {+ id: number;+ name: string;+ mcpEnabled: boolean;+ createdAt: string;+}++export interface InstanceTeamProject {+ id: number;+ key: string;+ name: string;+ mcpEnabled: boolean;+ memberCount: number;+ issueCount: number;+ createdAt: string;+}++// One member of the team. The role is the fixed team rank, not a project role, and+// 'agent' is the bot user of an ai_agent.+export interface InstanceTeamMember {+ userId: string;+ name: string;+ email: string;+ image: string | null;+ isAgent: boolean;+ role: TeamStanding;+ joinedAt: string;+}++export interface InstanceTeamPage {+ items: InstanceTeamRow[];+ // How many teams match the search, ignoring the page window.+ total: number;+}++export interface InstanceTeamProjectPage {+ items: InstanceTeamProject[];+ total: number;+}++export interface InstanceTeamMemberPage {+ items: InstanceTeamMember[];+ total: number;+}++const EMPTY_TEAM_COUNTS: InstanceTeamCounts = {+ memberCount: 0,+ projectCount: 0,+ issueCount: 0,+ agentCount: 0,+ skillCount: 0,+ toolCount: 0,+ roleCount: 0,+};++// The counts for the given teams, each in one grouped query and joined in memory,+// so the team query stays a plain select.+async function loadTeamCounts(teamIds: number[]): Promise<(id: number) => InstanceTeamCounts> {+ if (teamIds.length === 0) return () => EMPTY_TEAM_COUNTS;++ const [members, projects, issues, agents, skills, tools, roles] = await Promise.all([+ countByOwner(teamMember, teamMember.teamId, teamIds),+ countByOwner(project, project.teamId, teamIds),+ // Issues have no team column; they reach one through their project.+ db+ .select({ teamId: project.teamId, count: sql<number>`count(*)::int` })+ .from(issue)+ .innerJoin(project, eq(project.id, issue.projectId))+ .where(and(inArray(project.teamId, teamIds), isNull(issue.archivedAt)))+ .groupBy(project.teamId)+ .then((rows) => new Map(rows.map((r) => [r.teamId, r.count]))),+ countByOwner(aiAgent, aiAgent.teamId, teamIds),+ countByOwner(agentSkill, agentSkill.teamId, teamIds),+ countByOwner(agentTool, agentTool.teamId, teamIds),+ countByOwner(teamRole, teamRole.teamId, teamIds),+ ]);++ return (id) => ({+ memberCount: countAt(members, id),+ projectCount: countAt(projects, id),+ issueCount: countAt(issues, id),+ agentCount: countAt(agents, id),+ skillCount: countAt(skills, id),+ toolCount: countAt(tools, id),+ roleCount: countAt(roles, id),+ });+}++type TeamRow = typeof team.$inferSelect;++function toTeamRow(r: TeamRow, counts: InstanceTeamCounts): InstanceTeamRow {+ return {+ id: r.id,+ name: r.name,+ mcpEnabled: r.mcpEnabled,+ createdAt: iso(r.createdAt),+ ...counts,+ };+}++// One page of teams, newest first. `search` matches the name and runs in SQL, so the+// page window and the total count agree.+export async function listInstanceTeams(options: {+ search?: string;+ limit: number;+ offset: number;+}): Promise<InstanceTeamPage> {+ const term = options.search?.trim();+ const where = term ? ilike(team.name, `%${term}%`) : undefined;++ const [rows, totals] = await Promise.all([+ db+ .select()+ .from(team)+ .where(where)+ .orderBy(desc(team.createdAt))+ .limit(options.limit)+ .offset(options.offset),+ db+ .select({ count: sql<number>`count(*)::int` })+ .from(team)+ .where(where),+ ]);++ const counts = await loadTeamCounts(rows.map((r) => r.id));+ return { items: rows.map((r) => toTeamRow(r, counts(r.id))), total: totals[0]?.count ?? 0 };+}++// One team with what it holds. Its projects and its members are their own paged+// routes, so a large team is never loaded whole. Returns null for an unknown id.+export async function getInstanceTeam(teamId: number): Promise<InstanceTeamRow | null> {+ const rows = await db.select().from(team).where(eq(team.id, teamId));+ const row = rows[0];+ if (!row) return null;++ const counts = await loadTeamCounts([row.id]);+ return toTeamRow(row, counts(row.id));+}++// One page of the projects a team owns, by key. `search` matches the key or the name.+export async function listInstanceTeamProjects(+ teamId: number,+ options: { search?: string; limit: number; offset: number },+): Promise<InstanceTeamProjectPage> {+ const term = options.search?.trim();+ const where = and(+ eq(project.teamId, teamId),+ term ? or(ilike(project.key, `%${term}%`), ilike(project.name, `%${term}%`)) : undefined,+ );++ const [rows, totals] = await Promise.all([+ db+ .select({+ id: project.id,+ key: project.key,+ name: project.name,+ mcpEnabled: project.mcpEnabled,+ createdAt: project.createdAt,+ memberCount: sql<number>`count(distinct ${projectMember.userId})::int`,+ issueCount: sql<number>`count(distinct ${issue.id})::int`,+ })+ .from(project)+ .leftJoin(projectMember, eq(projectMember.projectId, project.id))+ .leftJoin(issue, and(eq(issue.projectId, project.id), isNull(issue.archivedAt)))+ .where(where)+ .groupBy(project.id)+ .orderBy(project.key)+ .limit(options.limit)+ .offset(options.offset),+ db+ .select({ count: sql<number>`count(*)::int` })+ .from(project)+ .where(where),+ ]);++ return {+ items: rows.map((p) => ({ ...p, createdAt: iso(p.createdAt) })),+ total: totals[0]?.count ?? 0,+ };+}++// One page of the team's members, people and agents alike, by name. `search` matches+// the name or the address.+export async function listInstanceTeamMembers(+ teamId: number,+ options: { search?: string; limit: number; offset: number },+): Promise<InstanceTeamMemberPage> {+ const term = options.search?.trim();+ const where = and(+ eq(teamMember.teamId, teamId),+ term ? or(ilike(user.name, `%${term}%`), ilike(user.email, `%${term}%`)) : undefined,+ );++ const [rows, totals] = await Promise.all([+ db+ .select({+ userId: user.id,+ name: user.name,+ email: user.email,+ image: user.image,+ agentId: aiAgent.id,+ role: teamMember.role,+ joinedAt: teamMember.createdAt,+ })+ .from(teamMember)+ .innerJoin(user, eq(user.id, teamMember.userId))+ .leftJoin(aiAgent, eq(aiAgent.userId, teamMember.userId))+ .where(where)+ .orderBy(user.name)+ .limit(options.limit)+ .offset(options.offset),+ db+ .select({ count: sql<number>`count(*)::int` })+ .from(teamMember)+ .innerJoin(user, eq(user.id, teamMember.userId))+ .where(where),+ ]);++ return {+ items: rows.map((m) => ({+ userId: m.userId,+ name: m.name,+ email: m.email,+ image: m.image,+ isAgent: m.agentId !== null,+ role: m.role as TeamStanding,+ joinedAt: iso(m.joinedAt),+ })),+ total: totals[0]?.count ?? 0,+ };+}+// Marks the account's email address as confirmed and returns the updated user.// Returns null for an unknown id.export async function verifyInstanceUserEmail(userId: string): Promise<InstanceUserDetail | null> {diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.jsonindex b6768fd1..b2eb8c76 100644--- a/apps/web/messages/ar/god.json+++ b/apps/web/messages/ar/god.json@@ -106,6 +106,55 @@"noMembersTitle": "لا يوجد أعضاء","noMembersHint": "محدش هيقدر يوصل للمشروع ده لحد ما حد يتدعى ليه."},+ "teams": {+ "empty": "لا توجد فرق مطابقة لهذا البحث.",+ "searchPlaceholder": "ابحث بالاسم",+ "columns": {+ "team": "الفريق",+ "projects": "المشاريع",+ "members": "الأعضاء",+ "issues": "المهام",+ "agents": "الوكلاء",+ "mcp": "MCP"+ },+ "mcpEnabled": "مفعّل",+ "mcpOff": "معطّل",+ "open": "فتح الفريق",+ "showDetails": "عرض تفاصيل الفريق"+ },+ "teamPanel": {+ "mcpEnabled": "MCP مفعّل",+ "mcpOff": "MCP معطّل",+ "created": "أُنشئ في {date}",+ "statTitle": "{label}: {value}",+ "stats": {+ "projects": "المشاريع",+ "issues": "المهام",+ "members": "الأعضاء",+ "agents": "وكلاء الذكاء الاصطناعي",+ "skills": "المهارات",+ "tools": "الأدوات",+ "roles": "أدوار المشاريع"+ },+ "projects": "المشاريع",+ "searchProjects": "ابحث في المشاريع",+ "projectCounts": "{issues} مهمة · {members} عضو",+ "noProjectsTitle": "لا توجد مشاريع",+ "noProjectsHint": "هذا الفريق لا يملك أي مشاريع بعد.",+ "noProjectMatches": "لا توجد مشاريع مطابقة لهذا البحث.",+ "members": "الأعضاء",+ "searchMembers": "ابحث في الأعضاء",+ "noMembersTitle": "لا يوجد أعضاء",+ "noMembersHint": "لا ينتمي أحد إلى هذا الفريق بعد.",+ "noMemberMatches": "لا يوجد أعضاء مطابقون لهذا البحث.",+ "roles": {+ "owner": "المالك",+ "manager": "المدير",+ "member": "عضو",+ "agent": "وكيل"+ },+ "joined": "انضم في {date}"+ },"general": {"saved": "تم حفظ الإعدادات الافتراضية","projectDefaults": "الإعدادات الافتراضية",diff --git a/apps/web/messages/ar/sections.json b/apps/web/messages/ar/sections.jsonindex 4bdf4f1b..3df2c6a0 100644--- a/apps/web/messages/ar/sections.json+++ b/apps/web/messages/ar/sections.json@@ -15,6 +15,10 @@"label": "المستخدمون","description": "كل حساب على النسخة دي: الدور العام، والعنوان اتأكّد ولا لأ، والمشاريع اللي كل مستخدم يقدر يدخلها."},+ "teams": {+ "label": "الفرق",+ "description": "كل الفرق في هذه النسخة: المشاريع التي تملكها ومن ينتمي إليها."+ },"projects": {"label": "المشاريع","description": "كل مشروع على النسخة دي: كل واحد فيه إيه، وآخر مرة كان نشط فيها، ومين يقدر يدخله."diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.jsonindex 54b29cd1..fa3bff02 100644--- a/apps/web/messages/en/god.json+++ b/apps/web/messages/en/god.json@@ -106,6 +106,55 @@"noMembersTitle": "No members","noMembersHint": "Nobody can reach this project until someone is invited to it."},+ "teams": {+ "empty": "No teams match this search.",+ "searchPlaceholder": "Search by name",+ "columns": {+ "team": "Team",+ "projects": "Projects",+ "members": "Members",+ "issues": "Issues",+ "agents": "Agents",+ "mcp": "MCP"+ },+ "mcpEnabled": "Enabled",+ "mcpOff": "Off",+ "open": "Open team",+ "showDetails": "Show team details"+ },+ "teamPanel": {+ "mcpEnabled": "MCP enabled",+ "mcpOff": "MCP off",+ "created": "created {date}",+ "statTitle": "{label}: {value}",+ "stats": {+ "projects": "Projects",+ "issues": "Issues",+ "members": "Members",+ "agents": "AI agents",+ "skills": "Skills",+ "tools": "Tools",+ "roles": "Project roles"+ },+ "projects": "Projects",+ "searchProjects": "Search projects",+ "projectCounts": "{issues} issues · {members} members",+ "noProjectsTitle": "No projects",+ "noProjectsHint": "This team owns no projects yet.",+ "noProjectMatches": "No projects match this search.",+ "members": "Members",+ "searchMembers": "Search members",+ "noMembersTitle": "No members",+ "noMembersHint": "Nobody belongs to this team yet.",+ "noMemberMatches": "No members match this search.",+ "roles": {+ "owner": "Owner",+ "manager": "Manager",+ "member": "Member",+ "agent": "Agent"+ },+ "joined": "joined {date}"+ },"general": {"saved": "Project defaults saved","projectDefaults": "Project defaults",diff --git a/apps/web/messages/en/sections.json b/apps/web/messages/en/sections.jsonindex 39379966..3154261b 100644--- a/apps/web/messages/en/sections.json+++ b/apps/web/messages/en/sections.json@@ -15,6 +15,10 @@"label": "Users","description": "Every account on this instance: the global role, whether the address is confirmed, and the projects each user can reach."},+ "teams": {+ "label": "Teams",+ "description": "Every team on this instance: the projects it owns and who belongs to it."+ },"projects": {"label": "Projects","description": "Every project on this instance: what each one holds, when it was last active, and who can reach it."diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.jsonindex ffa2c8a9..75240e8c 100644--- a/apps/web/messages/fr/god.json+++ b/apps/web/messages/fr/god.json@@ -106,6 +106,55 @@"noMembersTitle": "Aucun membre","noMembersHint": "Personne ne peut accéder à ce projet tant que personne n'y est invité."},+ "teams": {+ "empty": "Aucune équipe ne correspond à cette recherche.",+ "searchPlaceholder": "Rechercher par nom",+ "columns": {+ "team": "Équipe",+ "projects": "Projets",+ "members": "Membres",+ "issues": "Tickets",+ "agents": "Agents",+ "mcp": "MCP"+ },+ "mcpEnabled": "Activé",+ "mcpOff": "Désactivé",+ "open": "Ouvrir l'équipe",+ "showDetails": "Afficher les détails de l'équipe"+ },+ "teamPanel": {+ "mcpEnabled": "MCP activé",+ "mcpOff": "MCP désactivé",+ "created": "créée {date}",+ "statTitle": "{label} : {value}",+ "stats": {+ "projects": "Projets",+ "issues": "Tickets",+ "members": "Membres",+ "agents": "Agents IA",+ "skills": "Compétences",+ "tools": "Outils",+ "roles": "Rôles de projet"+ },+ "projects": "Projets",+ "searchProjects": "Rechercher des projets",+ "projectCounts": "{issues} tickets · {members} membres",+ "noProjectsTitle": "Aucun projet",+ "noProjectsHint": "Cette équipe ne possède encore aucun projet.",+ "noProjectMatches": "Aucun projet ne correspond à cette recherche.",+ "members": "Membres",+ "searchMembers": "Rechercher des membres",+ "noMembersTitle": "Aucun membre",+ "noMembersHint": "Personne n'appartient encore à cette équipe.",+ "noMemberMatches": "Aucun membre ne correspond à cette recherche.",+ "roles": {+ "owner": "Propriétaire",+ "manager": "Gestionnaire",+ "member": "Membre",+ "agent": "Agent"+ },+ "joined": "a rejoint le {date}"+ },"general": {"saved": "Valeurs par défaut des projets enregistrées","projectDefaults": "Valeurs par défaut des projets",diff --git a/apps/web/messages/fr/sections.json b/apps/web/messages/fr/sections.jsonindex d786b84d..f10eb88a 100644--- a/apps/web/messages/fr/sections.json+++ b/apps/web/messages/fr/sections.json@@ -15,6 +15,10 @@"label": "Utilisateurs","description": "Tous les comptes de cette instance : le rôle global, si l'adresse est confirmée, et les projets auxquels chaque utilisateur a accès."},+ "teams": {+ "label": "Équipes",+ "description": "Toutes les équipes de cette instance : les projets qu'elle possède et qui en fait partie."+ },"projects": {"label": "Projets","description": "Tous les projets de cette instance : ce que chacun contient, sa dernière activité, et qui peut y accéder."diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.jsonindex b3ed08c4..75b5dd1b 100644--- a/apps/web/messages/pt-BR/god.json+++ b/apps/web/messages/pt-BR/god.json@@ -106,6 +106,55 @@"noMembersTitle": "Sem membros","noMembersHint": "Ninguém pode alcançar este projeto até que alguém seja convidado."},+ "teams": {+ "empty": "Nenhuma equipe corresponde a esta busca.",+ "searchPlaceholder": "Buscar por nome",+ "columns": {+ "team": "Equipe",+ "projects": "Projetos",+ "members": "Membros",+ "issues": "Issues",+ "agents": "Agentes",+ "mcp": "MCP"+ },+ "mcpEnabled": "Ativado",+ "mcpOff": "Desativado",+ "open": "Abrir equipe",+ "showDetails": "Mostrar detalhes da equipe"+ },+ "teamPanel": {+ "mcpEnabled": "MCP ativado",+ "mcpOff": "MCP desativado",+ "created": "criada em {date}",+ "statTitle": "{label}: {value}",+ "stats": {+ "projects": "Projetos",+ "issues": "Issues",+ "members": "Membros",+ "agents": "Agentes de IA",+ "skills": "Habilidades",+ "tools": "Ferramentas",+ "roles": "Papéis de projeto"+ },+ "projects": "Projetos",+ "searchProjects": "Buscar projetos",+ "projectCounts": "{issues} issues · {members} membros",+ "noProjectsTitle": "Sem projetos",+ "noProjectsHint": "Esta equipe ainda não possui projetos.",+ "noProjectMatches": "Nenhum projeto corresponde a esta busca.",+ "members": "Membros",+ "searchMembers": "Buscar membros",+ "noMembersTitle": "Sem membros",+ "noMembersHint": "Ninguém pertence a esta equipe ainda.",+ "noMemberMatches": "Nenhum membro corresponde a esta busca.",+ "roles": {+ "owner": "Proprietário",+ "manager": "Gerente",+ "member": "Membro",+ "agent": "Agente"+ },+ "joined": "entrou em {date}"+ },"general": {"saved": "Padrões de projeto salvos","projectDefaults": "Padrões de projeto",diff --git a/apps/web/messages/pt-BR/sections.json b/apps/web/messages/pt-BR/sections.jsonindex 8903a56c..62216ab0 100644--- a/apps/web/messages/pt-BR/sections.json+++ b/apps/web/messages/pt-BR/sections.json@@ -15,6 +15,10 @@"label": "Usuários","description": "Toda conta nesta instância: a função global, se o endereço está confirmado e os projetos que cada usuário alcança."},+ "teams": {+ "label": "Equipes",+ "description": "Todas as equipes desta instância: os projetos que possui e quem faz parte dela."+ },"projects": {"label": "Projetos","description": "Todo projeto nesta instância: o que cada um contém, quando esteve ativo pela última vez e quem pode alcançá-lo."diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.jsonindex 6d61c5dc..b2c15d11 100644--- a/apps/web/messages/ru/god.json+++ b/apps/web/messages/ru/god.json@@ -106,6 +106,55 @@"noMembersTitle": "Нет участников","noMembersHint": "Никто не видит этот проект, пока кого-нибудь не пригласят."},+ "teams": {+ "empty": "Нет команд по этому запросу.",+ "searchPlaceholder": "Поиск по названию",+ "columns": {+ "team": "Команда",+ "projects": "Проекты",+ "members": "Участники",+ "issues": "Задачи",+ "agents": "Агенты",+ "mcp": "MCP"+ },+ "mcpEnabled": "Включено",+ "mcpOff": "Выключено",+ "open": "Открыть команду",+ "showDetails": "Показать детали команды"+ },+ "teamPanel": {+ "mcpEnabled": "MCP включён",+ "mcpOff": "MCP выключен",+ "created": "создана {date}",+ "statTitle": "{label}: {value}",+ "stats": {+ "projects": "Проекты",+ "issues": "Задачи",+ "members": "Участники",+ "agents": "AI-агенты",+ "skills": "Навыки",+ "tools": "Инструменты",+ "roles": "Роли в проектах"+ },+ "projects": "Проекты",+ "searchProjects": "Поиск проектов",+ "projectCounts": "{issues} задач · {members} участников",+ "noProjectsTitle": "Нет проектов",+ "noProjectsHint": "У этой команды пока нет проектов.",+ "noProjectMatches": "Нет проектов по этому запросу.",+ "members": "Участники",+ "searchMembers": "Поиск участников",+ "noMembersTitle": "Нет участников",+ "noMembersHint": "В этой команде пока никого нет.",+ "noMemberMatches": "Нет участников по этому запросу.",+ "roles": {+ "owner": "Владелец",+ "manager": "Менеджер",+ "member": "Участник",+ "agent": "Агент"+ },+ "joined": "вступил {date}"+ },"general": {"saved": "Настройки по умолчанию сохранены","projectDefaults": "Настройки по умолчанию",diff --git a/apps/web/messages/ru/sections.json b/apps/web/messages/ru/sections.jsonindex 249ded18..432ec31a 100644--- a/apps/web/messages/ru/sections.json+++ b/apps/web/messages/ru/sections.json@@ -15,6 +15,10 @@"label": "Пользователи","description": "Все аккаунты этого инстанса: глобальная роль, подтверждён ли адрес и к каким проектам есть доступ у каждого пользователя."},+ "teams": {+ "label": "Команды",+ "description": "Все команды инстанса: какие проекты ей принадлежат и кто в неё входит."+ },"projects": {"label": "Проекты","description": "Все проекты этого инстанса: что в каждом, когда была последняя активность и у кого есть доступ."diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.jsonindex 6dd9f603..2887f8c2 100644--- a/apps/web/messages/uk/god.json+++ b/apps/web/messages/uk/god.json@@ -106,6 +106,55 @@"noMembersTitle": "Немає учасників","noMembersHint": "Ніхто не бачить цей проєкт, доки когось не запросять."},+ "teams": {+ "empty": "Немає команд за цим запитом.",+ "searchPlaceholder": "Пошук за назвою",+ "columns": {+ "team": "Команда",+ "projects": "Проєкти",+ "members": "Учасники",+ "issues": "Задачі",+ "agents": "Агенти",+ "mcp": "MCP"+ },+ "mcpEnabled": "Увімкнено",+ "mcpOff": "Вимкнено",+ "open": "Відкрити команду",+ "showDetails": "Показати деталі команди"+ },+ "teamPanel": {+ "mcpEnabled": "MCP увімкнено",+ "mcpOff": "MCP вимкнено",+ "created": "створено {date}",+ "statTitle": "{label}: {value}",+ "stats": {+ "projects": "Проєкти",+ "issues": "Задачі",+ "members": "Учасники",+ "agents": "AI-агенти",+ "skills": "Навички",+ "tools": "Інструменти",+ "roles": "Ролі в проєктах"+ },+ "projects": "Проєкти",+ "searchProjects": "Пошук проєктів",+ "projectCounts": "{issues} задач · {members} учасників",+ "noProjectsTitle": "Немає проєктів",+ "noProjectsHint": "У цієї команди поки немає проєктів.",+ "noProjectMatches": "Немає проєктів за цим запитом.",+ "members": "Учасники",+ "searchMembers": "Пошук учасників",+ "noMembersTitle": "Немає учасників",+ "noMembersHint": "У цій команді поки нікого немає.",+ "noMemberMatches": "Немає учасників за цим запитом.",+ "roles": {+ "owner": "Власник",+ "manager": "Менеджер",+ "member": "Учасник",+ "agent": "Агент"+ },+ "joined": "приєднався {date}"+ },"general": {"saved": "Налаштування за замовчуванням збережено","projectDefaults": "Налаштування за замовчуванням",diff --git a/apps/web/messages/uk/sections.json b/apps/web/messages/uk/sections.jsonindex a16b8541..e4ee5f02 100644--- a/apps/web/messages/uk/sections.json+++ b/apps/web/messages/uk/sections.json@@ -15,6 +15,10 @@"label": "Користувачі","description": "Усі акаунти цього інстансу: глобальна роль, чи підтверджена адреса, і до яких проєктів має доступ кожен користувач."},+ "teams": {+ "label": "Команди",+ "description": "Усі команди інстансу: які проєкти їй належать і хто до неї входить."+ },"projects": {"label": "Проєкти","description": "Усі проєкти цього інстансу: що в кожному, коли була остання активність і хто має доступ."diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.jsonindex 529477d1..40d84363 100644--- a/apps/web/messages/zh-CN/god.json+++ b/apps/web/messages/zh-CN/god.json@@ -106,6 +106,55 @@"noMembersTitle": "暂无成员","noMembersHint": "需要邀请成员后才能访问此项目。"},+ "teams": {+ "empty": "没有符合搜索条件的团队。",+ "searchPlaceholder": "按名称搜索",+ "columns": {+ "team": "团队",+ "projects": "项目",+ "members": "成员",+ "issues": "工作项",+ "agents": "代理",+ "mcp": "MCP"+ },+ "mcpEnabled": "已启用",+ "mcpOff": "已关闭",+ "open": "打开团队",+ "showDetails": "查看团队详情"+ },+ "teamPanel": {+ "mcpEnabled": "MCP 已启用",+ "mcpOff": "MCP 已关闭",+ "created": "创建于 {date}",+ "statTitle": "{label}:{value}",+ "stats": {+ "projects": "项目",+ "issues": "工作项",+ "members": "成员",+ "agents": "AI 代理",+ "skills": "技能",+ "tools": "工具",+ "roles": "项目角色"+ },+ "projects": "项目",+ "searchProjects": "搜索项目",+ "projectCounts": "{issues} 个工作项 · {members} 名成员",+ "noProjectsTitle": "暂无项目",+ "noProjectsHint": "该团队还没有项目。",+ "noProjectMatches": "没有符合搜索条件的项目。",+ "members": "成员",+ "searchMembers": "搜索成员",+ "noMembersTitle": "暂无成员",+ "noMembersHint": "该团队还没有任何成员。",+ "noMemberMatches": "没有符合搜索条件的成员。",+ "roles": {+ "owner": "所有者",+ "manager": "管理员",+ "member": "成员",+ "agent": "代理"+ },+ "joined": "加入于 {date}"+ },"general": {"saved": "项目默认设置已保存","projectDefaults": "项目默认设置",diff --git a/apps/web/messages/zh-CN/sections.json b/apps/web/messages/zh-CN/sections.jsonindex e1fc06ed..869da947 100644--- a/apps/web/messages/zh-CN/sections.json+++ b/apps/web/messages/zh-CN/sections.json@@ -15,6 +15,10 @@"label": "用户","description": "此实例中的所有账户,包括全局角色、邮箱验证状态和各用户可访问的项目。"},+ "teams": {+ "label": "团队",+ "description": "实例中的所有团队:拥有哪些项目,以及谁属于它。"+ },"projects": {"label": "项目","description": "此实例中的所有项目,包括项目内容、最近活动时间和访问成员。"diff --git a/apps/web/src/app/god/teams/page.tsx b/apps/web/src/app/god/teams/page.tsxnew file mode 100644index 00000000..65f30df0--- /dev/null+++ b/apps/web/src/app/god/teams/page.tsx@@ -0,0 +1,5 @@+import GodTeamsPage from '@/features/god/GodTeamsPage';++export default function Page() {+ return <GodTeamsPage />;+}diff --git a/apps/web/src/features/god/GodTeamsPage.tsx b/apps/web/src/features/god/GodTeamsPage.tsxnew file mode 100644index 00000000..d9d6fcd3--- /dev/null+++ b/apps/web/src/features/god/GodTeamsPage.tsx@@ -0,0 +1,61 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { useDebouncedValue } from '@/hooks/useDebouncedValue';+import { usePaging } from '@/hooks/usePaging';+import ListPager from '@/components/common/ListPager';+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import SearchInput from '@/components/common/SearchInput';+import GodSectionPage from './components/GodSectionPage';+import GodTeamDetailPanel from './components/teams/GodTeamDetailPanel';+import GodTeamsTable from './components/teams/GodTeamsTable';+import { useInstanceTeamsQuery } from './services/god.service';++// The instance team directory: one row per team with what it holds, and a side panel+// showing the projects it owns and everyone in it. Search and paging run on the+// server, like the user and project directories.+export default function GodTeamsPage() {+ const t = useTranslations('god.teams');+ const [search, setSearch] = useState('');+ const paging = usePaging(25);+ const [selected, setSelected] = useState<number | null>(null);++ // Typing refetches, so wait for a pause instead of firing per keystroke.+ const debouncedSearch = useDebouncedValue(search, 300);++ const teamsQuery = useInstanceTeamsQuery({ search: debouncedSearch, ...paging.params });+ const teams = teamsQuery.data?.items ?? [];+ const total = teamsQuery.data?.total ?? 0;++ return (+ <GodSectionPage slug="teams" widthClassName="max-w-none">+ <div className="space-y-4">+ <SearchInput+ value={search}+ onChange={(value) => {+ setSearch(value);+ paging.reset();+ }}+ placeholder={t('searchPlaceholder')}+ className="max-w-md min-w-[240px]"+ />++ {teamsQuery.isPending ? (+ <ListSkeleton rows={6} rowClassName="h-12" />+ ) : total === 0 ? (+ <p className="text-sm text-muted-foreground">{t('empty')}</p>+ ) : (+ <>+ <GodTeamsTable teams={teams} onSelect={setSelected} />+ <ListPager paging={paging} total={total} />+ </>+ )}+ </div>++ {selected !== null && (+ <GodTeamDetailPanel teamId={selected} onClose={() => setSelected(null)} />+ )}+ </GodSectionPage>+ );+}diff --git a/apps/web/src/features/god/components/teams/GodTeamDetailPanel.tsx b/apps/web/src/features/god/components/teams/GodTeamDetailPanel.tsxnew file mode 100644index 00000000..d7c3bef8--- /dev/null+++ b/apps/web/src/features/god/components/teams/GodTeamDetailPanel.tsx@@ -0,0 +1,112 @@+'use client';++import { X } from 'lucide-react';+import { useTranslations } from 'next-intl';+import type { InstanceTeam } from '@/lib/api/endpoints/god';+import { formatDate } from '@/utils/dates';+import { useExitOnEscape } from '@/hooks/useExitOnEscape';+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { useInstanceTeamQuery } from '../../services/god.service';+import { compactCount } from '../../utils/numbers';+import GodTeamMembers from './GodTeamMembers';+import GodTeamProjects from './GodTeamProjects';++// One number from the team, with a quiet label under it. The counts read as a grid so+// the size of a team is one glance rather than a list of sentences.+function Stat({ label, value }: { label: string; value: number }) {+ const t = useTranslations('god.teamPanel');+ return (+ <div className="rounded-lg bg-muted/40 px-3 py-2.5" title={t('statTitle', { label, value })}>+ <div className="text-lg font-semibold tabular-nums">{compactCount(value)}</div>+ <div className="text-xs text-muted-foreground">{label}</div>+ </div>+ );+}++// The counts of a team, in the order they matter: the work first, then what is+// configured around it.+const STATS = [+ { key: 'projects', count: (team: InstanceTeam) => team.projectCount },+ { key: 'issues', count: (team: InstanceTeam) => team.issueCount },+ { key: 'members', count: (team: InstanceTeam) => team.memberCount },+ { key: 'agents', count: (team: InstanceTeam) => team.agentCount },+ { key: 'skills', count: (team: InstanceTeam) => team.skillCount },+ { key: 'tools', count: (team: InstanceTeam) => team.toolCount },+ { key: 'roles', count: (team: InstanceTeam) => team.roleCount },+] as const;++// One team in a right-hand side panel (the same surface the user and project+// directories use): what the team holds, the projects it owns and everyone in it,+// each list searched and paged on its own. Escape or a backdrop click closes it.+export default function GodTeamDetailPanel({+ teamId,+ onClose,+}: {+ teamId: number;+ onClose: () => void;+}) {+ const t = useTranslations('god.teamPanel');+ const tCommon = useTranslations('common');+ const teamQuery = useInstanceTeamQuery(teamId);+ const team = teamQuery.data;++ useExitOnEscape(onClose);++ return (+ <div+ className="fixed inset-0 z-40 flex bg-black/20"+ onClick={(e) => e.target === e.currentTarget && onClose()}+ >+ <div className="ml-auto flex h-full w-full flex-col border-l bg-card sm:w-[680px] sm:max-w-[92vw]">+ <div className="flex shrink-0 items-start justify-between gap-3 bg-muted/30 px-6 pt-5 pb-4">+ <div className="min-w-0 space-y-1.5">+ <h2 className="truncate text-base font-semibold">+ {team ? team.name : tCommon('loading')}+ </h2>+ {team && (+ <div className="flex flex-wrap items-center gap-1.5">+ <Badge+ variant={team.mcpEnabled ? 'secondary' : 'outline'}+ className="px-1.5 py-0 text-[10px] font-medium"+ >+ {t(team.mcpEnabled ? 'mcpEnabled' : 'mcpOff')}+ </Badge>+ <span className="text-xs text-muted-foreground">+ {t('created', { date: formatDate(team.createdAt) })}+ </span>+ </div>+ )}+ </div>+ <Button+ variant="ghost"+ size="icon"+ className="size-7"+ onClick={onClose}+ title={tCommon('close')}+ >+ <X />+ </Button>+ </div>++ <div className="flex-1 space-y-8 overflow-y-auto px-6 py-6">+ {!team ? (+ <ListSkeleton rows={5} rowClassName="h-12" />+ ) : (+ <>+ <div className="grid grid-cols-3 gap-2 sm:grid-cols-4">+ {STATS.map((s) => (+ <Stat key={s.key} label={t(`stats.${s.key}`)} value={s.count(team)} />+ ))}+ </div>++ <GodTeamProjects teamId={teamId} />+ <GodTeamMembers teamId={teamId} />+ </>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/god/components/teams/GodTeamMembers.tsx b/apps/web/src/features/god/components/teams/GodTeamMembers.tsxnew file mode 100644index 00000000..27bc2efb--- /dev/null+++ b/apps/web/src/features/god/components/teams/GodTeamMembers.tsx@@ -0,0 +1,91 @@+'use client';++import { Bot } from 'lucide-react';+import { useTranslations } from 'next-intl';+import { formatShortDate } from '@/utils/dates';+import { useSearchTerm } from '@/hooks/useSearchTerm';+import Avatar from '@/components/common/Avatar';+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import { EmptyState } from '@/components/common/page/EmptyState';+import SearchInput from '@/components/common/SearchInput';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { useInstanceTeamMembersQuery } from '../../services/god.service';++// Everyone in the team, people and agents alike, a page at a time. The rank is the+// fixed team one, so there is no permission matrix to unfold behind the row.+export default function GodTeamMembers({ teamId }: { teamId: number }) {+ const t = useTranslations('god.teamPanel');+ const tCommon = useTranslations('common');+ const { search, setSearch, term } = useSearchTerm();++ const membersQuery = useInstanceTeamMembersQuery(teamId, term);+ const members = membersQuery.data?.pages.flatMap((page) => page.items) ?? [];+ const total = membersQuery.data?.pages[0]?.total ?? 0;++ return (+ <section className="space-y-3">+ <div className="flex items-center gap-2">+ <h3 className="text-sm font-medium">{t('members')}</h3>+ {total > 0 && <span className="text-xs text-muted-foreground">{total}</span>}+ </div>++ <SearchInput+ value={search}+ onChange={setSearch}+ placeholder={t('searchMembers')}+ className="w-full"+ />++ {membersQuery.isPending ? (+ <ListSkeleton rows={4} rowClassName="h-12" />+ ) : members.length === 0 ? (+ <EmptyState+ title={t('noMembersTitle')}+ description={term ? t('noMemberMatches') : t('noMembersHint')}+ />+ ) : (+ <>+ <div className="space-y-2">+ {members.map((m) => (+ <div+ key={m.userId}+ className="flex items-center gap-2.5 rounded-lg bg-muted/40 px-3 py-2.5"+ >+ <Avatar+ name={m.name || m.email}+ image={m.image}+ className="size-8 shrink-0 text-[11px]"+ />+ <div className="flex min-w-0 flex-1 flex-col">+ <span className="truncate text-sm">{m.name || m.email}</span>+ <span className="truncate text-xs text-muted-foreground">{m.email}</span>+ </div>+ <Badge+ variant={m.role === 'owner' ? 'default' : 'secondary'}+ className="gap-1 px-1.5 py-0 text-[10px] font-medium"+ >+ {m.isAgent && <Bot className="size-3" />}+ {t(`roles.${m.role}`)}+ </Badge>+ <span className="hidden text-xs text-muted-foreground sm:inline">+ {t('joined', { date: formatShortDate(m.joinedAt) })}+ </span>+ </div>+ ))}+ </div>+ {membersQuery.hasNextPage && (+ <Button+ variant="outline"+ className="w-full"+ disabled={membersQuery.isFetchingNextPage}+ onClick={() => void membersQuery.fetchNextPage()}+ >+ {tCommon('showMore')}+ </Button>+ )}+ </>+ )}+ </section>+ );+}diff --git a/apps/web/src/features/god/components/teams/GodTeamProjects.tsx b/apps/web/src/features/god/components/teams/GodTeamProjects.tsxnew file mode 100644index 00000000..445fa4be--- /dev/null+++ b/apps/web/src/features/god/components/teams/GodTeamProjects.tsx@@ -0,0 +1,86 @@+'use client';++import { useTranslations } from 'next-intl';+import { useSearchTerm } from '@/hooks/useSearchTerm';+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';+import { EmptyState } from '@/components/common/page/EmptyState';+import SearchInput from '@/components/common/SearchInput';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { useInstanceTeamProjectsQuery } from '../../services/god.service';+import { compactCount } from '../../utils/numbers';++// The projects a team owns, a page at a time. The search runs on the server, so it+// reaches the projects the loaded pages do not hold.+export default function GodTeamProjects({ teamId }: { teamId: number }) {+ const t = useTranslations('god.teamPanel');+ const tCommon = useTranslations('common');+ const { search, setSearch, term } = useSearchTerm();++ const projectsQuery = useInstanceTeamProjectsQuery(teamId, term);+ const projects = projectsQuery.data?.pages.flatMap((page) => page.items) ?? [];+ const total = projectsQuery.data?.pages[0]?.total ?? 0;++ return (+ <section className="space-y-3">+ <div className="flex items-center gap-2">+ <h3 className="text-sm font-medium">{t('projects')}</h3>+ {total > 0 && <span className="text-xs text-muted-foreground">{total}</span>}+ </div>++ <SearchInput+ value={search}+ onChange={setSearch}+ placeholder={t('searchProjects')}+ className="w-full"+ />++ {projectsQuery.isPending ? (+ <ListSkeleton rows={4} rowClassName="h-12" />+ ) : projects.length === 0 ? (+ <EmptyState+ title={t('noProjectsTitle')}+ description={term ? t('noProjectMatches') : t('noProjectsHint')}+ />+ ) : (+ <>+ <div className="space-y-2">+ {projects.map((p) => (+ <div+ key={p.id}+ className="flex flex-wrap items-center gap-2 rounded-lg bg-muted/40 px-3 py-2.5"+ >+ <span className="shrink-0 rounded bg-secondary px-1.5 py-0.5 text-xs font-medium text-secondary-foreground">+ {p.key}+ </span>+ <span className="min-w-0 flex-1 truncate text-sm">{p.name}</span>+ <Badge+ variant={p.mcpEnabled ? 'secondary' : 'outline'}+ className="px-1.5 py-0 text-[10px] font-medium"+ >+ {t(p.mcpEnabled ? 'mcpEnabled' : 'mcpOff')}+ </Badge>+ <span className="text-xs text-muted-foreground tabular-nums">+ {t('projectCounts', {+ issues: compactCount(p.issueCount),+ members: compactCount(p.memberCount),+ })}+ </span>+ </div>+ ))}+ </div>+ {projectsQuery.hasNextPage && (+ <Button+ variant="outline"+ className="w-full"+ disabled={projectsQuery.isFetchingNextPage}+ onClick={() => void projectsQuery.fetchNextPage()}+ >+ {tCommon('showMore')}+ </Button>+ )}+ </>+ )}+ </section>+ );+}diff --git a/apps/web/src/features/god/components/teams/GodTeamsTable.tsx b/apps/web/src/features/god/components/teams/GodTeamsTable.tsxnew file mode 100644index 00000000..7484fb00--- /dev/null+++ b/apps/web/src/features/god/components/teams/GodTeamsTable.tsx@@ -0,0 +1,123 @@+'use client';++import { Pencil } from 'lucide-react';+import { useTranslations } from 'next-intl';+import type { InstanceTeam } from '@/lib/api/endpoints/god';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { compactCount } from '../../utils/numbers';++// The team list. A row (or the pencil in its Actions cell) opens the team in the side+// panel, where the full counts, the projects and the member list are.+export default function GodTeamsTable({+ teams,+ onSelect,+}: {+ teams: InstanceTeam[];+ onSelect: (teamId: number) => void;+}) {+ const t = useTranslations('god.teams');+ const tCommon = useTranslations('common');++ return (+ <Table className="min-w-[900px] table-fixed">+ <colgroup>+ <col className="w-[34%]" />+ <col className="w-[11%]" />+ <col className="w-[11%]" />+ <col className="w-[11%]" />+ <col className="w-[11%]" />+ <col className="w-[14%]" />+ <col className="w-[8%]" />+ </colgroup>+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.team')}+ </TableHead>+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.projects')}+ </TableHead>+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.members')}+ </TableHead>+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.issues')}+ </TableHead>+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.agents')}+ </TableHead>+ <TableHead className="text-xs font-medium text-muted-foreground">+ {t('columns.mcp')}+ </TableHead>+ <TableHead className="text-right text-xs font-medium text-muted-foreground">+ {tCommon('actions')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {teams.map((team) => (+ <TableRow+ key={team.id}+ className="cursor-pointer"+ onClick={() => onSelect(team.id)}+ title={t('showDetails')}+ >+ <TableCell className="px-3 py-3">+ <span className="truncate text-sm font-medium">{team.name}</span>+ </TableCell>++ <TableCell className="px-3 py-3 text-sm tabular-nums" title={String(team.projectCount)}>+ {compactCount(team.projectCount)}+ </TableCell>++ <TableCell className="px-3 py-3 text-sm tabular-nums" title={String(team.memberCount)}>+ {compactCount(team.memberCount)}+ </TableCell>++ <TableCell className="px-3 py-3 text-sm tabular-nums" title={String(team.issueCount)}>+ {compactCount(team.issueCount)}+ </TableCell>++ <TableCell className="px-3 py-3 text-sm tabular-nums" title={String(team.agentCount)}>+ {compactCount(team.agentCount)}+ </TableCell>++ <TableCell className="px-3 py-3">+ <Badge+ variant={team.mcpEnabled ? 'secondary' : 'outline'}+ className="px-1.5 py-0 text-[10px] font-medium"+ >+ {t(team.mcpEnabled ? 'mcpEnabled' : 'mcpOff')}+ </Badge>+ </TableCell>++ <TableCell className="px-3 py-3 text-right">+ <Button+ variant="ghost"+ size="icon"+ className="size-8 text-muted-foreground"+ aria-label={t('open')}+ title={t('open')}+ onClick={(e) => {+ e.stopPropagation();+ onSelect(team.id);+ }}+ >+ <Pencil />+ </Button>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ );+}diff --git a/apps/web/src/features/god/services/god.service.ts b/apps/web/src/features/god/services/god.service.tsindex 3e909246..d795b89f 100644--- a/apps/web/src/features/god/services/god.service.ts+++ b/apps/web/src/features/god/services/god.service.ts@@ -1,9 +1,16 @@'use client';-import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import {+ keepPreviousData,+ useInfiniteQuery,+ useMutation,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query';import type { StorageSettingsPatch } from '@/lib/api/endpoints/settings';import type { ProjectDefaults } from '@/lib/api/endpoints/projects';-import type { PageParams } from '@/lib/api/core/paging';+import { nextPageParam, type PageParams } from '@/lib/api/core/paging';+import { DEFAULT_PAGE_SIZE } from '@/hooks/usePaging';import {type InstanceAuthSettingsPatch,type InstanceEmailSettingsPatch,@@ -32,6 +39,10 @@ import {listInstanceProjects,listInstanceProjectOptions,getInstanceProject,+ listInstanceTeams,+ getInstanceTeam,+ listInstanceTeamProjects,+ listInstanceTeamMembers,verifyInstanceUserEmail,} from '@/lib/api/endpoints/god';import {@@ -315,3 +326,47 @@ export function useVerifyInstanceUserEmail() {},});}++export interface InstanceTeamFilters extends PageParams {+ search: string;+}++// One page of the team directory. Like the project directory, the filters are part+// of the key and the previous page stays on screen while the next one loads.+export function useInstanceTeamsQuery(filters: InstanceTeamFilters) {+ return useQuery({+ queryKey: qk.instanceTeams(filters),+ queryFn: () => listInstanceTeams({ ...filters, search: filters.search || undefined }),+ placeholderData: keepPreviousData,+ });+}++// One team with its counts. Mounted only while a team is selected.+export function useInstanceTeamQuery(teamId: number) {+ return useQuery({+ queryKey: qk.instanceTeam(teamId),+ queryFn: () => getInstanceTeam(teamId),+ });+}++// The projects a team owns and the people in it, each a page at a time. The search+// runs on the server, so it reaches what the loaded pages do not hold.+export function useInstanceTeamProjectsQuery(teamId: number, search: string | undefined) {+ return useInfiniteQuery({+ queryKey: qk.instanceTeamProjects(teamId, { search }),+ queryFn: ({ pageParam }) =>+ listInstanceTeamProjects(teamId, { search, page: pageParam, pageSize: DEFAULT_PAGE_SIZE }),+ initialPageParam: 1,+ getNextPageParam: nextPageParam,+ });+}++export function useInstanceTeamMembersQuery(teamId: number, search: string | undefined) {+ return useInfiniteQuery({+ queryKey: qk.instanceTeamMembers(teamId, { search }),+ queryFn: ({ pageParam }) =>+ listInstanceTeamMembers(teamId, { search, page: pageParam, pageSize: DEFAULT_PAGE_SIZE }),+ initialPageParam: 1,+ getNextPageParam: nextPageParam,+ });+}diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.tsindex d5fbd2f5..888310b7 100644--- a/apps/web/src/lib/api/endpoints/god.ts+++ b/apps/web/src/lib/api/endpoints/god.ts@@ -1,5 +1,6 @@import { request } from '@/lib/api/core/client';import type { MemberRole } from '@/lib/api/endpoints/members';+import type { TeamRole } from '@/lib/api/endpoints/teams';import type { NotificationEncryption } from '@/lib/api/endpoints/notificationSettings';import type { Permissions } from '@/lib/api/endpoints/roles';import type { ProjectDefaults } from '@/lib/api/endpoints/projects';@@ -327,3 +328,63 @@ export const listInstanceProjectOptions = () =>export const getInstanceProject = (projectId: number) =>request<InstanceProjectDetail>(`/god/projects/${projectId}`);++// One team in the instance team directory, with what it holds counted across the+// tables the team owns and the projects it owns.+export interface InstanceTeam {+ id: number;+ name: string;+ mcpEnabled: boolean;+ memberCount: number;+ projectCount: number;+ issueCount: number;+ agentCount: number;+ skillCount: number;+ toolCount: number;+ roleCount: number;+ createdAt: string;+}++// One project the team owns, as the team panel lists it.+export interface InstanceTeamProject {+ id: number;+ key: string;+ name: string;+ mcpEnabled: boolean;+ memberCount: number;+ issueCount: number;+ createdAt: string;+}++// One member of a team. The role is the fixed team rank ('owner', 'manager',+// 'member', 'agent'), not a project role.+export interface InstanceTeamMember {+ userId: string;+ name: string;+ email: string;+ image: string | null;+ isAgent: boolean;+ role: TeamRole | 'agent';+ joinedAt: string;+}++// The instance team directory: one page of teams, and one team with its counts. The+// projects and the members of a team are paged apart, so a large team is never+// loaded whole.+export const listInstanceTeams = (params: PageParams & { search?: string }) =>+ request<Page<InstanceTeam>>(`/god/teams${pageQuery(params, { search: params.search })}`);++export const getInstanceTeam = (teamId: number) => request<InstanceTeam>(`/god/teams/${teamId}`);++export const listInstanceTeamProjects = (+ teamId: number,+ params: PageParams & { search?: string },+) =>+ request<Page<InstanceTeamProject>>(+ `/god/teams/${teamId}/projects${pageQuery(params, { search: params.search })}`,+ );++export const listInstanceTeamMembers = (teamId: number, params: PageParams & { search?: string }) =>+ request<Page<InstanceTeamMember>>(+ `/god/teams/${teamId}/members${pageQuery(params, { search: params.search })}`,+ );diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex cc794d6f..7cd490e5 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -278,4 +278,12 @@ export const qk = {instanceProjects: (filters: unknown) => ['instanceProjects', filters] as const,instanceProjectOptions: ['instanceProjectOptions'] as const,instanceProject: (projectId: number) => ['instanceProject', projectId] as const,+ // The instance team directory: the list (scoped by the active filters) and one team+ // with its projects and members.+ instanceTeams: (filters: unknown) => ['instanceTeams', filters] as const,+ instanceTeam: (teamId: number) => ['instanceTeam', teamId] as const,+ instanceTeamProjects: (teamId: number, filters: unknown) =>+ ['instanceTeamProjects', teamId, filters] as const,+ instanceTeamMembers: (teamId: number, filters: unknown) =>+ ['instanceTeamMembers', teamId, filters] as const,};diff --git a/apps/web/src/utils/godSections.ts b/apps/web/src/utils/godSections.tsindex de469dcc..d6716bca 100644--- a/apps/web/src/utils/godSections.ts+++ b/apps/web/src/utils/godSections.ts@@ -1,4 +1,5 @@import {+ Building2,FolderKanban,HardDrive,Keyboard,@@ -35,6 +36,11 @@ export const GOD_SECTIONS: GodSection[] = [group: 'management',icon: Users,},+ {+ slug: 'teams',+ group: 'management',+ icon: Building2,+ },{slug: 'projects',group: 'management',