Skip to content

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

fix(invites): surface received invitations on start and account pages (#667)

I'm Groot 🌳bf6814fb066d
diff --git a/apps/api/src/modules/invites/__tests__/integration/received-invites.test.ts b/apps/api/src/modules/invites/__tests__/integration/received-invites.test.ts
new file mode 100644
index 00000000..b196a088
--- /dev/null
+++ b/apps/api/src/modules/invites/__tests__/integration/received-invites.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { auth, setAuthSettings } from '@repo/auth';
+import { createHmac } from 'node:crypto';
+import { db, teamInvite } from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { api, authedApi, createProject } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+async function setup(verified = true) {
+ const owner = await signUpTestUser();
+ const asOwner = authedApi(owner.cookie);
+ const project = (await createProject(asOwner, { key: 'MKT', name: 'Marketing' })).data!;
+ const invitee = await signUpTestUser({ team: false });
+ if (verified) {
+ const now = Math.floor(Date.now() / 1000);
+ const input = [{ alg: 'HS256' }, { email: invitee.email, iat: now, exp: now + 60 }]
+ .map((value) => Buffer.from(JSON.stringify(value)).toString('base64url'))
+ .join('.');
+ const signature = createHmac('sha256', (await auth.$context).secret)
+ .update(input)
+ .digest('base64url');
+ const token = `${input}.${signature}`;
+ await auth.api.verifyEmail({ query: { token } });
+ }
+ const client = authedApi(invitee.cookie);
+ const invite = (
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: invitee.email, role: 'member' })
+ ).data!;
+ return { client, asOwner, invitee, invite, project };
+}
+
+describe('received invitations', () => {
+ beforeEach(resetDb);
+
+ it('requires a signed-in account with a verified email', async () => {
+ const { client, invite } = await setup(false);
+ expect((await api.me.invites.get()).status).toBe(401);
+ const result = await client.me.invites.get();
+ expect(result.status).toBe(403);
+ expect(JSON.stringify(result.error)).not.toContain(invite.token);
+ });
+
+ it('discovers only the current email invitations without granting membership', async () => {
+ const { client, asOwner, invite, project } = await setup();
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ const result = await client.me.invites.get();
+ expect(result.status).toBe(200);
+ expect(result.data?.items).toEqual([
+ { token: invite.token, teamName: expect.any(String), projectName: 'Marketing' },
+ ]);
+ expect(result.data?.total).toBe(1);
+ expect(result.response.headers.get('cache-control')).toBe('private, no-store');
+ expect((await client.teams.get()).data?.some((team) => team.id === project.teamId)).toBe(false);
+ expect((await client.invites({ token: invite.token }).accept.post()).status).toBe(200);
+ expect((await client.me.invites.get()).data?.total).toBe(0);
+ });
+
+ it('pages team and project invitations with a stable total', async () => {
+ const { client, asOwner, invitee, project } = await setup();
+ const teamInvite = await asOwner
+ .teams({ teamId: project.teamId })
+ .invites.post({ email: invitee.email, role: 'member' });
+ expect(teamInvite.status).toBe(201);
+ const first = await client.me.invites.get({ query: { page: 1, pageSize: 1 } });
+ const second = await client.me.invites.get({ query: { page: 2, pageSize: 1 } });
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ expect(first.data?.total).toBe(2);
+ expect(first.data?.items).toHaveLength(1);
+ expect(second.data?.items).toHaveLength(1);
+ expect(first.data?.items[0]?.token).not.toBe(second.data?.items[0]?.token);
+ expect(first.data?.items[0]?.projectName).toBe(null);
+ });
+
+ it('excludes expired invitations and honors unlimited lifetime', async () => {
+ const { client, invite } = await setup();
+ await db
+ .update(teamInvite)
+ .set({ createdAt: new Date(Date.now() - 8 * 86400000) })
+ .where(eq(teamInvite.token, invite.token));
+ expect((await client.me.invites.get()).data?.total).toBe(0);
+ expect((await client.invites({ token: invite.token }).accept.post()).status).toBe(409);
+ await setAuthSettings({ inviteTtlDays: 0 });
+ expect((await client.me.invites.get()).data?.total).toBe(1);
+ });
+
+ it('removes declined invitations', async () => {
+ const { client, invite } = await setup();
+ expect((await client.invites({ token: invite.token }).reject.post()).status).toBe(204);
+ expect((await client.me.invites.get()).data?.total).toBe(0);
+ });
+
+ it('removes revoked invitations', async () => {
+ const { client, asOwner, invite } = await setup();
+ expect((await client.me.invites.get()).data?.total).toBe(1);
+ expect(
+ (await asOwner.projects({ projectKey: 'MKT' }).invites({ inviteId: invite.id }).delete())
+ .status,
+ ).toBe(204);
+ expect((await client.me.invites.get()).data?.total).toBe(0);
+ });
+
+ it('rejects invalid paging windows', async () => {
+ const { client } = await setup();
+ expect((await client.me.invites.get({ query: { page: 0 } })).status).toBe(400);
+ expect((await client.me.invites.get({ query: { pageSize: 101 } })).status).toBe(400);
+ });
+});
diff --git a/apps/api/src/modules/invites/index.ts b/apps/api/src/modules/invites/index.ts
index 620c4ba9..a66886c9 100644
--- a/apps/api/src/modules/invites/index.ts
+++ b/apps/api/src/modules/invites/index.ts
@@ -1,6 +1,7 @@
import { Elysia, t } from 'elysia';
import { mcpTool } from '#mcp/generate';
import { noContent } from '#shared/http';
+import { paginate } from '#shared/pagination';
import { authContext } from '#shared/auth-context';
import { guards } from '#shared/guards';
import {
@@ -18,6 +19,8 @@ import { getRole } from '#modules/roles/service';
import type { ProjectRow } from '#modules/projects/service';
import { teamParams } from '#modules/teams/model';
import {
+ receivedInvitesQuery,
+ ReceivedInvitePageResponse,
AcceptInviteResponse,
InviteCreateResponse,
InviteEmailResponse,
@@ -30,6 +33,7 @@ import {
tokenParams,
} from './model';
import {
+ listReceivedInvites,
createInvite,
mayGrantInviteRanks,
listProjectInvites,
@@ -121,6 +125,31 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
.use(authContext)
.use(guards)
+ .get(
+ '/me/invites',
+ async ({ user, query, set }) => {
+ set.headers['cache-control'] = 'private, no-store';
+ return paginate(query, (window) =>
+ listReceivedInvites(requireUser(user).email ?? '', window),
+ );
+ },
+ {
+ beforeHandle: ({ user }) => {
+ requireUser(user);
+ if (!user?.emailVerified || !user.email) {
+ throw new HttpError(403, 'Confirm your email before viewing invitations');
+ }
+ },
+ query: receivedInvitesQuery,
+ response: { 200: ReceivedInvitePageResponse, ...errors(400, 401, 403) },
+ detail: {
+ summary: 'List invitations received by your verified email',
+ description:
+ 'Pending, unexpired invitations for the signed-in account. Open an invitation to review its role and explicitly accept or decline it.',
+ },
+ },
+ )
+
.post(
'/projects/:projectKey/invites',
async ({ project, body, user, set }) => {
diff --git a/apps/api/src/modules/invites/model.ts b/apps/api/src/modules/invites/model.ts
index 64242701..f40b6765 100644
--- a/apps/api/src/modules/invites/model.ts
+++ b/apps/api/src/modules/invites/model.ts
@@ -1,4 +1,5 @@
import { t } from 'elysia';
+import { pageQueryFields, pageResponse } from '#shared/pagination';
const projectRole = t.Union([t.Literal('owner'), t.Literal('member')]);
@@ -80,3 +81,12 @@ export const AcceptInviteResponse = t.Object({
projectName: t.Nullable(t.String()),
role: t.Nullable(projectRole),
});
+
+export const receivedInvitesQuery = t.Object(pageQueryFields);
+export const ReceivedInvitePageResponse = pageResponse(
+ t.Object({
+ token: t.String(),
+ teamName: t.String(),
+ projectName: t.Nullable(t.String()),
+ }),
+);
diff --git a/apps/api/src/modules/invites/service.ts b/apps/api/src/modules/invites/service.ts
index 8f62535a..c181048c 100644
--- a/apps/api/src/modules/invites/service.ts
+++ b/apps/api/src/modules/invites/service.ts
@@ -1,5 +1,5 @@
import { db, teamInvite, teamMember, projectMember, teamRole, team, project, user } from '@repo/db';
-import { and, desc, eq, inArray, isNull, lt, sql } from 'drizzle-orm';
+import { and, desc, eq, gte, inArray, isNull, lt, sql } from 'drizzle-orm';
import { getAuthSettings, inviteValidSince } from '@repo/auth';
import { HttpError, iso, pgErrorCode } from '#shared/lib';
import { getProjectAccess, getTeamAccess } from '#shared/access';
@@ -551,3 +551,31 @@ export async function rejectInvite(inviteId: number): Promise<void> {
.set({ status: 'rejected', respondedAt: new Date() })
.where(eq(teamInvite.id, inviteId));
}
+
+export async function listReceivedInvites(
+ email: string,
+ window: { limit: number; offset: number },
+) {
+ const since = await inviteValidSince();
+ const where = and(
+ eq(teamInvite.email, normalizeEmail(email)),
+ eq(teamInvite.status, 'pending'),
+ since ? gte(teamInvite.createdAt, since) : undefined,
+ );
+ const [items, counts] = await Promise.all([
+ db
+ .select({ token: teamInvite.token, teamName: team.name, projectName: project.name })
+ .from(teamInvite)
+ .innerJoin(team, eq(team.id, teamInvite.teamId))
+ .leftJoin(project, eq(project.id, teamInvite.projectId))
+ .where(where)
+ .orderBy(desc(teamInvite.createdAt), desc(teamInvite.id))
+ .limit(window.limit)
+ .offset(window.offset),
+ db
+ .select({ total: sql<number>`count(*)::int` })
+ .from(teamInvite)
+ .where(where),
+ ]);
+ return { items, total: counts[0]?.total ?? 0 };
+}
diff --git a/apps/web/messages/ar/invite.json b/apps/web/messages/ar/invite.json
index 7dbbb4b1..a1538a85 100644
--- a/apps/web/messages/ar/invite.json
+++ b/apps/web/messages/ar/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "البريد ده له حساب بالفعل. سجّل الدخول بكلمة مرورك.",
"passwordsDoNotMatch": "كلمتا المرور غير متطابقتين.",
"registerFailed": "تعذّر إنشاء حسابك.",
- "signInFailed": "تعذّر تسجيل دخولك."
+ "signInFailed": "تعذّر تسجيل دخولك.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/ar/sections.json b/apps/web/messages/ar/sections.json
index 629d2c84..1b2793e0 100644
--- a/apps/web/messages/ar/sections.json
+++ b/apps/web/messages/ar/sections.json
@@ -4,7 +4,8 @@
"preferences": "التفضيلات",
"accounts": "الحسابات",
"security": "الأمان",
- "api-keys": "مفاتيح واجهة البرمجة (API keys)"
+ "api-keys": "مفاتيح واجهة البرمجة (API keys)",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "الإدارة",
diff --git a/apps/web/messages/en/invite.json b/apps/web/messages/en/invite.json
index 8306f995..644159a9 100644
--- a/apps/web/messages/en/invite.json
+++ b/apps/web/messages/en/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "This email already has an account. Sign in with your password.",
"passwordsDoNotMatch": "Passwords do not match.",
"registerFailed": "Could not create your account.",
- "signInFailed": "Could not sign you in."
+ "signInFailed": "Could not sign you in.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/en/sections.json b/apps/web/messages/en/sections.json
index 52076a50..e3eecb6d 100644
--- a/apps/web/messages/en/sections.json
+++ b/apps/web/messages/en/sections.json
@@ -4,7 +4,8 @@
"preferences": "Preferences",
"accounts": "Accounts",
"security": "Security",
- "api-keys": "API keys"
+ "api-keys": "API keys",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Management",
diff --git a/apps/web/messages/es-ES/invite.json b/apps/web/messages/es-ES/invite.json
index 1ab001d5..aa2b576d 100644
--- a/apps/web/messages/es-ES/invite.json
+++ b/apps/web/messages/es-ES/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Este correo ya tiene una cuenta. Inicia sesión con tu contraseña.",
"passwordsDoNotMatch": "Las contraseñas no coinciden.",
"registerFailed": "No se ha podido crear tu cuenta.",
- "signInFailed": "No se ha podido iniciar tu sesión."
+ "signInFailed": "No se ha podido iniciar tu sesión.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/es-ES/sections.json b/apps/web/messages/es-ES/sections.json
index 011a8dd1..73d74759 100644
--- a/apps/web/messages/es-ES/sections.json
+++ b/apps/web/messages/es-ES/sections.json
@@ -4,7 +4,8 @@
"preferences": "Preferencias",
"accounts": "Cuentas",
"security": "Seguridad",
- "api-keys": "Claves de API"
+ "api-keys": "Claves de API",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Gestión",
diff --git a/apps/web/messages/fa/invite.json b/apps/web/messages/fa/invite.json
index d366ab09..e3e1a76d 100644
--- a/apps/web/messages/fa/invite.json
+++ b/apps/web/messages/fa/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "این ایمیل قبلاً حساب دارد. با رمز عبور خود وارد شوید.",
"passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند.",
"registerFailed": "نمی‌توان حساب شما را ایجاد کرد.",
- "signInFailed": "نمی‌توان شما را وارد کرد."
+ "signInFailed": "نمی‌توان شما را وارد کرد.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/fa/sections.json b/apps/web/messages/fa/sections.json
index ba6f8b2d..bfeeacca 100644
--- a/apps/web/messages/fa/sections.json
+++ b/apps/web/messages/fa/sections.json
@@ -4,7 +4,8 @@
"preferences": "ترجیحات",
"accounts": "حساب‌ها",
"security": "امنیت",
- "api-keys": "کلیدهای API"
+ "api-keys": "کلیدهای API",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "مدیریت",
diff --git a/apps/web/messages/fr/invite.json b/apps/web/messages/fr/invite.json
index f8503fb4..038b0120 100644
--- a/apps/web/messages/fr/invite.json
+++ b/apps/web/messages/fr/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Un compte existe déjà pour cette adresse. Connectez-vous avec votre mot de passe.",
"passwordsDoNotMatch": "Les mots de passe ne correspondent pas.",
"registerFailed": "Impossible de créer votre compte.",
- "signInFailed": "Impossible de vous connecter."
+ "signInFailed": "Impossible de vous connecter.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/fr/sections.json b/apps/web/messages/fr/sections.json
index 67a16db7..063cd513 100644
--- a/apps/web/messages/fr/sections.json
+++ b/apps/web/messages/fr/sections.json
@@ -4,7 +4,8 @@
"preferences": "Préférences",
"accounts": "Comptes",
"security": "Sécurité",
- "api-keys": "Clés d'API"
+ "api-keys": "Clés d'API",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Gestion",
diff --git a/apps/web/messages/id/invite.json b/apps/web/messages/id/invite.json
index 81710b56..fc20071a 100644
--- a/apps/web/messages/id/invite.json
+++ b/apps/web/messages/id/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Email ini sudah memiliki akun. Masuk dengan kata sandi Anda.",
"passwordsDoNotMatch": "Kata sandi tidak cocok.",
"registerFailed": "Tidak dapat membuat akun Anda.",
- "signInFailed": "Gagal masuk."
+ "signInFailed": "Gagal masuk.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/id/sections.json b/apps/web/messages/id/sections.json
index fb409e3b..532b4936 100644
--- a/apps/web/messages/id/sections.json
+++ b/apps/web/messages/id/sections.json
@@ -4,7 +4,8 @@
"preferences": "Preferensi",
"accounts": "Akun",
"security": "Keamanan",
- "api-keys": "Kunci API"
+ "api-keys": "Kunci API",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Manajemen",
diff --git a/apps/web/messages/ko/invite.json b/apps/web/messages/ko/invite.json
index beee0b9c..1bccb3ab 100644
--- a/apps/web/messages/ko/invite.json
+++ b/apps/web/messages/ko/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "이 이메일로 등록된 계정이 이미 있습니다. 비밀번호로 로그인해 주세요.",
"passwordsDoNotMatch": "비밀번호가 일치하지 않습니다.",
"registerFailed": "계정을 생성할 수 없습니다.",
- "signInFailed": "로그인할 수 없습니다."
+ "signInFailed": "로그인할 수 없습니다.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/ko/sections.json b/apps/web/messages/ko/sections.json
index 51452b9c..d4f88dba 100644
--- a/apps/web/messages/ko/sections.json
+++ b/apps/web/messages/ko/sections.json
@@ -4,7 +4,8 @@
"preferences": "환경 설정",
"accounts": "계정",
"security": "보안",
- "api-keys": "API 키"
+ "api-keys": "API 키",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "관리",
diff --git a/apps/web/messages/pt-BR/invite.json b/apps/web/messages/pt-BR/invite.json
index 4ca2ee5b..f95f1031 100644
--- a/apps/web/messages/pt-BR/invite.json
+++ b/apps/web/messages/pt-BR/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Este e-mail já tem uma conta. Entre com sua senha.",
"passwordsDoNotMatch": "As senhas não coincidem.",
"registerFailed": "Não foi possível criar sua conta.",
- "signInFailed": "Não foi possível conectar você."
+ "signInFailed": "Não foi possível conectar você.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/pt-BR/sections.json b/apps/web/messages/pt-BR/sections.json
index 8d42d8e5..560dfc97 100644
--- a/apps/web/messages/pt-BR/sections.json
+++ b/apps/web/messages/pt-BR/sections.json
@@ -4,7 +4,8 @@
"preferences": "Preferências",
"accounts": "Contas",
"security": "Segurança",
- "api-keys": "Chaves de API"
+ "api-keys": "Chaves de API",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Gerenciamento",
diff --git a/apps/web/messages/ru/invite.json b/apps/web/messages/ru/invite.json
index 195361bc..a138a40c 100644
--- a/apps/web/messages/ru/invite.json
+++ b/apps/web/messages/ru/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Для этой почты уже есть аккаунт. Войдите со своим паролем.",
"passwordsDoNotMatch": "Пароли не совпадают.",
"registerFailed": "Не удалось создать аккаунт.",
- "signInFailed": "Не удалось выполнить вход."
+ "signInFailed": "Не удалось выполнить вход.",
+ "received": {
+ "title": "Ваши приглашения",
+ "description": "Откройте приглашение, чтобы проверить команду, проект и роль перед вступлением.",
+ "review": "Посмотреть приглашение",
+ "continue": "Продолжить без вступления",
+ "loadFailed": "Не удалось загрузить приглашения. Повторите попытку или продолжите без вступления.",
+ "retry": "Повторить попытку",
+ "loading": "Загружаем приглашения…",
+ "empty": "Нет ожидающих приглашений. Новые приглашения на вашу подтверждённую почту появятся здесь.",
+ "verifyRequired": "Подтвердите адрес почты, чтобы находить приглашения автоматически. Вы по-прежнему можете открыть приглашение по присланной ссылке.",
+ "loadFailedAccount": "Не удалось загрузить приглашения. Повторите попытку."
+ }
}
diff --git a/apps/web/messages/ru/sections.json b/apps/web/messages/ru/sections.json
index 30655516..0dfba158 100644
--- a/apps/web/messages/ru/sections.json
+++ b/apps/web/messages/ru/sections.json
@@ -4,7 +4,8 @@
"preferences": "Настройки",
"accounts": "Аккаунты",
"security": "Безопасность",
- "api-keys": "API-ключи"
+ "api-keys": "API-ключи",
+ "invitations": "Приглашения"
},
"godGroups": {
"management": "Управление",
diff --git a/apps/web/messages/tr/invite.json b/apps/web/messages/tr/invite.json
index eae79ec0..7c99271f 100644
--- a/apps/web/messages/tr/invite.json
+++ b/apps/web/messages/tr/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Bu e-posta adresine kayıtlı bir hesap zaten var. Şifrenizle giriş yapın.",
"passwordsDoNotMatch": "Şifreler eşleşmiyor.",
"registerFailed": "Hesabınız oluşturulamadı.",
- "signInFailed": "Giriş yapılamadı."
+ "signInFailed": "Giriş yapılamadı.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/tr/sections.json b/apps/web/messages/tr/sections.json
index c4446a19..e9734279 100644
--- a/apps/web/messages/tr/sections.json
+++ b/apps/web/messages/tr/sections.json
@@ -4,7 +4,8 @@
"preferences": "Tercihler",
"accounts": "Hesaplar",
"security": "Güvenlik",
- "api-keys": "API anahtarları"
+ "api-keys": "API anahtarları",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Yönetim",
diff --git a/apps/web/messages/uk/invite.json b/apps/web/messages/uk/invite.json
index 42e3eb0e..9005719c 100644
--- a/apps/web/messages/uk/invite.json
+++ b/apps/web/messages/uk/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "Для цієї пошти вже є акаунт. Увійдіть зі своїм паролем.",
"passwordsDoNotMatch": "Паролі не збігаються.",
"registerFailed": "Не вдалося створити акаунт.",
- "signInFailed": "Не вдалося виконати вхід."
+ "signInFailed": "Не вдалося виконати вхід.",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/uk/sections.json b/apps/web/messages/uk/sections.json
index 25e92ebf..12838a5f 100644
--- a/apps/web/messages/uk/sections.json
+++ b/apps/web/messages/uk/sections.json
@@ -4,7 +4,8 @@
"preferences": "Налаштування",
"accounts": "Акаунти",
"security": "Безпека",
- "api-keys": "API-ключі"
+ "api-keys": "API-ключі",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "Керування",
diff --git a/apps/web/messages/zh-CN/invite.json b/apps/web/messages/zh-CN/invite.json
index 001e4670..0805e61d 100644
--- a/apps/web/messages/zh-CN/invite.json
+++ b/apps/web/messages/zh-CN/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "此邮箱已有账户,请使用密码登录。",
"passwordsDoNotMatch": "两次输入的密码不一致。",
"registerFailed": "无法创建账户。",
- "signInFailed": "无法登录。"
+ "signInFailed": "无法登录。",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/zh-CN/sections.json b/apps/web/messages/zh-CN/sections.json
index 73c994e7..84fbf13f 100644
--- a/apps/web/messages/zh-CN/sections.json
+++ b/apps/web/messages/zh-CN/sections.json
@@ -4,7 +4,8 @@
"preferences": "偏好设置",
"accounts": "关联账户",
"security": "安全",
- "api-keys": "API 密钥"
+ "api-keys": "API 密钥",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "管理",
diff --git a/apps/web/messages/zh-TW/invite.json b/apps/web/messages/zh-TW/invite.json
index 689ac368..be19ec2e 100644
--- a/apps/web/messages/zh-TW/invite.json
+++ b/apps/web/messages/zh-TW/invite.json
@@ -37,5 +37,17 @@
"existingAccountNotice": "此電子郵件已有帳號,請使用密碼登入。",
"passwordsDoNotMatch": "兩次輸入的密碼不一致。",
"registerFailed": "無法建立帳號。",
- "signInFailed": "無法登入。"
+ "signInFailed": "無法登入。",
+ "received": {
+ "title": "Your invitations",
+ "description": "Review an invitation to see the team, project and role before joining.",
+ "review": "Review invitation",
+ "continue": "Continue without joining",
+ "loadFailed": "Invitations could not be loaded. Try again or continue without joining.",
+ "retry": "Try again",
+ "loading": "Loading invitations…",
+ "empty": "No pending invitations. New invitations sent to your verified email will appear here.",
+ "verifyRequired": "Verify your email address to discover invitations automatically. You can still open an invitation link shared with you.",
+ "loadFailedAccount": "Could not load invitations. Please try again."
+ }
}
diff --git a/apps/web/messages/zh-TW/sections.json b/apps/web/messages/zh-TW/sections.json
index cba1679d..cef44ab4 100644
--- a/apps/web/messages/zh-TW/sections.json
+++ b/apps/web/messages/zh-TW/sections.json
@@ -4,7 +4,8 @@
"preferences": "偏好設定",
"accounts": "關聯帳號",
"security": "安全",
- "api-keys": "API 金鑰"
+ "api-keys": "API 金鑰",
+ "invitations": "Invitations"
},
"godGroups": {
"management": "管理",
diff --git a/apps/web/src/app/account/invitations/page.tsx b/apps/web/src/app/account/invitations/page.tsx
new file mode 100644
index 00000000..28b193da
--- /dev/null
+++ b/apps/web/src/app/account/invitations/page.tsx
@@ -0,0 +1,5 @@
+import AccountInvitationsPage from '@/features/account/AccountInvitationsPage';
+
+export default function Page() {
+ return <AccountInvitationsPage />;
+}
diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx
index f4262bf4..fe01a4bd 100644
--- a/apps/web/src/app/page.tsx
+++ b/apps/web/src/app/page.tsx
@@ -14,6 +14,7 @@ import NewProjectModal from '@/components/layout/NewProjectModal';
import NewTeamModal from '@/features/teams/components/NewTeamModal';
import ProjectSwitcherHiddenState from '@/components/layout/ProjectSwitcherHiddenState';
import StartEmpty from '@/components/layout/StartEmpty';
+import InviteStart from '@/features/invite/components/InviteStart';
// The index route: reopen the last-used project if it still exists, otherwise the
// first visible favorite or project, on the user's preferred start page. Waits for both
@@ -50,23 +51,30 @@ export default function Home() {
workspaces?.find((one) => one.role === 'owner') ?? workspaces?.find((one) => one.canCreateTeam);
if (teams && workspaces && !managedTeam && projects?.length === 0) {
- if (teams.length === 0 && !teamWorkspace) return <NoTeamStart />;
+ if (teams.length === 0 && !teamWorkspace)
+ return (
+ <InviteStart>
+ <NoTeamStart />
+ </InviteStart>
+ );
return (
- <StartEmpty
- icon={<Users />}
- title={teams.length === 0 ? t('noTeamsTitle') : t('noProjectsTitle')}
- hint={
- teams.length === 0
- ? t('noTeamsHint')
- : t(teamWorkspace ? 'noProjectAccessOwnerHint' : 'noProjectAccessHint')
- }
- action={teamWorkspace && t('createTeam')}
- onAction={() => setCreating(true)}
- >
- {creating && teamWorkspace && (
- <NewTeamModal workspaceId={teamWorkspace.id} onClose={() => setCreating(false)} />
- )}
- </StartEmpty>
+ <InviteStart>
+ <StartEmpty
+ icon={<Users />}
+ title={teams.length === 0 ? t('noTeamsTitle') : t('noProjectsTitle')}
+ hint={
+ teams.length === 0
+ ? t('noTeamsHint')
+ : t(teamWorkspace ? 'noProjectAccessOwnerHint' : 'noProjectAccessHint')
+ }
+ action={teamWorkspace && t('createTeam')}
+ onAction={() => setCreating(true)}
+ >
+ {creating && teamWorkspace && (
+ <NewTeamModal workspaceId={teamWorkspace.id} onClose={() => setCreating(false)} />
+ )}
+ </StartEmpty>
+ </InviteStart>
);
}
@@ -74,24 +82,26 @@ export default function Home() {
// without a project, so the empty state offers project creation directly.
if (managedTeam && projects?.length === 0) {
return (
- <StartEmpty
- icon={<SquareKanban />}
- title={t('noProjectsTitle')}
- hint={t('noProjectsHint')}
- action={t('createProject')}
- onAction={() => setCreating(true)}
- >
- {creating && (
- <NewProjectModal
- teamId={managedTeam.id}
- onClose={() => setCreating(false)}
- onCreated={(key) => {
- setCreating(false);
- router.push(projectPath(key));
- }}
- />
- )}
- </StartEmpty>
+ <InviteStart>
+ <StartEmpty
+ icon={<SquareKanban />}
+ title={t('noProjectsTitle')}
+ hint={t('noProjectsHint')}
+ action={t('createProject')}
+ onAction={() => setCreating(true)}
+ >
+ {creating && (
+ <NewProjectModal
+ teamId={managedTeam.id}
+ onClose={() => setCreating(false)}
+ onCreated={(key) => {
+ setCreating(false);
+ router.push(projectPath(key));
+ }}
+ />
+ )}
+ </StartEmpty>
+ </InviteStart>
);
}
diff --git a/apps/web/src/components/common/invites/ReceivedInvitesList.test.tsx b/apps/web/src/components/common/invites/ReceivedInvitesList.test.tsx
new file mode 100644
index 00000000..90f74da5
--- /dev/null
+++ b/apps/web/src/components/common/invites/ReceivedInvitesList.test.tsx
@@ -0,0 +1,34 @@
+import assert from 'node:assert/strict';
+import { it } from 'node:test';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import invite from '../../../../messages/en/invite.json';
+import ReceivedInvitesList from './ReceivedInvitesList';
+
+it('distinguishes invitations for different projects of the same team', () => {
+ const html = renderToStaticMarkup(
+ <NextIntlClientProvider locale="en" messages={{ invite }} timeZone="UTC">
+ <ReceivedInvitesList
+ items={[
+ { token: 'marketing-token', teamName: 'Acme', projectName: 'Marketing' },
+ { token: 'platform-token', teamName: 'Acme', projectName: 'Platform' },
+ ]}
+ />
+ </NextIntlClientProvider>,
+ );
+ const dom = new JSDOM(html);
+ try {
+ const links = [...dom.window.document.querySelectorAll('a')];
+ assert.deepEqual(
+ links.map((link) => link.getAttribute('aria-label')),
+ ['Review invitation: Acme / Marketing', 'Review invitation: Acme / Platform'],
+ );
+ assert.deepEqual(
+ links.map((link) => link.getAttribute('href')),
+ ['/invite/marketing-token', '/invite/platform-token'],
+ );
+ } finally {
+ dom.window.close();
+ }
+});
diff --git a/apps/web/src/components/common/invites/ReceivedInvitesList.tsx b/apps/web/src/components/common/invites/ReceivedInvitesList.tsx
new file mode 100644
index 00000000..f010bf45
--- /dev/null
+++ b/apps/web/src/components/common/invites/ReceivedInvitesList.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import Link from 'next/link';
+import { useTranslations } from 'next-intl';
+import type { ReceivedInvite } from '@/lib/api/endpoints/invites';
+import { Button } from '@/components/ui/button';
+
+export default function ReceivedInvitesList({ items }: { items: ReceivedInvite[] }) {
+ const t = useTranslations('invite.received');
+
+ return (
+ <ul className="divide-y">
+ {items.map((invite) => (
+ <li
+ key={invite.token}
+ className="flex flex-col gap-3 py-4 sm:flex-row sm:items-center sm:justify-between"
+ >
+ <div className="min-w-0 break-words">
+ <p className="font-medium">{invite.teamName}</p>
+ {invite.projectName && (
+ <p className="mt-1 text-sm text-muted-foreground">{invite.projectName}</p>
+ )}
+ </div>
+ <Button asChild variant="outline" className="shrink-0">
+ <Link
+ aria-label={`${t('review')}: ${invite.teamName}${invite.projectName ? ` / ${invite.projectName}` : ''}`}
+ href={`/invite/${encodeURIComponent(invite.token)}`}
+ >
+ {t('review')}
+ </Link>
+ </Button>
+ </li>
+ ))}
+ </ul>
+ );
+}
diff --git a/apps/web/src/features/account/AccountInvitationsPage.tsx b/apps/web/src/features/account/AccountInvitationsPage.tsx
new file mode 100644
index 00000000..a32c9bf4
--- /dev/null
+++ b/apps/web/src/features/account/AccountInvitationsPage.tsx
@@ -0,0 +1,62 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { useSession } from '@/lib/auth-client';
+import { usePaging } from '@/hooks/usePaging';
+import { useReceivedInvitesQuery } from '@/services/invites.service';
+import FullPageView from '@/components/common/page/FullPageView';
+import ReceivedInvitesList from '@/components/common/invites/ReceivedInvitesList';
+import ListPager from '@/components/common/ListPager';
+import { Button } from '@/components/ui/button';
+
+export default function AccountInvitationsPage() {
+ const t = useTranslations('invite.received');
+ const sectionLabel = useTranslations('sections.account');
+ const session = useSession();
+ const user = session.data?.user;
+ const paging = usePaging();
+ const query = useReceivedInvitesQuery(user, paging.params);
+
+ let content;
+ if (session.isPending || (user?.emailVerified && query.isPending)) {
+ content = (
+ <p role="status" className="py-6 text-sm text-muted-foreground">
+ {t('loading')}
+ </p>
+ );
+ } else if (!user?.emailVerified) {
+ content = <p className="py-6 text-sm text-muted-foreground">{t('verifyRequired')}</p>;
+ } else if (query.isError) {
+ content = (
+ <div role="alert" className="space-y-3 py-6">
+ <p className="text-sm text-destructive">{t('loadFailedAccount')}</p>
+ <Button variant="outline" disabled={query.isFetching} onClick={() => void query.refetch()}>
+ {t('retry')}
+ </Button>
+ </div>
+ );
+ } else if (query.data?.total === 0) {
+ content = (
+ <p role="status" className="py-6 text-sm text-muted-foreground">
+ {t('empty')}
+ </p>
+ );
+ } else {
+ content = (
+ <div className="space-y-6">
+ <ReceivedInvitesList items={query.data?.items ?? []} />
+ <ListPager paging={paging} total={query.data?.total ?? 0} />
+ </div>
+ );
+ }
+
+ return (
+ <FullPageView
+ label={sectionLabel('invitations')}
+ title={t('title')}
+ description={t('description')}
+ >
+ {content}
+ </FullPageView>
+ );
+}
diff --git a/apps/web/src/features/invite/components/InviteActions.test.tsx b/apps/web/src/features/invite/components/InviteActions.test.tsx
new file mode 100644
index 00000000..9a476293
--- /dev/null
+++ b/apps/web/src/features/invite/components/InviteActions.test.tsx
@@ -0,0 +1,165 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { NextIntlClientProvider } from 'next-intl';
+import { AppRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';
+import { JSDOM } from 'jsdom';
+import { qk } from '@/services/queryKeys';
+import messages from '../../../../messages/en/invite.json';
+import InviteActions from './InviteActions';
+
+const token = '00000000-0000-4000-8000-000000000001';
+const keys = [qk.projects, qk.teams, qk.workspaces, qk.receivedInvites];
+const globals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'HTMLElement',
+ 'fetch',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let dom: JSDOM;
+let root: Root;
+let client: QueryClient;
+let navigated: string[];
+let membershipAtNavigation: unknown[];
+let status: number;
+
+beforeEach(async () => {
+ originals = new Map(
+ globals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', {
+ url: 'https://example.test/invite/' + token,
+ });
+ status = 200;
+ navigated = [];
+ membershipAtNavigation = [];
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ HTMLElement: { configurable: true, value: dom.window.HTMLElement },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ fetch: {
+ configurable: true,
+ value: async (input: string | URL | Request) => {
+ if (status !== 200) return Response.json({ error: 'Invitation unavailable' }, { status });
+ if (String(input).endsWith('/reject')) return new Response(null, { status: 204 });
+ return Response.json({
+ teamName: 'Example',
+ teamRef: '1.example',
+ projectKey: null,
+ projectName: null,
+ role: null,
+ });
+ },
+ },
+ });
+ client = new QueryClient({
+ defaultOptions: { queries: { staleTime: Infinity, retry: false, gcTime: Infinity } },
+ });
+ for (const key of keys) client.setQueryData(key, []);
+ client.setQueryData(['invite', token], { status: 'pending' });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+ const router = {
+ push: (path: string) => {
+ membershipAtNavigation = [qk.teams, qk.projects, qk.workspaces].map((key) =>
+ client.getQueryData(key),
+ );
+ navigated.push(path);
+ },
+ refresh() {},
+ replace() {},
+ back() {},
+ forward() {},
+ prefetch() {},
+ };
+ await act(async () =>
+ root.render(
+ <AppRouterContext.Provider value={router as never}>
+ <QueryClientProvider client={client}>
+ <NextIntlClientProvider locale="en" messages={{ invite: messages }} timeZone="UTC">
+ <InviteActions token={token} projectKey={null} />
+ </NextIntlClientProvider>
+ </QueryClientProvider>
+ </AppRouterContext.Provider>,
+ ),
+ );
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ client.clear();
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+async function click(label: string) {
+ const button = [...document.querySelectorAll('button')].find((one) => one.textContent === label);
+ assert.ok(button);
+ await act(async () => {
+ button.click();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+describe('InviteActions membership cache', () => {
+ it('invalidates teams, projects, workspaces and received invites before returning home', async () => {
+ await click(messages.accept);
+ assert.deepEqual(navigated, ['/']);
+ assert.deepEqual(
+ keys.map((key) => client.getQueryState(key)?.isInvalidated),
+ [true, true, true, true],
+ );
+ });
+
+ it('refreshes inactive membership lists before navigation', async () => {
+ let joined = false;
+ const membershipKeys = [qk.teams, qk.projects, qk.workspaces];
+ for (const queryKey of membershipKeys) {
+ await client.fetchQuery({
+ queryKey,
+ queryFn: async () => (joined ? ['new membership'] : []),
+ staleTime: 0,
+ });
+ assert.equal(client.getQueryCache().find({ queryKey })?.getObserversCount(), 0);
+ }
+ joined = true;
+
+ await click(messages.accept);
+
+ assert.deepEqual(navigated, ['/']);
+ assert.deepEqual(membershipAtNavigation, [
+ ['new membership'],
+ ['new membership'],
+ ['new membership'],
+ ]);
+ });
+
+ it('invalidates the received list on decline without granting membership', async () => {
+ await click(messages.decline);
+ assert.equal(client.getQueryState(qk.receivedInvites)?.isInvalidated, true);
+ assert.equal(client.getQueryState(['invite', token])?.isInvalidated, true);
+ assert.equal(client.getQueryState(qk.teams)?.isInvalidated, false);
+ assert.deepEqual(navigated, []);
+ });
+
+ it('preserves membership caches and stays on the invite when acceptance is refused', async () => {
+ status = 409;
+ await click(messages.accept);
+ assert.deepEqual(navigated, []);
+ assert.deepEqual(
+ keys.map((key) => client.getQueryState(key)?.isInvalidated),
+ [false, false, false, false],
+ );
+ assert.ok(document.body.textContent?.includes('Invitation unavailable'));
+ });
+});
diff --git a/apps/web/src/features/invite/components/InviteActions.tsx b/apps/web/src/features/invite/components/InviteActions.tsx
index 29b6f5b2..a085c8c5 100644
--- a/apps/web/src/features/invite/components/InviteActions.tsx
+++ b/apps/web/src/features/invite/components/InviteActions.tsx
@@ -7,6 +7,7 @@ import { useQueryClient } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { acceptInvite, rejectInvite } from '@/lib/api/endpoints/invites';
import { ApiError } from '@/lib/api/core/client';
+import { qk } from '@/services/queryKeys';
import { projectPath, projectRefOf } from '@/utils/paths';
import { Button } from '@/components/ui/button';
import { FieldError } from '@/components/ui/field';
@@ -37,6 +38,12 @@ export default function InviteActions({
setBusy('accept');
try {
const result = await acceptInvite(token);
+ await Promise.all([
+ ...[qk.teams, qk.projects, qk.workspaces].map((queryKey) =>
+ qc.invalidateQueries({ queryKey, refetchType: 'all' }),
+ ),
+ qc.invalidateQueries({ queryKey: qk.receivedInvites }),
+ ]);
router.push(
result.projectKey ? projectPath(projectRefOf(result.teamRef, result.projectKey)) : '/',
);
@@ -53,7 +60,10 @@ export default function InviteActions({
setBusy('reject');
try {
await rejectInvite(token);
- await qc.invalidateQueries({ queryKey: ['invite', token] });
+ await Promise.all([
+ qc.invalidateQueries({ queryKey: ['invite', token] }),
+ qc.invalidateQueries({ queryKey: qk.receivedInvites }),
+ ]);
} catch (err) {
setError(err instanceof Error ? err.message : t('declineError'));
setBusy(null);
diff --git a/apps/web/src/features/invite/components/InviteStart.tsx b/apps/web/src/features/invite/components/InviteStart.tsx
new file mode 100644
index 00000000..33a15323
--- /dev/null
+++ b/apps/web/src/features/invite/components/InviteStart.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import { useState, type ReactNode } from 'react';
+import { useSession } from '@/lib/auth-client';
+import { usePaging } from '@/hooks/usePaging';
+import { useReceivedInvitesQuery } from '@/services/invites.service';
+import InviteStartList from './InviteStartList';
+
+export default function InviteStart({ children }: { children: ReactNode }) {
+ const session = useSession();
+ const user = session.data?.user;
+ const paging = usePaging();
+ const query = useReceivedInvitesQuery(user, paging.params);
+ const [continued, setContinued] = useState(false);
+
+ if (continued) return children;
+ const loading = session.isPending || (!!user?.emailVerified && query.isPending);
+ if (!loading && (!user?.emailVerified || (!query.isError && query.data?.total === 0)))
+ return children;
+
+ return (
+ <InviteStartList
+ items={query.data?.items ?? []}
+ total={query.data?.total ?? 0}
+ paging={paging}
+ loading={loading}
+ failed={query.isError}
+ retrying={query.isFetching}
+ onRetry={() => void query.refetch()}
+ onContinue={() => setContinued(true)}
+ />
+ );
+}
diff --git a/apps/web/src/features/invite/components/InviteStartList.tsx b/apps/web/src/features/invite/components/InviteStartList.tsx
new file mode 100644
index 00000000..6b68e989
--- /dev/null
+++ b/apps/web/src/features/invite/components/InviteStartList.tsx
@@ -0,0 +1,73 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { useDocumentTitle } from '@/hooks/useDocumentTitle';
+import type { Paging } from '@/hooks/usePaging';
+import type { ReceivedInvite } from '@/lib/api/endpoints/invites';
+import { Button } from '@/components/ui/button';
+import ListPager from '@/components/common/ListPager';
+import ReceivedInvitesList from '@/components/common/invites/ReceivedInvitesList';
+import { LocaleToggle } from '@/components/locale-toggle';
+import { ThemeToggle } from '@/components/theme-toggle';
+import UserMenu from '@/components/layout/UserMenu';
+
+export default function InviteStartList({
+ items,
+ total,
+ paging,
+ loading,
+ failed,
+ retrying,
+ onRetry,
+ onContinue,
+}: {
+ items: ReceivedInvite[];
+ total: number;
+ paging: Paging;
+ loading: boolean;
+ failed: boolean;
+ retrying: boolean;
+ onRetry: () => void;
+ onContinue: () => void;
+}) {
+ const t = useTranslations('invite.received');
+ useDocumentTitle(t('title'));
+
+ return (
+ <main className="relative min-h-svh">
+ <div className="absolute end-4 top-3 flex items-center gap-1">
+ <LocaleToggle />
+ <ThemeToggle />
+ <UserMenu />
+ </div>
+ <div className="mx-auto flex min-h-svh w-full max-w-xl flex-col justify-center gap-6 px-6 py-20">
+ <header>
+ <h1 className="text-2xl font-semibold">{t('title')}</h1>
+ <p className="mt-2 text-sm text-muted-foreground">{t('description')}</p>
+ </header>
+ {loading && (
+ <p role="status" className="text-sm text-muted-foreground">
+ {t('loading')}
+ </p>
+ )}
+ {!loading && failed && (
+ <div role="alert" className="space-y-3">
+ <p className="text-sm text-destructive">{t('loadFailed')}</p>
+ <Button variant="outline" disabled={retrying} onClick={onRetry}>
+ {t('retry')}
+ </Button>
+ </div>
+ )}
+ {!loading && !failed && (
+ <>
+ <ReceivedInvitesList items={items} />
+ <ListPager paging={paging} total={total} />
+ </>
+ )}
+ <Button variant="ghost" className="self-start" onClick={onContinue}>
+ {t('continue')}
+ </Button>
+ </div>
+ </main>
+ );
+}
diff --git a/apps/web/src/lib/api/endpoints/invites.ts b/apps/web/src/lib/api/endpoints/invites.ts
index d0533983..d291556a 100644
--- a/apps/web/src/lib/api/endpoints/invites.ts
+++ b/apps/web/src/lib/api/endpoints/invites.ts
@@ -1,4 +1,5 @@
import { request } from '@/lib/api/core/client';
+import { pageQuery, type Page, type PageParams } from '@/lib/api/core/paging';
import type { MemberRole } from '@/lib/api/endpoints/members';
export type InviteStatus = 'pending' | 'accepted' | 'rejected';
@@ -132,3 +133,12 @@ export const acceptInvite = (token: string) =>
export const rejectInvite = (token: string) =>
request<void>(`/invites/${encodeURIComponent(token)}/reject`, { method: 'POST' });
+
+export interface ReceivedInvite {
+ token: string;
+ teamName: string;
+ projectName: string | null;
+}
+
+export const listReceivedInvites = (params: PageParams) =>
+ request<Page<ReceivedInvite>>(`/me/invites${pageQuery(params)}`);
diff --git a/apps/web/src/services/invites.service.ts b/apps/web/src/services/invites.service.ts
new file mode 100644
index 00000000..8e2b10ba
--- /dev/null
+++ b/apps/web/src/services/invites.service.ts
@@ -0,0 +1,16 @@
+import { useQuery } from '@tanstack/react-query';
+import { listReceivedInvites } from '@/lib/api/endpoints/invites';
+import type { PageParams } from '@/lib/api/core/paging';
+import { qk } from '@/services/queryKeys';
+
+export function useReceivedInvitesQuery(
+ user: { id: string; email: string; emailVerified: boolean } | undefined,
+ params: PageParams,
+) {
+ return useQuery({
+ queryKey: qk.receivedInvitesPage(user?.id ?? '', user?.email ?? '', params),
+ queryFn: () => listReceivedInvites(params),
+ enabled: user?.emailVerified === true,
+ retry: false,
+ });
+}
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 6a328111..99bf8782 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -7,6 +7,9 @@ const scimKey = (workspaceId: number | null) =>
// or key scopes its entry. Kept in one registry so a mutation in one service can
// invalidate another service's queries by the same key.
export const qk = {
+ receivedInvites: ['receivedInvites'] as const,
+ receivedInvitesPage: (userId: string, email: string, params: unknown) =>
+ ['receivedInvites', userId, email, params] as const,
externalRunTrace: (runId: number) => ['externalRunTrace', runId] as const,
runnerQueue: ['runnerQueue'] as const,
issueAgentRuns: (issueId: number) => ['issueAgentRuns', issueId] as const,
diff --git a/apps/web/src/utils/accountSections.ts b/apps/web/src/utils/accountSections.ts
index 64db76cb..16d0c980 100644
--- a/apps/web/src/utils/accountSections.ts
+++ b/apps/web/src/utils/accountSections.ts
@@ -1,6 +1,7 @@
import {
KeyRound,
Link2,
+ Mail,
ShieldCheck,
SlidersHorizontal,
UserRound,
@@ -17,6 +18,7 @@ export const ACCOUNT_SECTIONS: AccountSection[] = [
{ slug: 'profile', icon: UserRound },
{ slug: 'preferences', icon: SlidersHorizontal },
{ slug: 'accounts', icon: Link2 },
+ { slug: 'invitations', icon: Mail },
{ slug: 'security', icon: ShieldCheck },
{ slug: 'api-keys', icon: KeyRound },
];