⭐️⭐️⭐️ 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
fix(web): the start page no longer stays on Loading forever (#782)
Pasqual Troncone9b85a0d78c4f
diff --git a/apps/web/messages/ar/shell.json b/apps/web/messages/ar/shell.jsonindex 57e55490..f1911793 100644--- a/apps/web/messages/ar/shell.json+++ b/apps/web/messages/ar/shell.json@@ -10,5 +10,7 @@"createTeam": "إنشاء فريق","noProjectsTitle": "لا توجد مشاريع بعد","noProjectsHint": "اعمل أول مشروع ليك وابدأ تخطّط مهامك على لوحة.",- "createProject": "إنشاء مشروع"+ "createProject": "إنشاء مشروع",+ "loadFailedTitle": "تعذّر تحميل مشاريعك",+ "loadFailedHint": "تأكد من الاتصال وأعد تحميل الصفحة."}diff --git a/apps/web/messages/en/shell.json b/apps/web/messages/en/shell.jsonindex 788705b7..aceb6827 100644--- a/apps/web/messages/en/shell.json+++ b/apps/web/messages/en/shell.json@@ -10,5 +10,7 @@"createTeam": "Create team","noProjectsTitle": "No projects yet","noProjectsHint": "Create your first project to start planning issues on a board.",- "createProject": "Create project"+ "createProject": "Create project",+ "loadFailedTitle": "Could not load your projects",+ "loadFailedHint": "Check your connection and reload the page."}diff --git a/apps/web/messages/es-ES/shell.json b/apps/web/messages/es-ES/shell.jsonindex 5bd8b4b4..b3b312bf 100644--- a/apps/web/messages/es-ES/shell.json+++ b/apps/web/messages/es-ES/shell.json@@ -10,5 +10,7 @@"createTeam": "Crear equipo","noProjectsTitle": "Todavía no hay proyectos","noProjectsHint": "Crea tu primer proyecto para empezar a planificar tickets en un tablero.",- "createProject": "Crear proyecto"+ "createProject": "Crear proyecto",+ "loadFailedTitle": "No se pudieron cargar tus proyectos",+ "loadFailedHint": "Comprueba tu conexión y vuelve a cargar la página."}diff --git a/apps/web/messages/fa/shell.json b/apps/web/messages/fa/shell.jsonindex 5504ceb4..c5ce255c 100644--- a/apps/web/messages/fa/shell.json+++ b/apps/web/messages/fa/shell.json@@ -10,5 +10,7 @@"createTeam": "ساخت تیم","noProjectsTitle": "هنوز پروژهای نیست","noProjectsHint": "اولین پروژه خود را بسازید تا برنامهریزی تسکها را روی برد شروع کنید.",- "createProject": "ساخت پروژه"+ "createProject": "ساخت پروژه",+ "loadFailedTitle": "بارگذاری پروژههای شما ممکن نشد",+ "loadFailedHint": "اتصال خود را بررسی کنید و صفحه را دوباره بارگذاری کنید."}diff --git a/apps/web/messages/fr/shell.json b/apps/web/messages/fr/shell.jsonindex 5411cf48..ca3b89e1 100644--- a/apps/web/messages/fr/shell.json+++ b/apps/web/messages/fr/shell.json@@ -10,5 +10,7 @@"createTeam": "Créer une équipe","noProjectsTitle": "Aucun projet pour l'instant","noProjectsHint": "Créez votre premier projet pour commencer à organiser vos tickets sur un tableau.",- "createProject": "Créer un projet"+ "createProject": "Créer un projet",+ "loadFailedTitle": "Impossible de charger vos projets",+ "loadFailedHint": "Vérifiez votre connexion et rechargez la page."}diff --git a/apps/web/messages/id/shell.json b/apps/web/messages/id/shell.jsonindex 6ecc9071..dd919a32 100644--- a/apps/web/messages/id/shell.json+++ b/apps/web/messages/id/shell.json@@ -10,5 +10,7 @@"createTeam": "Buat tim","noProjectsTitle": "Belum ada proyek","noProjectsHint": "Buat proyek pertama Anda untuk mulai merencanakan issue di papan.",- "createProject": "Buat proyek"+ "createProject": "Buat proyek",+ "loadFailedTitle": "Proyek Anda tidak dapat dimuat",+ "loadFailedHint": "Periksa koneksi Anda, lalu muat ulang halaman."}diff --git a/apps/web/messages/ko/shell.json b/apps/web/messages/ko/shell.jsonindex bca851fe..e2006790 100644--- a/apps/web/messages/ko/shell.json+++ b/apps/web/messages/ko/shell.json@@ -10,5 +10,7 @@"createTeam": "팀 생성","noProjectsTitle": "아직 프로젝트가 없습니다","noProjectsHint": "첫 프로젝트를 생성하고 보드에서 이슈 계획을 시작하세요.",- "createProject": "프로젝트 생성"+ "createProject": "프로젝트 생성",+ "loadFailedTitle": "프로젝트를 불러올 수 없습니다",+ "loadFailedHint": "연결을 확인하고 페이지를 새로고침하세요."}diff --git a/apps/web/messages/pt-BR/shell.json b/apps/web/messages/pt-BR/shell.jsonindex 6f22dab4..896c07bf 100644--- a/apps/web/messages/pt-BR/shell.json+++ b/apps/web/messages/pt-BR/shell.json@@ -10,5 +10,7 @@"createTeam": "Criar equipe","noProjectsTitle": "Nenhum projeto ainda","noProjectsHint": "Crie seu primeiro projeto para começar a planejar issues em um quadro.",- "createProject": "Criar projeto"+ "createProject": "Criar projeto",+ "loadFailedTitle": "Não foi possível carregar seus projetos",+ "loadFailedHint": "Verifique sua conexão e recarregue a página."}diff --git a/apps/web/messages/ru/shell.json b/apps/web/messages/ru/shell.jsonindex 23950f03..3c125ef6 100644--- a/apps/web/messages/ru/shell.json+++ b/apps/web/messages/ru/shell.json@@ -10,5 +10,7 @@"createTeam": "Создать команду","noProjectsTitle": "Проектов пока нет","noProjectsHint": "Создайте первый проект, чтобы планировать задачи на доске.",- "createProject": "Создать проект"+ "createProject": "Создать проект",+ "loadFailedTitle": "Не удалось загрузить ваши проекты",+ "loadFailedHint": "Проверьте подключение и перезагрузите страницу."}diff --git a/apps/web/messages/tr/shell.json b/apps/web/messages/tr/shell.jsonindex 849a95bb..e25a2a43 100644--- a/apps/web/messages/tr/shell.json+++ b/apps/web/messages/tr/shell.json@@ -10,5 +10,7 @@"createTeam": "Takım oluştur","noProjectsTitle": "Henüz proje yok","noProjectsHint": "İşleri bir pano üzerinde planlamaya başlamak için ilk projenizi oluşturun.",- "createProject": "Proje oluştur"+ "createProject": "Proje oluştur",+ "loadFailedTitle": "Projeleriniz yüklenemedi",+ "loadFailedHint": "Bağlantınızı kontrol edin ve sayfayı yeniden yükleyin."}diff --git a/apps/web/messages/uk/shell.json b/apps/web/messages/uk/shell.jsonindex 4d7ed3df..014b12b9 100644--- a/apps/web/messages/uk/shell.json+++ b/apps/web/messages/uk/shell.json@@ -10,5 +10,7 @@"createTeam": "Створити команду","noProjectsTitle": "Проєктів ще немає","noProjectsHint": "Створіть перший проєкт, щоб планувати задачі на дошці.",- "createProject": "Створити проєкт"+ "createProject": "Створити проєкт",+ "loadFailedTitle": "Не вдалося завантажити ваші проєкти",+ "loadFailedHint": "Перевірте з’єднання та перезавантажте сторінку."}diff --git a/apps/web/messages/zh-CN/shell.json b/apps/web/messages/zh-CN/shell.jsonindex 963235fa..29bf16d7 100644--- a/apps/web/messages/zh-CN/shell.json+++ b/apps/web/messages/zh-CN/shell.json@@ -10,5 +10,7 @@"createTeam": "创建团队","noProjectsTitle": "暂无项目","noProjectsHint": "新建第一个项目,然后开始在看板中规划工作项。",- "createProject": "新建项目"+ "createProject": "新建项目",+ "loadFailedTitle": "无法加载项目",+ "loadFailedHint": "请检查网络连接并刷新页面。"}diff --git a/apps/web/messages/zh-TW/shell.json b/apps/web/messages/zh-TW/shell.jsonindex 6e74f84e..cbe55ee8 100644--- a/apps/web/messages/zh-TW/shell.json+++ b/apps/web/messages/zh-TW/shell.json@@ -10,5 +10,7 @@"createTeam": "建立團隊","noProjectsTitle": "暫無專案","noProjectsHint": "新建第一個專案,然後開始在看板中規劃工作項目。",- "createProject": "新建專案"+ "createProject": "新建專案",+ "loadFailedTitle": "無法載入專案",+ "loadFailedHint": "請檢查網路連線並重新整理頁面。"}diff --git a/apps/web/src/app/page.test.tsx b/apps/web/src/app/page.test.tsxnew file mode 100644index 00000000..9e5684c3--- /dev/null+++ b/apps/web/src/app/page.test.tsx@@ -0,0 +1,153 @@+import assert from 'node:assert/strict';+import { createRequire } from 'node:module';+import { afterEach, beforeEach, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { NextIntlClientProvider } from 'next-intl';+import { AppRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';+import { JSDOM } from 'jsdom';+import { projectPath } from '@/utils/paths';+import common from '../../messages/en/common.json';+import shell from '../../messages/en/shell.json';++type SessionSnapshot = ReturnType<(typeof import('@/lib/auth-client'))['useSession']>;+// Loading the test helper without Bun's globals preserves the web app's fetch type.+const { spyOn } = createRequire(import.meta.url)('bun:test') as {+ spyOn: (+ target: object,+ method: string,+ ) => {+ mockImplementation: (implementation: () => SessionSnapshot) => { mockRestore: () => void };+ };+};++const project = { id: 1, ref: 'acme.SUP', isHidden: false, isFavorite: false };+const lastProject = { id: 2, ref: 'acme.OPS', isHidden: false, isFavorite: false };+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 restoreSession: () => void;+let replaced: string[];+let answer: (path: string) => Response;+let session: { user: { id: string } } | null;++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/' });+ Object.assign(dom.window, { __ITSAPLAN_ENV__: { apiUrl: 'http://api.test' } });+ replaced = [];+ session = null;+ answer = (path) => Response.json(path === '/projects' ? [project] : []);+ 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) => answer(new URL(String(input)).pathname),+ },+ });+ const auth = await import('@/lib/auth-client');+ const sessionSpy = spyOn(auth, 'useSession').mockImplementation(+ () => ({ data: session, isPending: false, error: null, refetch: async () => {} }) as never,+ );+ restoreSession = () => sessionSpy.mockRestore();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+});++afterEach(() => {+ act(() => root.unmount());+ restoreSession();+ 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 renderHome() {+ const { default: Home } = await import('./page');+ const { createRoot } = await import('react-dom/client');+ root = createRoot(document.getElementById('root')!);+ const router = {+ replace: (path: string) => replaced.push(path),+ push() {},+ refresh() {},+ back() {},+ forward() {},+ prefetch() {},+ };+ await act(async () => {+ root.render(+ <AppRouterContext.Provider value={router as never}>+ <QueryClientProvider client={client}>+ <NextIntlClientProvider locale="en" messages={{ common, shell }} timeZone="UTC">+ <Home />+ </NextIntlClientProvider>+ </QueryClientProvider>+ </AppRouterContext.Provider>,+ );+ });+ // The page decides once its reads settle, a few ticks after the first render.+ for (let tick = 0; tick < 10; tick++) {+ await act(() => new Promise((resolve) => setTimeout(resolve, 20)));+ }+}++it('reopens the last-used project from the preferences when the client has a session', async () => {+ session = { user: { id: 'user-1' } };+ answer = (path) => {+ if (path === '/projects') return Response.json([project, lastProject]);+ if (path === '/account/preferences') return Response.json({ lastProjectId: lastProject.id });+ return Response.json([]);+ };++ await renderHome();++ assert.deepEqual(replaced, [projectPath(lastProject.ref)]);+});++// better-auth reports no session when its session request failed or came back empty.+it('opens the project when the client has no session to read the preferences with', async () => {+ await renderHome();++ assert.deepEqual(replaced, [projectPath(project.ref)]);+});++it('says the projects could not be loaded instead of loading forever', async () => {+ answer = (path) =>+ path === '/projects'+ ? Response.json({ error: 'Unavailable' }, { status: 500 })+ : Response.json([]);++ await renderHome();++ assert.ok(document.body.textContent?.includes(shell.loadFailedTitle));+ assert.deepEqual(replaced, []);+});++it('says the projects could not be loaded when the list is empty and the teams fail', async () => {+ answer = (path) =>+ path === '/teams'+ ? Response.json({ error: 'Unavailable' }, { status: 500 })+ : Response.json([]);++ await renderHome();++ assert.ok(document.body.textContent?.includes(shell.loadFailedTitle));+});diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsxindex fe01a4bd..10f4e067 100644--- a/apps/web/src/app/page.tsx+++ b/apps/web/src/app/page.tsx@@ -3,8 +3,9 @@import { useEffect, useState } from 'react';import { useRouter } from 'next/navigation';import { useTranslations } from 'next-intl';-import { SquareKanban, Users } from 'lucide-react';+import { CloudOff, SquareKanban, Users } from 'lucide-react';import { NoTeamStart } from '@/cloud';+import { useSession } from '@/lib/auth-client';import { useProjectsQuery } from '@/services/projects.service';import { useTeamsQuery } from '@/services/teams.service';import { useWorkspacesQuery } from '@/services/workspaces.service';@@ -17,30 +18,35 @@ 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-// the project list and the preferences before deciding so it does not flash the-// wrong destination. With no projects at all, an account that owns or manages a team-// is offered to create the first one there. An account that may create a team in a-// workspace, its own first, is offered to; one with no team and nowhere to create one gets-// `NoTeamStart`, and a team member is told who adds them to a project.+// first visible favorite or project, on the user's preferred start page. Waits for the+// project list and, when the client has a session, the preferences before deciding so+// it does not flash the wrong destination, and says so when a list it needs cannot be+// read. With no projects at all, an account that owns or manages a team is offered to+// create the first one there. An account that may create a team in a workspace, its own+// first, is offered to; one with no team and nowhere to create one gets `NoTeamStart`,+// and a team member is told who adds them to a project.export default function Home() {const t = useTranslations('shell');const tCommon = useTranslations('common');const router = useRouter();- const { data: teams } = useTeamsQuery();- const { data: workspaces } = useWorkspacesQuery();- const { data: projects } = useProjectsQuery();+ const { data: teams, isError: teamsFailed } = useTeamsQuery();+ const { data: workspaces, isError: workspacesFailed } = useWorkspacesQuery();+ const { data: projects, isError: projectsFailed } = useProjectsQuery();+ const { data: session, isPending: sessionPending } = useSession();const { data: prefs, isPending: prefsPending } = useAccountPreferencesQuery();+ // The preferences are read only once the client has the session. Without one (its+ // request failed or came back empty) they never load, so the default start page is used.+ const prefsSettled = session ? !prefsPending : !sessionPending;const [creating, setCreating] = useState(false);useEffect(() => {- if (projects == null || projects.length === 0 || prefsPending) return;+ if (projects == null || projects.length === 0 || !prefsSettled) return;const visible = projects.filter((project) => !project.isHidden);if (visible.length === 0) return;const last = visible.find((p) => p.id === prefs?.lastProjectId);const target = last?.ref ?? visible.find((p) => p.isFavorite)?.ref ?? visible[0]?.ref;if (target) router.replace(startPagePath(target, prefs?.startPage ?? 'work-items'));- }, [projects, prefs, prefsPending, router]);+ }, [projects, prefs, prefsSettled, router]);if (projects && projects.length > 0 && projects.every((project) => project.isHidden)) {return <ProjectSwitcherHiddenState projects={projects} />;@@ -105,6 +111,15 @@ export default function Home() {);}+ const loadFailed = projects+ ? projects.length === 0 && (teamsFailed || workspacesFailed)+ : projectsFailed;+ if (loadFailed) {+ return (+ <StartEmpty icon={<CloudOff />} title={t('loadFailedTitle')} hint={t('loadFailedHint')} />+ );+ }+return (<div className="flex h-svh items-center justify-center bg-background text-sm text-muted-foreground">{tCommon('loading')}