⭐️⭐️⭐️ 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: keep live updates working when a user sees more than 20 projects (#704)
San Chen8f5e80bcd5d1
diff --git a/apps/api/src/modules/sync/__tests__/integration/sync.test.ts b/apps/api/src/modules/sync/__tests__/integration/sync.test.tsindex 2942a897..d2b7bd67 100644--- a/apps/api/src/modules/sync/__tests__/integration/sync.test.ts+++ b/apps/api/src/modules/sync/__tests__/integration/sync.test.ts@@ -329,6 +329,55 @@ describe('sync', () => {});});+ describe('inbox:all scope', () => {+ // A member of MKT who also joins OPS, a second project of the same team.+ async function twoProjects() {+ const base = await setup();+ const { userId, api: asMember } = await addMember(base.asOwner);+ await createProject(base.asOwner, { key: 'OPS', name: 'Operations' });+ const ops = base.asOwner.projects({ projectKey: 'OPS' });+ await ops.members.post({ userId, role: 'member' });+ const opsColumnId = (await ops.get()).data!.columns[0].id;+ const notifyInOps = () =>+ ops.issues.post({ columnId: opsColumnId, title: 'Task', assigneeUserId: userId });+ return { ...base, userId, asMember, ops, notifyInOps };+ }++ it('moves when an inbox in any of the projects moves', async () => {+ const { asOwner, columnId, userId, asMember, notifyInOps } = await twoProjects();++ const initial = await rev(asMember, 'inbox:all');+ await createIssue(asOwner, columnId, { assigneeUserId: userId });+ const afterMkt = await rev(asMember, 'inbox:all');+ expect(afterMkt).not.toBe(initial);++ await notifyInOps();+ expect(await rev(asMember, 'inbox:all')).not.toBe(afterMkt);+ });++ it('leaves out a project the user can no longer read', async () => {+ const { asOwner, columnId, userId, asMember, ops, notifyInOps } = await twoProjects();+ await createIssue(asOwner, columnId, { assigneeUserId: userId });+ const mktOnly = await rev(asMember, 'inbox:all');++ await notifyInOps();+ expect(await rev(asMember, 'inbox:all')).not.toBe(mktOnly);++ expect((await ops.members({ userId }).delete()).status).toBe(204);+ expect(await rev(asMember, 'inbox:all')).toBe(mktOnly);+ });++ it("never reads someone else's inbox", async () => {+ const { asOwner, columnId } = await setup();+ const { userId } = await addMember(asOwner);+ const before = await rev(asOwner, 'inbox:all');++ await createIssue(asOwner, columnId, { assigneeUserId: userId });++ expect(await rev(asOwner, 'inbox:all')).toBe(before);+ });+ });+describe('access', () => {it('reads a non-member\'s project as "0"', async () => {const { asOwner, projectId, columnId } = await setup();diff --git a/apps/api/src/modules/sync/index.ts b/apps/api/src/modules/sync/index.tsindex 70b3715c..c71709c4 100644--- a/apps/api/src/modules/sync/index.ts+++ b/apps/api/src/modules/sync/index.ts@@ -5,7 +5,7 @@ import { authContext } from '#shared/auth-context';import { requireUser } from '#shared/access';import { HttpError } from '#shared/lib';import { errors } from '#shared/responses';-import { NO_REV, readRevs, scopeKind, type ScopeRead } from './service';+import { inboxAllRevision, NO_REV, readRevs, scopeKind, type ScopeRead } from './service';import { RevResponse, revQuery } from './model';const MAX_SCOPES = 20;@@ -33,7 +33,7 @@ export const syncRoutes = new Elysia({ name: 'sync', detail: { tags: ['Sync'] }// knowing how a scope is stored.const reads = new Map<string, ScopeRead>();for (const scope of requested) {- if (scope === 'runnerQueue:1') continue;+ if (scope === 'runnerQueue:1' || scope === 'inbox:all') continue;const [kind, rawId] = scope.split(':');// Own properties only: an inherited name like '__proto__' is not a kind.const spec = kind && Object.hasOwn(scopeKind, kind) ? scopeKind[kind] : undefined;@@ -51,6 +51,9 @@ export const syncRoutes = new Elysia({ name: 'sync', detail: { tags: ['Sync'] }if (requested.includes('runnerQueue:1')) {revs['runnerQueue:1'] = await runnerQueueRevision(userId, isMcpRequest(request.headers));}+ if (requested.includes('inbox:all')) {+ revs['inbox:all'] = await inboxAllRevision(userId);+ }return { revs };},{diff --git a/apps/api/src/modules/sync/model.ts b/apps/api/src/modules/sync/model.tsindex 867d3f3a..aa4ad4e2 100644--- a/apps/api/src/modules/sync/model.ts+++ b/apps/api/src/modules/sync/model.ts@@ -3,7 +3,7 @@ import { t } from 'elysia';export const revQuery = t.Object({scopes: t.String({description:- "Comma-separated scopes to read, each '<kind>:<id>' — board, issue, initiative, or inbox (by project id).",+ "Comma-separated scopes to read, each '<kind>:<id>' — board, issue, initiative, documents, or inbox (by project id) — plus 'inbox:all' for the inbox of every readable project and 'runnerQueue:1'.",}),});diff --git a/apps/api/src/modules/sync/service.ts b/apps/api/src/modules/sync/service.tsindex be2a90b5..5c269aa8 100644--- a/apps/api/src/modules/sync/service.ts+++ b/apps/api/src/modules/sync/service.ts@@ -1,5 +1,5 @@import { db, project, projectMember, teamRole, revision } from '@repo/db';-import { and, eq, inArray, isNotNull, or } from 'drizzle-orm';+import { and, eq, inArray, isNotNull, or, sql } from 'drizzle-orm';import { toMemberContext, type MemberRole } from '#modules/members/service';import { workspaceGrants } from '#modules/workspaces/service';import { hasPermission, type PermissionResource } from '#shared/permissions';@@ -39,6 +39,13 @@ export interface ScopeRead {resource: PermissionResource | null;}+function memberOrGranted(grantedTeams: number[]) {+ return or(+ isNotNull(projectMember.userId),+ grantedTeams.length > 0 ? inArray(project.teamId, grantedTeams) : undefined,+ );+}+// The markers a client is watching, in one query. A scope of a project the user neither// belongs to nor reaches through their workspace role returns no row and reads as// unchanged. A scope whose resource their access may not read is dropped the same way,@@ -71,10 +78,7 @@ export async function readRevs(revision.scope,wanted.map((w) => w.key),),- or(- isNotNull(projectMember.userId),- grantedTeams.length > 0 ? inArray(project.teamId, grantedTeams) : undefined,- ),+ memberOrGranted(grantedTeams),),);@@ -91,3 +95,22 @@ export async function readRevs(}return out;}++// One marker for the session user's inbox in every project they can read, so the app+// badge watches a single scope however many projects there are. It lists each+// project's marker, so it moves when any inbox moves and when a project is gained or lost.+export async function inboxAllRevision(userId: string): Promise<string> {+ const grantedTeams = [...(await workspaceGrants(userId)).keys()];+ const rows = await db+ .select({ projectId: project.id, rev: revision.rev })+ .from(project)+ .innerJoin(revision, eq(revision.scope, sql`'inbox:' || ${project.id} || ':' || ${userId}`))+ .leftJoin(+ projectMember,+ and(eq(projectMember.projectId, project.id), eq(projectMember.userId, userId)),+ )+ .where(memberOrGranted(grantedTeams))+ .orderBy(project.id);+ if (rows.length === 0) return NO_REV;+ return rows.map((row) => `${row.projectId}=${row.rev}`).join(',');+}diff --git a/apps/web/src/components/layout/Shell.tsx b/apps/web/src/components/layout/Shell.tsxindex 4f925cee..9a6c9613 100644--- a/apps/web/src/components/layout/Shell.tsx+++ b/apps/web/src/components/layout/Shell.tsx@@ -61,7 +61,7 @@ export default function Shell({errorMsg,forbidden,} = useShellProject(projectKey, route.activeViewId);- useAppBadge(projects.map((item) => item.id));+ useAppBadge();const projectName = project?.project.name ?? t('project');// A failed read keeps the last data, so a project that became unreadable is named// generically.diff --git a/apps/web/src/context/syncContext.test.tsx b/apps/web/src/context/syncContext.test.tsxnew file mode 100644index 00000000..5057c8f5--- /dev/null+++ b/apps/web/src/context/syncContext.test.tsx@@ -0,0 +1,95 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act, useEffect } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { JSDOM } from 'jsdom';+import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';+import { SyncProvider, useSyncSubscribe } from './syncContext';++const replacedGlobals = ['window', 'document', 'navigator', 'fetch', 'IS_REACT_ACT_ENVIRONMENT'];++let dom: JSDOM;+let root: Root;+let client: QueryClient;+let saved: Map<string, PropertyDescriptor | undefined>;+let rev: number;+let revRequests: string[][];+let lastScopeReads: number;++const scopes = Array.from({ length: 25 }, (_, i) => `board:${i + 1}`);+const lastScope = scopes[scopes.length - 1];++function Probe() {+ const subscribe = useSyncSubscribe();+ useEffect(() => {+ const off = scopes.map((scope) => subscribe({ scope, targets: [['probe', scope]] }));+ return () => off.forEach((o) => o());+ }, [subscribe]);+ useQuery({ queryKey: ['probe', lastScope], queryFn: () => ++lastScopeReads });+ return null;+}++function setGlobal(name: string, value: unknown) {+ Object.defineProperty(globalThis, name, { configurable: true, writable: true, value });+}++async function settle() {+ for (let i = 0; i < 10; i++) await act(() => new Promise((r) => setTimeout(r, 5)));+}++beforeEach(() => {+ saved = new Map(replacedGlobals.map((n) => [n, Object.getOwnPropertyDescriptor(globalThis, n)]));+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://web.test/' });+ rev = 1;+ revRequests = [];+ lastScopeReads = 0;+ setGlobal('window', dom.window);+ setGlobal('document', dom.window.document);+ setGlobal('navigator', dom.window.navigator);+ setGlobal('IS_REACT_ACT_ENVIRONMENT', true);+ setGlobal('fetch', async (input: string) => {+ const url = new URL(input);+ const requested = url.searchParams.get('scopes')!.split(',');+ revRequests.push(requested);+ if (requested.length > 20) return new Response('{}', { status: 400 });+ const revs = Object.fromEntries(requested.map((s) => [s, String(rev)]));+ return new Response(JSON.stringify({ revs }), {+ headers: { 'content-type': 'application/json' },+ });+ });+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ root = createRoot(dom.window.document.getElementById('root')!);+});++afterEach(() => {+ act(() => root.unmount());+ client.clear();+ for (const [name, descriptor] of saved) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else delete (globalThis as Record<string, unknown>)[name];+ }+});++describe('SyncProvider', () => {+ it('reads more scopes than one request takes in batches', async () => {+ await act(async () =>+ root.render(+ <QueryClientProvider client={client}>+ <SyncProvider>+ <Probe />+ </SyncProvider>+ </QueryClientProvider>,+ ),+ );+ await settle();++ assert.ok(revRequests.every((r) => r.length <= 20));+ assert.deepEqual(revRequests.slice(-2).flat().sort(), [...scopes].sort());++ const reads = lastScopeReads;+ rev = 2;+ await act(() => client.invalidateQueries({ queryKey: ['sync', 'rev'] }));+ await settle();+ assert.equal(lastScopeReads, reads + 1);+ });+});diff --git a/apps/web/src/context/syncContext.tsx b/apps/web/src/context/syncContext.tsxindex 945ade90..6776e897 100644--- a/apps/web/src/context/syncContext.tsx+++ b/apps/web/src/context/syncContext.tsx@@ -13,9 +13,8 @@ import { useQuery, useQueryClient, type QueryKey } from '@tanstack/react-query';import { getRevs } from '@/lib/api/endpoints/sync';// One poll for the whole app. Every screen that wants to stay live registers the-// scopes it depends on (see useLiveRefresh); this provider asks the API for their-// change markers in a single request and invalidates the queries of the scopes that-// moved. The heavy reads happen only on an actual change.+// scopes it depends on (see useLiveRefresh); this provider polls the API for their+// change markers and invalidates the queries of the scopes that moved. The heavy reads happen only on an actual change.//// Polling pauses while the tab is in the background — TanStack does not refetch on// an interval there — and stops when nothing is registered.diff --git a/apps/web/src/hooks/useAppBadge.test.tsx b/apps/web/src/hooks/useAppBadge.test.tsxindex e57f875c..9207ca38 100644--- a/apps/web/src/hooks/useAppBadge.test.tsx+++ b/apps/web/src/hooks/useAppBadge.test.tsx@@ -18,8 +18,8 @@ let rev: number;let badge: (number | 'cleared')[];let requests: string[];-function Probe({ projectIds }: { projectIds: number[] }) {- useAppBadge(projectIds);+function Probe() {+ useAppBadge();return null;}@@ -35,12 +35,12 @@ async function settle() {for (let i = 0; i < 10; i++) await act(() => new Promise((r) => setTimeout(r, 5)));}-async function render(projectIds: number[]) {+async function render() {await act(async () =>root.render(<QueryClientProvider client={client}><SyncProvider>- <Probe projectIds={projectIds} />+ <Probe /></SyncProvider></QueryClientProvider>,),@@ -65,7 +65,7 @@ beforeEach(() => {setGlobal('fetch', async (input: string) => {const path = new URL(input).pathname + new URL(input).search;requests.push(path);- if (path.startsWith('/sync/rev')) return json({ revs: { 'inbox:7': String(rev) } });+ if (path.startsWith('/sync/rev')) return json({ revs: { 'inbox:all': String(rev) } });if (path === '/notifications/unread') return json({ unread });return json({});});@@ -84,14 +84,17 @@ afterEach(() => {describe('useAppBadge', () => {it('shows the unread total across projects on the app icon', async () => {- await render([7, 8]);+ await render();assert.deepEqual(badge, [2]);assert.ok(requests.includes('/notifications/unread'));- assert.ok(requests.some((p) => p.startsWith('/sync/rev') && p.includes('inbox:8')));+ assert.deepEqual(+ requests.filter((p) => p.startsWith('/sync/rev')),+ ['/sync/rev?scopes=inbox:all'],+ );});- it('clears the badge when an inbox scope moves and nothing is unread', async () => {- await render([7]);+ it('clears the badge when the inbox scope moves and nothing is unread', async () => {+ await render();unread = 0;rev = 2;await act(() => client.invalidateQueries({ queryKey: ['sync', 'rev'] }));@@ -101,7 +104,7 @@ describe('useAppBadge', () => {it('does nothing where the browser has no Badging API', async () => {delete (dom.window.navigator as unknown as Record<string, unknown>).setAppBadge;- await render([7]);+ await render();assert.deepEqual(badge, []);assert.ok(!requests.includes('/notifications/unread'));});diff --git a/apps/web/src/hooks/useAppBadge.ts b/apps/web/src/hooks/useAppBadge.tsindex e04e314a..cedb2f27 100644--- a/apps/web/src/hooks/useAppBadge.ts+++ b/apps/web/src/hooks/useAppBadge.ts@@ -7,22 +7,16 @@ import { revScope } from '@/utils/revScopes';// Shows the signed-in user's unread notifications, across every project, on the app// icon through the Badging API: the Dock or taskbar badge of the installed web app, or-// of a desktop shell that forwards it. Refetched when any project's inbox scope moves.+// of a desktop shell that forwards it. Refetched when the inbox of any project moves.// Where the browser has no Badging API it does nothing and fetches nothing.-export function useAppBadge(projectIds: number[]) {+export function useAppBadge() {const supported = typeof navigator !== 'undefined' && 'setAppBadge' in navigator;const subscribe = useSyncSubscribe();- const ids = projectIds.join(',');useEffect(() => {- if (!supported || !ids) return;- const unsubscribe = ids- .split(',')- .map((id) =>- subscribe({ scope: revScope.inbox(Number(id)), targets: [qk.notificationsUnreadTotal] }),- );- return () => unsubscribe.forEach((off) => off());- }, [supported, ids, subscribe]);+ if (!supported) return;+ return subscribe({ scope: revScope.inboxAll, targets: [qk.notificationsUnreadTotal] });+ }, [supported, subscribe]);const { data: unread } = useQuery({queryKey: qk.notificationsUnreadTotal,diff --git a/apps/web/src/lib/api/endpoints/sync.ts b/apps/web/src/lib/api/endpoints/sync.tsindex 152bcf88..1c2ca4a4 100644--- a/apps/web/src/lib/api/endpoints/sync.ts+++ b/apps/web/src/lib/api/endpoints/sync.ts@@ -1,6 +1,16 @@import { request } from '@/lib/api/core/client';-// The change markers of every scope the client is watching, in one request.-// Polled by the sync provider; see utils/revScopes.-export const getRevs = (scopes: string[]) =>- request<{ revs: Record<string, string> }>(`/sync/rev?scopes=${scopes.join(',')}`);+// The API's limit on scopes per request (MAX_SCOPES in apps/api/src/modules/sync).+const MAX_SCOPES = 20;++// The change markers of every scope the client is watching. Polled by the sync+// provider; see utils/revScopes.+export async function getRevs(scopes: string[]): Promise<{ revs: Record<string, string> }> {+ const batches = [];+ for (let i = 0; i < scopes.length; i += MAX_SCOPES) {+ const batch = scopes.slice(i, i + MAX_SCOPES);+ batches.push(request<{ revs: Record<string, string> }>(`/sync/rev?scopes=${batch.join(',')}`));+ }+ const results = await Promise.all(batches);+ return { revs: Object.assign({}, ...results.map((r) => r.revs)) };+}diff --git a/apps/web/src/utils/revScopes.ts b/apps/web/src/utils/revScopes.tsindex 960d6354..5f86e56c 100644--- a/apps/web/src/utils/revScopes.ts+++ b/apps/web/src/utils/revScopes.ts@@ -1,11 +1,13 @@// Names of the change-marker scopes a screen can watch, mirroring the kinds the-// API accepts on GET /sync/rev. The inbox is asked for by project — the server-// answers with the session user's own, so the user id never appears here.+// API accepts on GET /sync/rev. The inbox is asked for by project, or for every+// project at once — the server answers with the session user's own, so the user id+// never appears here.export const revScope = {runnerQueue: 'runnerQueue:1',board: (projectId: number) => `board:${projectId}`,issue: (issueId: number) => `issue:${issueId}`,initiative: (initiativeId: number) => `initiative:${initiativeId}`,inbox: (projectId: number) => `inbox:${projectId}`,+ inboxAll: 'inbox:all',documents: (projectId: number) => `documents:${projectId}`,};diff --git a/docs/dev/revision-engine.md b/docs/dev/revision-engine.mdindex a833a560..7fc1b499 100644--- a/docs/dev/revision-engine.md+++ b/docs/dev/revision-engine.md@@ -33,7 +33,8 @@ and never do arithmetic on it, so gaps in the numbers are harmless.| `board:<projectId>` | the work items board | any issue, label, relation, initiative or cycle in the project changes || `issue:<issueId>` | the issue screen | the issue, its comments, checklists, attachments or field values change || `initiative:<initiativeId>` | the initiative screen | the initiative or any issue inside it changes |-| `inbox:<projectId>:<userId>` | the inbox and the badge | that user gets a notification, reads one, or deletes one |+| `inbox:<projectId>:<userId>` | the inbox | that user gets a notification, reads one, or deletes one |+| `inbox:all` | the app icon badge | any `inbox:<projectId>:<userId>` of a project the user can read moves, or such a project is gained or lost |Comments deliberately do not move the board: the board does not show them, so refetching itwould be wasted work.@@ -41,13 +42,18 @@ would be wasted work.The inbox is the one scope that belongs to a person rather than an entity. Clients ask for`inbox:12` and the API fills in the session user, so one person can never watch another's inbox.+`inbox:all` has no row of its own. The API reads the session user's inbox row of every project+they can read and answers with the list of `<projectId>=<rev>` pairs, so the badge watches one+scope however many projects the user sees. A sum of the counters would be shorter, but it can+come back to an earlier value when a project is lost while another inbox moves.+## Where the code lives| File | What it holds || -------------------------------------- | -------------------------------------------------------- || `packages/db/drizzle/0070_*.sql` | `bump_rev`, the trigger functions, and their triggers |-| `apps/api/src/sync/store.ts` | the scope names and the read query |-| `apps/api/src/sync/routes.ts` | `GET /sync/rev` |+| `apps/api/src/modules/sync/service.ts` | the scope names and the read queries |+| `apps/api/src/modules/sync/index.ts` | `GET /sync/rev` || `apps/web/src/context/syncContext.tsx` | the one poll every screen shares || `apps/web/src/hooks/useLiveRefresh.ts` | what a screen calls || `apps/web/src/utils/revScopes.ts` | the scope names on the client |@@ -67,8 +73,9 @@ useLiveRefresh({That is the whole integration. No screen runs its own timer: `SyncProvider` collects the scopesof everything currently mounted, asks for them in one request, and invalidates the targets of-the scopes that moved. The poll stops while the tab sits in the background, and while nothing is-registered.+the scopes that moved. The API takes at most 20 scopes per request; `getRevs` splits a longer+list into requests of 20 and merges the answers. The poll stops while the tab sits in the+background, and while nothing is registered.## Reading the counters@@ -109,7 +116,7 @@ the migration. `rev_checklist_item()` is the example to copy: it goes from## Adding a new scopeA new kind of scope touches two more places: the entry in `scopeKind` in-`apps/api/src/sync/store.ts`, which names it, makes the API accept it, and says which resource a+`apps/api/src/modules/sync/service.ts`, which names it, makes the API accept it, and says which resource awatcher must be allowed to read, and the mirror in `apps/web/src/utils/revScopes.ts`.`packages/db/AGENTS.md` keeps the same recipe next to the schema.diff --git a/packages/db/AGENTS.md b/packages/db/AGENTS.mdindex fa982e31..70f7b4f6 100644--- a/packages/db/AGENTS.md+++ b/packages/db/AGENTS.md@@ -80,7 +80,7 @@ order in which they take the scopes (board, then issue, then initiative, and twoone kind in id order), which is what stops two writers from deadlocking on thecounters.-A new scope kind also needs its entry in `apps/api/src/sync/store.ts` — its name and+A new scope kind also needs its entry in `apps/api/src/modules/sync/service.ts` — its name andthe resource a watcher must be allowed to read — and the mirror in`apps/web/src/utils/revScopes.ts`.