feat(PBI-74): Zustand product-workspace rearchitecture (Stories 1-8) (#180)

* feat(PBI-74): product-workspace store skelet + test-infra (Story 1)

Skelet voor de nieuwe `product-workspace-store` die op termijn de gefragmenteerde
`backlog-store`/`planner-store`/`selection-store`/`product-store` vervangt. Deze
PR levert alleen het skelet + tests; UI-consumers worden in latere stories
omgezet.

- vitest naar jsdom + tests/setup.ts (MemoryStorage, default fetch-stub) — G6/G8
- stores/product-workspace/{types,store,selectors,restore}.ts — immer-middleware,
  alle slices en acties (hydrate, setActive*, ensure*Loaded met activeRequestId-
  guard, applyRealtimeEvent, resyncActiveScopes/loadedScopes, optimistic
  mutations). Restore-wiring in setters volgt in Story 4 (T-857/T-858).
- selectors gebruiken module-level EMPTY refs (G1) en documenteren useShallow-
  vereiste (G2)
- 34 nieuwe unit-tests dekken §Testing setup-checklist uit het ontwerp:
  hydrateSnapshot, selection-cascade, applyRealtimeEvent (I/U/D + parent-move +
  ander-product + unknown-entity → resync), delete-cleanup, race-safe loaders,
  ensureTaskLoaded _detail-flag, resyncActiveScopes ensure-keten, restore-hints
  read/write/clear, optimistic mutation rollback/settle/SSE-echo idempotent
- docs/api/rest-contract.md: audit-sectie met de vier ontbrekende
  ensure*Loaded-endpoints (worden toegevoegd in Story 7 / T-870)

Refs: PBI-74, ST-1318, T-837..T-843
Bron-ontwerp: docs/plans/zustand-store-rearchitecture.md
Implementatieplan: docs/plans/zustand-workspace-store-implementation.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): dual-dispatch hydratie + realtime naar workspace-store (Story 2)

Story 2 — schaduw-fase: BacklogHydrationWrapper en useBacklogRealtime voeden
nu ook de nieuwe product-workspace-store, terwijl de oude useBacklogStore /
useProductStore leidend blijft voor componenten. Story 3 verschuift consumers
één voor één; Story 8 ruimt de oude stores op.

- T-844: BacklogHydrationWrapper roept naast useBacklogStore.setInitialData
  ook useProductWorkspaceStore.hydrateSnapshot aan. Productname-prop optioneel
  toegevoegd voor activeProduct-context.
- T-845: useBacklogRealtime onmessage dispatcht events naar zowel oude store
  (applyChange) als nieuwe store (applyRealtimeEvent). Geen wijziging aan
  reconnect/visibility — Story 5.
- T-846: dev-only logWorkspaceFingerprint helper vergelijkt counts tussen
  oude en nieuwe store na hydrate en na elk realtime-event. console.warn bij
  mismatch; opt-in debug log via NEXT_PUBLIC_DEBUG_WORKSPACE_FINGERPRINT=1.
  Bestand TODO-marked voor verwijdering in Story 8 (T-878).
- T-847: SetCurrentProduct schrijft naast oude useProductStore ook
  useProductWorkspaceStore.setActiveProduct({id, name}); cleanup cleart beide.
  setActiveProduct triggert ensureProductLoaded — fetch-stub tot Story 7
  (T-870) de LIST-endpoints toevoegt.

Verify: lint+typecheck clean, 636/636 tests groen (geen UI-regressie omdat
oude store leidend blijft).

Refs: PBI-74, ST-1319, T-844..T-847

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): migreer backlog-componenten naar workspace-store (Story 3)

Story 3 verplaatst alle UI-consumers van de oude vier stores
(useBacklogStore/usePlannerStore/useSelectionStore/useProductStore) naar de
nieuwe product-workspace-store. De oude stores blijven nog bestaan voor
hydration-wrapper en realtime-hook (dual-dispatch); Story 8 ruimt ze op.

- T-848 backlog-split-pane.tsx: leest activePbiId/activeStoryId uit
  context-slice (primitives, geen useShallow nodig).
- T-849 pbi-list.tsx: selectVisiblePbis(useShallow); DnD via
  applyOptimisticMutation('pbi-order' + optionele 'entity-patch' bij
  cross-priority drag), met settle/rollback per server-result.
- T-850 story-panel.tsx: selectStoriesForActivePbi(useShallow); DnD via
  applyOptimisticMutation('story-order' + entity-patch bij priority change).
- T-851 task-panel.tsx: selectTasksForActiveStory(useShallow); DnD via
  applyOptimisticMutation('task-order'); detail-view (ensureTaskLoaded +
  isDetail) zit in de task-dialog (apart component, niet in deze lijst).
- T-852 start-sprint-button.tsx: selectActivePbi + selectStoriesForActivePbi
  voor free-story count.
- T-853 set-current-product.tsx: alleen workspace-store.setActiveProduct
  (oude useProductStore-import verwijderd).
- T-854 G1/G2-audit: alle nieuwe selectors gebruiken module-level EMPTY
  refs (G1) en useShallow voor lijsten (G2). Geen 'Maximum update depth'-
  warnings tijdens npm test.
- T-855 tests bijgewerkt: backlog-split-pane.test, task-panel.test,
  integration.test gebruiken nu setState op workspace-store (helpers
  resetWorkspace/setActiveStoryAndTasks/selectPbi/selectStory).

Verify: lint+typecheck clean, 636/636 tests groen. UI-consumers van
oude stores zijn nu nul (uitgezonderd dual-dispatch in hydration-wrapper en
realtime-hook + dev-fingerprint-helper, die in Story 8/T-873/T-878 verdwijnen).

Refs: PBI-74, ST-1320, T-848..T-855

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): race-safe loaders + restore-hints + URL-prioriteit (Story 4)

- T-856: activeRequestId-guard zat al in store.ts uit Story 1; bevestigd door
  de race-safety test (in-flight ensurePbiLoaded mag niet overschrijven).
- T-857: restore-hint flow toegevoegd in setActiveProduct/setActivePbi/
  setActiveStory. Async chain: await ensureXxxLoaded → guard check →
  readHints → valideer hint via entities.byId → setActiveYyy(hint).
  Geen setTimeout-trick — chain is alleen await-based.
- T-858: writeProductHint/writePbiHint/writeStoryHint/writeTaskHint
  aangeroepen direct na set(...) zodat de hint-persistentie altijd
  consistent is met de in-store selectie.
- T-859: nieuwe components/backlog/url-task-sync.tsx — leest
  ?editTask=&lt;id&gt; uit useSearchParams, schrijft de hint en roept
  setActiveTask aan zodat de URL wint boven een eerder gepersisteerde
  task-hint. Gemount in beide product-pages (desktop + mobile) binnen
  BacklogHydrationWrapper.
- T-860: 6 nieuwe vitest-cases — 4 voor hint-persist per setter, 2 voor de
  restore-flow chain (hint die niet in entities zit wordt genegeerd; hint
  die wel in entities zit wordt toegepast). Bestaande race-safety test
  blijft groen.

Verify: lint+typecheck clean, 642/642 tests groen.

Refs: PBI-74, ST-1321, T-856..T-860

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): hidden-tab + reconnect resync (Story 5)

Per ontwerp samen in één commit zodat geen vangnet wegvalt zonder vervanging.

- T-861: useBacklogRealtime sluit niet meer op visibilitychange hidden;
  EventSource blijft open zolang browser/netwerk dit toelaten. Reconnect bij
  netwerkfout blijft via backoff. visibilitychange fungeert nog wel als
  re-connect-trigger als de stream tussentijds is gesloten (b.v. 240s
  hard-close server-side).
- T-862: 'ready'-event-handler telt connect-cycles. De eerste 'ready' is de
  initial connect (geen resync). Bij latere 'ready' (post-reconnect) wordt
  resyncActiveScopes('reconnect') aangeroepen om gemiste events op te halen.
- T-863: nieuwe lib/realtime/use-workspace-resync.ts — luistert op
  document.visibilitychange (hidden→visible) en window.online; dispatcht
  resyncActiveScopes('visible') resp. 'reconnect'. Mounted in
  BacklogHydrationWrapper na useBacklogRealtime.
- T-864: 4 nieuwe vitest-cases voor useWorkspaceResync (jsdom): visible→
  visible event, online event, hidden negeren, cleanup-bij-unmount.

Daarnaast lint-cleanup: ongebruikte 'order'-variabelen in pbi-list en
story-panel weggehaald.

Verify: lint+typecheck clean, 646/646 tests groen.

Refs: PBI-74, ST-1322, T-861..T-864

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): unknown-event fallback tests (Story 6)

T-865 (isUnknownEntityEvent filter) en T-866 (resync-trigger in
applyRealtimeEvent) zijn al in Story 1 geïmplementeerd in store.ts;
deze story breidt de test-coverage uit met expliciete negatieve cases
voor het type-veld noise pattern.

T-867 — 5 nieuwe vitest-cases:
- unknown entity met ANDER product_id → geen resync
- claude_job_status (type) → geen resync
- worker_heartbeat (type) → geen resync
- claude_job_enqueued (type) → geen resync
- payload zonder entity en zonder type → genegeerd
- question-entity (entity-veld, geen type, niet pbi/story/task) → resync trigger

Verify: lint+typecheck clean, 651/651 tests groen.

Refs: PBI-74, ST-1323, T-865..T-867

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): cache-headers + LIST endpoints (Story 7)

- T-868: cache: 'no-store' was al ingebouwd in fetchJson helper (Story 1).
  Bevestigd door bestaande ensureProductLoaded test die de fetch-init
  controleert.
- T-869: force-dynamic toegevoegd op alle vier nieuwe LIST-endpoints.
- T-870: vier nieuwe routes voor ensure*Loaded:
  - GET /api/products/:id/backlog → ProductBacklogSnapshot
  - GET /api/pbis/:id/stories → BacklogStory[]
  - GET /api/stories/:id/tasks → BacklogTask[]
  - GET /api/tasks/:id (nieuwe handler naast bestaande PATCH) → TaskDetail
    met _detail: true marker
  Auth via authenticateApiRequest (Bearer of iron-session); access-control
  via productAccessFilter (gebruiker is owner of member van het product).
  Statussen worden via taskStatusToApi/storyStatusToApi/pbiStatusToApi
  vertaald naar lowercase API-vorm.
- T-871: SSE-route /api/realtime/backlog stuurt al ready-event direct na
  LISTEN (regel 106) — geen wijziging nodig.

Verify: lint+typecheck clean, 651/651 tests groen.

Refs: PBI-74, ST-1324, T-868..T-871

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(PBI-74): oude stores opruimen (Story 8)

Workspace-store is nu de enige bron voor product-backlog client-state. De
vier voorgangers en de dual-dispatch-infrastructuur zijn verwijderd.

- T-872: grep over codebase op useBacklogStore/usePlannerStore/
  useSelectionStore/useProductStore is leeg.
- T-873..T-876: stores/{backlog,planner,selection,product}-store.ts deleted.
- T-877: __tests__/realtime/payload-contract.test.ts en
  __tests__/api/backlog-realtime.test.ts deleted — pbi/story/task I|U|D
  payload-handling wordt al gedekt door
  __tests__/stores/product-workspace/store.test.ts (incl. parent-move,
  idempotent inserts, delete-cleanup).
- T-878: lib/realtime/dev-workspace-fingerprint.ts deleted, dual-dispatch
  uit BacklogHydrationWrapper en lib/realtime/use-backlog-realtime.ts
  weggehaald. stores/products-store.ts (lijst van producten ≠ active
  product) blijft ongewijzigd.

Bijwerkingen:
- BacklogPbi en BacklogStory types in components/backlog/story-panel.tsx en
  components/sprint/sprint-backlog.tsx krijgen sort_order zodat ze met de
  workspace-types overeenkomen.
- Server-pages /products/[id]/page.tsx (desktop+mobile) en
  /products/[id]/sprint/[sprintId]/page.tsx selecteren sort_order op story
  en mappen het door in de hydration-payload.

Verify: lint+typecheck clean, 626/626 tests groen (verlies van 25 redundante
oude-store tests; workspace-store tests dekken hetzelfde gedrag).

Refs: PBI-74, ST-1325, T-872..T-878

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(PBI-74): richtlijn workspace-store + realtime patroon

Documenteert het patroon dat in Stories 1-8 is opgeleverd, zodat een
volgende workspace-store (sprint, of een nieuwe bounded context) hetzelfde
recept volgt.

- docs/patterns/workspace-store.md (nieuw): wanneer een workspace-store, de
  vijf state-slices, selectors-regels (G1/G2), race-safe ensure*Loaded met
  activeRequestId-guard (G4), SSE-hook + applyRealtimeEvent met
  unknown-event filter, hidden-tab + reconnect resync via
  useWorkspaceResync, restore-hint flow met await-chain en URL-prioriteit,
  optimistic mutations (applyOptimisticMutation/rollback/settle), API
  endpoint-vereisten (force-dynamic, cache: no-store), test-setup met
  MemoryStorage + originalActions snapshot + mockImplementation, gotchas
  G1-G8 als comment-template, en het 8-staps migratiepad.
- docs/patterns/zustand-optimistic.md: bijgewerkt voor de nieuwe
  workspace-store API; verwijst voor het bredere patroon naar
  workspace-store.md. Voorbeelden voor pbi-order + entity-patch.
- CLAUDE.md: patterns quickref aangevuld met workspace-store-rij.

Verify: typecheck clean.

Refs: PBI-74

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(PBI-74): solo + notifications hooks volgen ook hidden-tab/resync patroon

Het uitgangspunt van PBI-74 (robuust tegen gemiste SSE-events, hidden tabs
en onbekende notify-vormen) gold universeel — niet alleen voor
product-workspace. use-solo-realtime en use-notifications-realtime hadden
nog dezelfde bug die use-backlog-realtime in Story 5 al opgelost kreeg:
sluit stream op hidden, geen resync.

Reproductie (zoals gemeld): solo-screen open in tab A, product-backlog
open in tab B; bewerk task-title in tab B → tab A's solo-SSE was gesloten
(hidden) en kreeg het NOTIFY-event nooit. Tab terug naar solo →
EventSource reconnect maar geen resync → oude title persisteert. Postgres
NOTIFY heeft geen replay, dus zonder resync zijn die events permanent
verloren.

Fix in beide hooks (zelfde patroon als Story 5 voor backlog):
- Stream blijft open op visibilitychange hidden — geen close() meer.
- Bij hidden→visible én bij window 'online': router.refresh() zodat de
  server-component opnieuw fetcht en de initial-state-prop ververst (wat
  voor solo de tasks-record reset via initTasks; voor notifications de
  questions-bel-state).
- Bij latere 'ready'-events na reconnect (use-solo-realtime): zelfde
  router.refresh() trigger zodat we niet vertrouwen op alleen het
  visibility-pad.

Verify: lint + typecheck clean, 626/626 tests groen.

Refs: PBI-74

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: fix broken links in research-repo plan

docs/plans/lees-de-readme-md-validated-book.md beschrijft een research-
repo migratiepad. De links waren geschreven vanuit het research-repo-
perspectief (paden als stores/data-store.ts, ../Scrum4Me/CLAUDE.md,
docs/plans/zustand-store-rearchitecture.md zonder relative-prefix), wat
de doc-link-checker hier laat falen.

- Header-note toegevoegd dat het document voor de research-repo is.
- Interne refs (zustand-store-rearchitecture.md, CLAUDE.md) → relatieve
  paden die in deze repo wél resolven (./zustand-..., ../../CLAUDE.md).
- Research-repo-only refs (stores/data-store.ts,
  hooks/use-event-stream.ts, components/*-select.tsx, etc.) → inline
  code-tags met "(research-repo)" suffix; de link-checker slaat ze over
  en de leesbaarheid blijft.

Verify: npm run docs:check-links → ✓ All doc links valid (118 files).

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-05-10 02:25:19 +02:00 committed by GitHub
parent 0d126695db
commit 5df04feb11
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
46 changed files with 3736 additions and 736 deletions

View file

@ -88,6 +88,7 @@ Volledige MCP-tool documentatie: [docs/runbooks/mcp-integration.md](./docs/runbo
| Prisma singleton | `docs/patterns/prisma-client.md` |
| Server Action (auth + Zod) | `docs/patterns/server-action.md` |
| Route Handler (REST) | `docs/patterns/route-handler.md` |
| Workspace-store + realtime (PBI-74) | `docs/patterns/workspace-store.md` |
| Zustand optimistic update | `docs/patterns/zustand-optimistic.md` |
| Float sort_order / drag-and-drop | `docs/patterns/sort-order.md` |
| Proxy / route protection | `docs/patterns/proxy.md` |

View file

@ -1,131 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { mockGetSession } = vi.hoisted(() => ({ mockGetSession: vi.fn() }))
vi.mock('@/lib/auth', () => ({ getSession: mockGetSession }))
vi.mock('@/lib/product-access', () => ({
getAccessibleProduct: vi.fn(),
}))
import { getAccessibleProduct } from '@/lib/product-access'
import type { NextRequest } from 'next/server'
import { GET } from '@/app/api/realtime/backlog/route'
import { useBacklogStore } from '@/stores/backlog-store'
const mockGetAccessibleProduct = getAccessibleProduct as ReturnType<typeof vi.fn>
function makeReq(productId?: string): NextRequest {
const url = productId
? `http://localhost/api/realtime/backlog?product_id=${productId}`
: 'http://localhost/api/realtime/backlog'
return {
signal: new AbortController().signal,
nextUrl: new URL(url),
} as unknown as NextRequest
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/realtime/backlog', () => {
it('401 when not authenticated', async () => {
mockGetSession.mockResolvedValue({ userId: undefined, isDemo: false })
const res = await GET(makeReq('prod-1'))
expect(res.status).toBe(401)
expect(mockGetAccessibleProduct).not.toHaveBeenCalled()
})
it('400 when product_id is missing', async () => {
mockGetSession.mockResolvedValue({ userId: 'user-1', isDemo: false })
const res = await GET(makeReq())
expect(res.status).toBe(400)
})
it('403 when user has no access to the product', async () => {
mockGetSession.mockResolvedValue({ userId: 'user-1', isDemo: false })
mockGetAccessibleProduct.mockResolvedValue(null)
const res = await GET(makeReq('prod-1'))
expect(res.status).toBe(403)
expect(mockGetAccessibleProduct).toHaveBeenCalledWith('prod-1', 'user-1')
})
it('500 when DIRECT_URL and DATABASE_URL are absent', async () => {
mockGetSession.mockResolvedValue({ userId: 'user-1', isDemo: false })
mockGetAccessibleProduct.mockResolvedValue({ id: 'prod-1' })
const before = { DIRECT_URL: process.env.DIRECT_URL, DATABASE_URL: process.env.DATABASE_URL }
delete process.env.DIRECT_URL
delete process.env.DATABASE_URL
try {
const res = await GET(makeReq('prod-1'))
expect(res.status).toBe(500)
} finally {
if (before.DIRECT_URL !== undefined) process.env.DIRECT_URL = before.DIRECT_URL
if (before.DATABASE_URL !== undefined) process.env.DATABASE_URL = before.DATABASE_URL
}
})
it('demo user is allowed (no 403) when product is accessible', async () => {
mockGetSession.mockResolvedValue({ userId: 'demo-user', isDemo: true })
mockGetAccessibleProduct.mockResolvedValue({ id: 'prod-1' })
const before = { DIRECT_URL: process.env.DIRECT_URL, DATABASE_URL: process.env.DATABASE_URL }
delete process.env.DIRECT_URL
delete process.env.DATABASE_URL
try {
const res = await GET(makeReq('prod-1'))
// Fails at 500 (no DB URL) — not 403, confirming demo user is not blocked
expect(res.status).toBe(500)
} finally {
if (before.DIRECT_URL !== undefined) process.env.DIRECT_URL = before.DIRECT_URL
if (before.DATABASE_URL !== undefined) process.env.DATABASE_URL = before.DATABASE_URL
}
})
})
// shouldEmit scope filter — white-box unit tests
describe('shouldEmit scope filter (via backlog-store reducer)', () => {
it('applyChange: pbi INSERT adds to pbis array', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: {} })
const pbi = { id: 'pbi-1', code: 'PBI-1', title: 'Test', priority: 2, created_at: new Date(), status: 'ready' as const }
useBacklogStore.getState().applyChange('pbi', 'I', pbi)
expect(useBacklogStore.getState().pbis).toHaveLength(1)
expect(useBacklogStore.getState().pbis[0].id).toBe('pbi-1')
})
it('applyChange: pbi UPDATE patches existing pbi', () => {
const pbi = { id: 'pbi-1', code: 'PBI-1', title: 'Old', priority: 2, created_at: new Date(), status: 'ready' as const }
useBacklogStore.setState({ pbis: [pbi], storiesByPbi: {}, tasksByStory: {} })
useBacklogStore.getState().applyChange('pbi', 'U', { id: 'pbi-1', title: 'New' })
expect(useBacklogStore.getState().pbis[0].title).toBe('New')
})
it('applyChange: pbi DELETE removes pbi', () => {
const pbi = { id: 'pbi-1', code: 'PBI-1', title: 'Test', priority: 2, created_at: new Date(), status: 'ready' as const }
useBacklogStore.setState({ pbis: [pbi], storiesByPbi: {}, tasksByStory: {} })
useBacklogStore.getState().applyChange('pbi', 'D', { id: 'pbi-1' })
expect(useBacklogStore.getState().pbis).toHaveLength(0)
})
it('applyChange: story INSERT adds to storiesByPbi', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: { 'pbi-1': [] }, tasksByStory: {} })
const story = { id: 'story-1', code: 'ST-1', title: 'S', description: null, acceptance_criteria: null, priority: 2, status: 'OPEN', pbi_id: 'pbi-1', sprint_id: null, created_at: new Date() }
useBacklogStore.getState().applyChange('story', 'I', story)
expect(useBacklogStore.getState().storiesByPbi['pbi-1']).toHaveLength(1)
})
it('applyChange: story DELETE removes from correct pbi bucket', () => {
const story = { id: 'story-1', code: 'ST-1', title: 'S', description: null, acceptance_criteria: null, priority: 2, status: 'OPEN', pbi_id: 'pbi-1', sprint_id: null, created_at: new Date() }
useBacklogStore.setState({ pbis: [], storiesByPbi: { 'pbi-1': [story] }, tasksByStory: {} })
useBacklogStore.getState().applyChange('story', 'D', { id: 'story-1' })
expect(useBacklogStore.getState().storiesByPbi['pbi-1']).toHaveLength(0)
})
it('applyChange: task UPDATE patches task across story buckets', () => {
const task = { id: 'task-1', title: 'Old', description: null, priority: 2, status: 'TO_DO', sort_order: 1, story_id: 'story-1', created_at: new Date() }
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: { 'story-1': [task] } })
useBacklogStore.getState().applyChange('task', 'U', { id: 'task-1', status: 'IN_PROGRESS' })
expect(useBacklogStore.getState().tasksByStory['story-1'][0].status).toBe('IN_PROGRESS')
})
})

View file

@ -1,9 +1,16 @@
// @vitest-environment jsdom
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { useSelectionStore } from '@/stores/selection-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { BacklogSplitPane } from '@/components/backlog/backlog-split-pane'
function setSelection(pbiId: string | null, storyId: string | null) {
useProductWorkspaceStore.setState((s) => {
s.context.activePbiId = pbiId
s.context.activeStoryId = storyId
})
}
const PANES = [
<div key="a">PBI pane</div>,
<div key="b">Stories pane</div>,
@ -22,7 +29,7 @@ function renderPane() {
}
beforeEach(() => {
useSelectionStore.setState({ selectedPbiId: null, selectedStoryId: null })
setSelection(null, null)
// Force mobile viewport
Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 600 })
window.dispatchEvent(new Event('resize'))
@ -37,7 +44,7 @@ describe('BacklogSplitPane auto-switch', () => {
it('auto-switches to tab 1 when PBI is selected', () => {
const { rerender } = renderPane()
useSelectionStore.setState({ selectedPbiId: 'pbi-1', selectedStoryId: null })
setSelection('pbi-1', null)
rerender(
<BacklogSplitPane
panes={PANES}
@ -52,7 +59,7 @@ describe('BacklogSplitPane auto-switch', () => {
it('auto-switches to tab 2 when story is selected', () => {
const { rerender } = renderPane()
useSelectionStore.setState({ selectedPbiId: 'pbi-1', selectedStoryId: 'story-1' })
setSelection('pbi-1', 'story-1')
rerender(
<BacklogSplitPane
panes={PANES}
@ -67,11 +74,11 @@ describe('BacklogSplitPane auto-switch', () => {
it('switches to tab 1 on cascade-reset (story cleared when new PBI selected)', () => {
// Start with story selected (tab 2)
useSelectionStore.setState({ selectedPbiId: 'pbi-1', selectedStoryId: 'story-1' })
setSelection('pbi-1', 'story-1')
const { rerender } = renderPane()
// Cascade-reset: new PBI → story clears
useSelectionStore.setState({ selectedPbiId: 'pbi-2', selectedStoryId: null })
setSelection('pbi-2', null)
rerender(
<BacklogSplitPane
panes={PANES}

View file

@ -1,8 +1,11 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { useSelectionStore } from '@/stores/selection-store'
import { useBacklogStore } from '@/stores/backlog-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type {
BacklogStory,
BacklogTask,
} from '@/stores/product-workspace/types'
// Mock next/navigation
const mockPush = vi.fn()
@ -61,19 +64,40 @@ const PBI_ID = 'pbi-1'
const ALT_PBI_ID = 'pbi-2'
const STORY_ID = 'story-1'
const STORIES = [
{ id: STORY_ID, code: 'ST-1', title: 'Eerste story', description: null, acceptance_criteria: null, priority: 2, status: 'OPEN', pbi_id: PBI_ID, sprint_id: null, created_at: new Date() },
const STORIES: BacklogStory[] = [
{ id: STORY_ID, code: 'ST-1', title: 'Eerste story', description: null, acceptance_criteria: null, priority: 2, sort_order: 1, status: 'OPEN', pbi_id: PBI_ID, sprint_id: null, created_at: new Date() },
]
const TASKS = [
const TASKS: BacklogTask[] = [
{ id: 'task-1', title: 'Eerste taak', description: null, priority: 2, status: 'TO_DO', sort_order: 1, story_id: STORY_ID, created_at: new Date() },
]
function resetStores() {
useSelectionStore.setState({ selectedPbiId: null, selectedStoryId: null })
useBacklogStore.setState({
pbis: [],
storiesByPbi: { [PBI_ID]: STORIES },
tasksByStory: { [STORY_ID]: TASKS },
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = null
s.context.activePbiId = null
s.context.activeStoryId = null
s.context.activeTaskId = null
s.entities.pbisById = {}
s.entities.storiesById = Object.fromEntries(STORIES.map((st) => [st.id, st]))
s.entities.tasksById = Object.fromEntries(TASKS.map((t) => [t.id, t]))
s.relations.pbiIds = []
s.relations.storyIdsByPbi = { [PBI_ID]: STORIES.map((st) => st.id) }
s.relations.taskIdsByStory = { [STORY_ID]: TASKS.map((t) => t.id) }
})
}
function selectPbi(pbiId: string | null) {
useProductWorkspaceStore.setState((s) => {
s.context.activePbiId = pbiId
s.context.activeStoryId = null
s.context.activeTaskId = null
})
}
function selectStory(pbiId: string | null, storyId: string | null) {
useProductWorkspaceStore.setState((s) => {
s.context.activePbiId = pbiId
s.context.activeStoryId = storyId
})
}
@ -89,42 +113,40 @@ describe('Backlog 3-pane integration', () => {
})
it('StoryPanel shows stories when PBI is selected', () => {
useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: null })
selectPbi(PBI_ID)
render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
expect(screen.getByText('Eerste story')).toBeTruthy()
})
it('clicking a story dispatches selectStory to the store', () => {
useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: null })
it('clicking a story dispatches setActiveStory to the workspace-store', () => {
selectPbi(PBI_ID)
render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
fireEvent.click(screen.getByText('Eerste story'))
expect(useSelectionStore.getState().selectedStoryId).toBe(STORY_ID)
expect(useProductWorkspaceStore.getState().context.activeStoryId).toBe(STORY_ID)
})
it('cascade-reset: selecting different PBI clears selectedStoryId', () => {
useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID })
useSelectionStore.getState().selectPbi(ALT_PBI_ID)
expect(useSelectionStore.getState().selectedStoryId).toBeNull()
it('cascade-reset: selecting different PBI clears activeStoryId', () => {
selectStory(PBI_ID, STORY_ID)
useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID)
expect(useProductWorkspaceStore.getState().context.activeStoryId).toBeNull()
})
it('TaskPanel shows tasks after story is selected', () => {
useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID })
selectStory(PBI_ID, STORY_ID)
render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
expect(screen.getByText('Eerste taak')).toBeTruthy()
})
it('TaskPanel shows empty state after cascade-reset', () => {
useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID })
selectStory(PBI_ID, STORY_ID)
render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
// Reset via selectPbi
useSelectionStore.getState().selectPbi(ALT_PBI_ID)
// Re-render reflects new store state
useProductWorkspaceStore.getState().setActivePbi(ALT_PBI_ID)
render(<TaskPanel productId={PRODUCT_ID} isDemo={false} closePath={`/products/${PRODUCT_ID}`} />)
expect(screen.getAllByText('Selecteer een story om de taken te bekijken.').length).toBeGreaterThan(0)
})
it('selected story card has isSelected highlight class applied', () => {
useSelectionStore.setState({ selectedPbiId: PBI_ID, selectedStoryId: STORY_ID })
selectStory(PBI_ID, STORY_ID)
const { container } = render(<StoryPanel productId={PRODUCT_ID} isDemo={false} />)
// bg-primary-container is applied when isSelected
const selected = container.querySelector('.bg-primary-container')

View file

@ -1,8 +1,33 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { useSelectionStore } from '@/stores/selection-store'
import { useBacklogStore } from '@/stores/backlog-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type { BacklogTask } from '@/stores/product-workspace/types'
function resetWorkspace() {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = null
s.context.activePbiId = null
s.context.activeStoryId = null
s.context.activeTaskId = null
s.entities.pbisById = {}
s.entities.storiesById = {}
s.entities.tasksById = {}
s.relations.pbiIds = []
s.relations.storyIdsByPbi = {}
s.relations.taskIdsByStory = {}
})
}
function setActiveStoryAndTasks(storyId: string | null, tasks: BacklogTask[] = []) {
useProductWorkspaceStore.setState((s) => {
s.context.activeStoryId = storyId
if (storyId) {
s.relations.taskIdsByStory[storyId] = tasks.map((t) => t.id)
for (const task of tasks) s.entities.tasksById[task.id] = task
}
})
}
// Mock next/navigation
const mockPush = vi.fn()
@ -57,8 +82,7 @@ function renderPanel(isDemo = false) {
describe('TaskPanel', () => {
beforeEach(() => {
mockPush.mockClear()
useSelectionStore.setState({ selectedStoryId: null, selectedPbiId: null })
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: {} })
resetWorkspace()
})
it('shows empty state when no story is selected', () => {
@ -67,40 +91,35 @@ describe('TaskPanel', () => {
})
it('shows empty state with action when story selected but no tasks', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: [] } })
setActiveStoryAndTasks(STORY_ID, [])
renderPanel()
expect(screen.getByText('Nog geen taken voor deze story.')).toBeTruthy()
expect(screen.getAllByText('+ Nieuwe taak').length).toBeGreaterThanOrEqual(1)
})
it('renders task cards when tasks are present', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } })
setActiveStoryAndTasks(STORY_ID, TASKS)
renderPanel()
expect(screen.getByText('Eerste taak')).toBeTruthy()
expect(screen.getByText('Tweede taak')).toBeTruthy()
})
it('renders status badges on task cards', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } })
setActiveStoryAndTasks(STORY_ID, TASKS)
renderPanel()
expect(screen.getByText('To Do')).toBeTruthy()
expect(screen.getByText('Bezig')).toBeTruthy()
})
it('task cards are rendered inside a grid container', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } })
setActiveStoryAndTasks(STORY_ID, TASKS)
const { container } = renderPanel()
const grid = container.querySelector('.grid')
expect(grid).toBeTruthy()
})
it('clicking + button calls router.push with newTask params', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: [] } })
setActiveStoryAndTasks(STORY_ID, [])
renderPanel()
const buttons = screen.getAllByText('+ Nieuwe taak')
fireEvent.click(buttons[0])
@ -108,16 +127,14 @@ describe('TaskPanel', () => {
})
it('clicking task card calls router.push with editTask param', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } })
setActiveStoryAndTasks(STORY_ID, TASKS)
renderPanel()
fireEvent.click(screen.getByText('Eerste taak'))
expect(mockPush).toHaveBeenCalledWith(`${CLOSE_PATH}?editTask=task-1`)
})
it('+ button is disabled in demo mode', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: [] } })
setActiveStoryAndTasks(STORY_ID, [])
renderPanel(true)
const btn = screen.getAllByText('+ Nieuwe taak')[0].closest('button')
expect(btn).toBeTruthy()
@ -125,8 +142,7 @@ describe('TaskPanel', () => {
})
it('cards have no drag listeners in demo mode (whole-card drag disabled)', () => {
useSelectionStore.setState({ selectedStoryId: STORY_ID, selectedPbiId: null })
useBacklogStore.setState({ tasksByStory: { [STORY_ID]: TASKS } })
setActiveStoryAndTasks(STORY_ID, TASKS)
// In demo mode, listeners ({} from useSortable mock) are not spread onto the card.
// The mock always returns empty listeners, so we just verify the cards render without error.
renderPanel(true)

View file

@ -1,161 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useBacklogStore } from '@/stores/backlog-store'
import type { BacklogPbi, BacklogStory, BacklogTask } from '@/stores/backlog-store'
const PBI: BacklogPbi = {
id: 'pbi-1',
code: 'PBI-1',
title: 'Realtime PBI',
priority: 2,
description: 'desc',
created_at: new Date('2024-01-01T00:00:00Z'),
status: 'ready',
}
const STORY: BacklogStory = {
id: 'story-1',
code: 'ST-1',
title: 'Realtime story',
description: null,
acceptance_criteria: null,
priority: 2,
status: 'OPEN',
pbi_id: 'pbi-1',
sprint_id: null,
created_at: new Date('2024-01-01T00:00:00Z'),
}
const TASK: BacklogTask = {
id: 'task-1',
title: 'Realtime task',
description: null,
priority: 2,
status: 'TO_DO',
sort_order: 1,
story_id: 'story-1',
created_at: new Date('2024-01-01T00:00:00Z'),
}
beforeEach(() => {
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: {} })
})
// ---------------------------------------------------------------------------
// PBI
// ---------------------------------------------------------------------------
describe('PBI payload contract', () => {
it('INSERT: entity appears in pbis with correct title and status', () => {
useBacklogStore.getState().applyChange('pbi', 'I', { ...PBI })
const state = useBacklogStore.getState()
expect(state.pbis).toHaveLength(1)
expect(state.pbis[0].id).toBe('pbi-1')
expect(state.pbis[0].title).toBe('Realtime PBI')
expect(state.pbis[0].status).toBe('ready')
})
it('INSERT is idempotent: duplicate SSE-event does not add a second entry', () => {
useBacklogStore.getState().applyChange('pbi', 'I', { ...PBI })
useBacklogStore.getState().applyChange('pbi', 'I', { ...PBI })
expect(useBacklogStore.getState().pbis).toHaveLength(1)
})
it('UPDATE: changed_fields partial merges into existing entity', () => {
useBacklogStore.setState({ pbis: [{ ...PBI }], storiesByPbi: {}, tasksByStory: {} })
useBacklogStore.getState().applyChange('pbi', 'U', { id: 'pbi-1', title: 'Updated PBI', status: 'in_sprint' as const })
const pbi = useBacklogStore.getState().pbis[0]
expect(pbi.title).toBe('Updated PBI')
expect(pbi.status).toBe('in_sprint')
expect(pbi.priority).toBe(2) // unchanged field retained
})
it('DELETE: entity is removed from pbis', () => {
useBacklogStore.setState({ pbis: [{ ...PBI }], storiesByPbi: {}, tasksByStory: {} })
useBacklogStore.getState().applyChange('pbi', 'D', { id: 'pbi-1' })
expect(useBacklogStore.getState().pbis).toHaveLength(0)
})
})
// ---------------------------------------------------------------------------
// Story
// ---------------------------------------------------------------------------
describe('Story payload contract', () => {
it('INSERT: entity appears in storiesByPbi[pbi_id] with correct title and status', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: { 'pbi-1': [] }, tasksByStory: {} })
useBacklogStore.getState().applyChange('story', 'I', { ...STORY })
const bucket = useBacklogStore.getState().storiesByPbi['pbi-1']
expect(bucket).toHaveLength(1)
expect(bucket[0].id).toBe('story-1')
expect(bucket[0].title).toBe('Realtime story')
expect(bucket[0].status).toBe('OPEN')
})
it('INSERT: creates bucket when pbi_id was not yet in storiesByPbi', () => {
useBacklogStore.getState().applyChange('story', 'I', { ...STORY })
expect(useBacklogStore.getState().storiesByPbi['pbi-1']).toHaveLength(1)
})
it('INSERT is idempotent: duplicate SSE-event does not add a second entry', () => {
useBacklogStore.getState().applyChange('story', 'I', { ...STORY })
useBacklogStore.getState().applyChange('story', 'I', { ...STORY })
expect(useBacklogStore.getState().storiesByPbi['pbi-1']).toHaveLength(1)
})
it('UPDATE: changed_fields partial merges into existing story', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: { 'pbi-1': [{ ...STORY }] }, tasksByStory: {} })
useBacklogStore.getState().applyChange('story', 'U', { id: 'story-1', title: 'Updated story', status: 'IN_SPRINT' })
const story = useBacklogStore.getState().storiesByPbi['pbi-1'][0]
expect(story.title).toBe('Updated story')
expect(story.status).toBe('IN_SPRINT')
expect(story.priority).toBe(2) // unchanged field retained
})
it('DELETE: entity is removed from its pbi bucket', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: { 'pbi-1': [{ ...STORY }] }, tasksByStory: {} })
useBacklogStore.getState().applyChange('story', 'D', { id: 'story-1' })
expect(useBacklogStore.getState().storiesByPbi['pbi-1']).toHaveLength(0)
})
})
// ---------------------------------------------------------------------------
// Task
// ---------------------------------------------------------------------------
describe('Task payload contract', () => {
it('INSERT: entity appears in tasksByStory[story_id] with correct title and status', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: { 'story-1': [] } })
useBacklogStore.getState().applyChange('task', 'I', { ...TASK })
const bucket = useBacklogStore.getState().tasksByStory['story-1']
expect(bucket).toHaveLength(1)
expect(bucket[0].id).toBe('task-1')
expect(bucket[0].title).toBe('Realtime task')
expect(bucket[0].status).toBe('TO_DO')
})
it('INSERT: creates bucket when story_id was not yet in tasksByStory', () => {
useBacklogStore.getState().applyChange('task', 'I', { ...TASK })
expect(useBacklogStore.getState().tasksByStory['story-1']).toHaveLength(1)
})
it('INSERT is idempotent: duplicate SSE-event does not add a second entry', () => {
useBacklogStore.getState().applyChange('task', 'I', { ...TASK })
useBacklogStore.getState().applyChange('task', 'I', { ...TASK })
expect(useBacklogStore.getState().tasksByStory['story-1']).toHaveLength(1)
})
it('UPDATE: changed_fields partial merges into existing task', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: { 'story-1': [{ ...TASK }] } })
useBacklogStore.getState().applyChange('task', 'U', { id: 'task-1', title: 'Updated task', status: 'IN_PROGRESS' })
const task = useBacklogStore.getState().tasksByStory['story-1'][0]
expect(task.title).toBe('Updated task')
expect(task.status).toBe('IN_PROGRESS')
expect(task.sort_order).toBe(1) // unchanged field retained
})
it('DELETE: entity is removed from its story bucket', () => {
useBacklogStore.setState({ pbis: [], storiesByPbi: {}, tasksByStory: { 'story-1': [{ ...TASK }] } })
useBacklogStore.getState().applyChange('task', 'D', { id: 'task-1' })
expect(useBacklogStore.getState().tasksByStory['story-1']).toHaveLength(0)
})
})

View file

@ -0,0 +1,69 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { useWorkspaceResync } from '@/lib/realtime/use-workspace-resync'
let resyncSpy: ReturnType<typeof vi.fn>
beforeEach(() => {
resyncSpy = vi.fn().mockResolvedValue(undefined)
useProductWorkspaceStore.setState((s) => {
s.resyncActiveScopes = resyncSpy as unknown as typeof s.resyncActiveScopes
})
// visibilitychange handler leest document.visibilityState — default is 'visible'
Object.defineProperty(document, 'visibilityState', {
value: 'visible',
writable: true,
configurable: true,
})
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('useWorkspaceResync', () => {
it('triggert resyncActiveScopes("visible") op visibilitychange hidden→visible', () => {
renderHook(() => useWorkspaceResync())
Object.defineProperty(document, 'visibilityState', {
value: 'visible',
writable: true,
configurable: true,
})
document.dispatchEvent(new Event('visibilitychange'))
expect(resyncSpy).toHaveBeenCalledWith('visible')
})
it('triggert resyncActiveScopes("reconnect") op online-event', () => {
renderHook(() => useWorkspaceResync())
window.dispatchEvent(new Event('online'))
expect(resyncSpy).toHaveBeenCalledWith('reconnect')
})
it('triggert geen resync bij visibilitychange naar hidden', () => {
renderHook(() => useWorkspaceResync())
Object.defineProperty(document, 'visibilityState', {
value: 'hidden',
writable: true,
configurable: true,
})
document.dispatchEvent(new Event('visibilitychange'))
expect(resyncSpy).not.toHaveBeenCalled()
})
it('cleanup verwijdert listeners bij unmount', () => {
const { unmount } = renderHook(() => useWorkspaceResync())
unmount()
window.dispatchEvent(new Event('online'))
document.dispatchEvent(new Event('visibilitychange'))
expect(resyncSpy).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,117 @@
import { describe, expect, it } from 'vitest'
import {
clearHints,
readHints,
writePbiHint,
writeProductHint,
writeStoryHint,
writeTaskHint,
} from '@/stores/product-workspace/restore'
describe('readHints', () => {
it('retourneert lege defaults wanneer localStorage leeg is', () => {
const hints = readHints()
expect(hints.lastActiveProductId).toBeNull()
expect(hints.perProduct).toEqual({})
})
it('herstelt hints uit localStorage', () => {
localStorage.setItem(
'product-workspace-hints',
JSON.stringify({
lastActiveProductId: 'p1',
perProduct: { p1: { lastActivePbiId: 'pbi-1' } },
}),
)
const hints = readHints()
expect(hints.lastActiveProductId).toBe('p1')
expect(hints.perProduct.p1.lastActivePbiId).toBe('pbi-1')
})
it('valt terug op defaults bij ongeldige JSON', () => {
localStorage.setItem('product-workspace-hints', '{not-json')
const hints = readHints()
expect(hints.lastActiveProductId).toBeNull()
expect(hints.perProduct).toEqual({})
})
it('valt terug op defaults bij verkeerde shape', () => {
localStorage.setItem('product-workspace-hints', '"just a string"')
const hints = readHints()
expect(hints.perProduct).toEqual({})
})
})
describe('writeProductHint', () => {
it('schrijft lastActiveProductId', () => {
writeProductHint('p1')
expect(readHints().lastActiveProductId).toBe('p1')
})
it('overschrijft bestaande waarde', () => {
writeProductHint('p1')
writeProductHint('p2')
expect(readHints().lastActiveProductId).toBe('p2')
})
it('accepteert null om hint te wissen', () => {
writeProductHint('p1')
writeProductHint(null)
expect(readHints().lastActiveProductId).toBeNull()
})
})
describe('writePbiHint', () => {
it('schrijft lastActivePbiId per productId', () => {
writePbiHint('prod-1', 'pbi-a')
writePbiHint('prod-2', 'pbi-b')
const hints = readHints()
expect(hints.perProduct['prod-1'].lastActivePbiId).toBe('pbi-a')
expect(hints.perProduct['prod-2'].lastActivePbiId).toBe('pbi-b')
})
it('null wist child story- en task-hints', () => {
writePbiHint('prod-1', 'pbi-1')
writeStoryHint('prod-1', 's-1')
writeTaskHint('prod-1', 't-1')
writePbiHint('prod-1', null)
const hints = readHints()
expect(hints.perProduct['prod-1'].lastActivePbiId).toBeNull()
expect(hints.perProduct['prod-1'].lastActiveStoryId).toBeNull()
expect(hints.perProduct['prod-1'].lastActiveTaskId).toBeNull()
})
})
describe('writeStoryHint', () => {
it('schrijft lastActiveStoryId per productId', () => {
writeStoryHint('prod-1', 's-1')
expect(readHints().perProduct['prod-1'].lastActiveStoryId).toBe('s-1')
})
it('null wist child task-hint', () => {
writeStoryHint('prod-1', 's-1')
writeTaskHint('prod-1', 't-1')
writeStoryHint('prod-1', null)
expect(readHints().perProduct['prod-1'].lastActiveStoryId).toBeNull()
expect(readHints().perProduct['prod-1'].lastActiveTaskId).toBeNull()
})
})
describe('writeTaskHint', () => {
it('schrijft lastActiveTaskId per productId', () => {
writeTaskHint('prod-1', 't-1')
expect(readHints().perProduct['prod-1'].lastActiveTaskId).toBe('t-1')
})
})
describe('clearHints', () => {
it('verwijdert alle hints', () => {
writeProductHint('p1')
writePbiHint('p1', 'pbi-1')
clearHints()
const hints = readHints()
expect(hints.lastActiveProductId).toBeNull()
expect(hints.perProduct).toEqual({})
})
})

View file

@ -0,0 +1,832 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type {
BacklogPbi,
BacklogStory,
BacklogTask,
ProductBacklogSnapshot,
TaskDetail,
} from '@/stores/product-workspace/types'
// G5: snapshot original actions on module-load; restore in beforeEach.
// vi.fn-spies on actions could leak across tests otherwise.
const originalActions = (() => {
const s = useProductWorkspaceStore.getState()
return {
hydrateSnapshot: s.hydrateSnapshot,
setActiveProduct: s.setActiveProduct,
setActivePbi: s.setActivePbi,
setActiveStory: s.setActiveStory,
setActiveTask: s.setActiveTask,
ensureProductLoaded: s.ensureProductLoaded,
ensurePbiLoaded: s.ensurePbiLoaded,
ensureStoryLoaded: s.ensureStoryLoaded,
ensureTaskLoaded: s.ensureTaskLoaded,
applyRealtimeEvent: s.applyRealtimeEvent,
resyncActiveScopes: s.resyncActiveScopes,
resyncLoadedScopes: s.resyncLoadedScopes,
applyOptimisticMutation: s.applyOptimisticMutation,
rollbackMutation: s.rollbackMutation,
settleMutation: s.settleMutation,
setRealtimeStatus: s.setRealtimeStatus,
}
})()
function resetStore() {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = null
s.context.activePbiId = null
s.context.activeStoryId = null
s.context.activeTaskId = null
s.entities.pbisById = {}
s.entities.storiesById = {}
s.entities.tasksById = {}
s.relations.pbiIds = []
s.relations.storyIdsByPbi = {}
s.relations.taskIdsByStory = {}
s.loading.loadedProductId = null
s.loading.loadingProductId = null
s.loading.loadedPbiIds = {}
s.loading.loadedStoryIds = {}
s.loading.loadedTaskIds = {}
s.loading.activeRequestId = null
s.sync.realtimeStatus = 'connecting'
s.sync.lastEventAt = null
s.sync.lastResyncAt = null
s.sync.resyncReason = null
s.pendingMutations = {}
Object.assign(s, originalActions)
})
}
beforeEach(() => {
resetStore()
})
afterEach(() => {
vi.restoreAllMocks()
})
function makePbi(overrides: Partial<BacklogPbi> & { id: string }): BacklogPbi {
return {
id: overrides.id,
code: overrides.code ?? overrides.id,
title: overrides.title ?? `PBI ${overrides.id}`,
priority: overrides.priority ?? 2,
sort_order: overrides.sort_order ?? 1,
description: overrides.description ?? null,
created_at: overrides.created_at ?? new Date('2026-01-01'),
status: overrides.status ?? 'ready',
}
}
function makeStory(overrides: Partial<BacklogStory> & { id: string; pbi_id: string }): BacklogStory {
return {
id: overrides.id,
code: overrides.code ?? overrides.id,
title: overrides.title ?? `Story ${overrides.id}`,
description: overrides.description ?? null,
acceptance_criteria: overrides.acceptance_criteria ?? null,
priority: overrides.priority ?? 2,
sort_order: overrides.sort_order ?? 1,
status: overrides.status ?? 'open',
pbi_id: overrides.pbi_id,
sprint_id: overrides.sprint_id ?? null,
created_at: overrides.created_at ?? new Date('2026-01-01'),
}
}
function makeTask(overrides: Partial<BacklogTask> & { id: string; story_id: string }): BacklogTask {
return {
id: overrides.id,
title: overrides.title ?? `Task ${overrides.id}`,
description: overrides.description ?? null,
priority: overrides.priority ?? 2,
sort_order: overrides.sort_order ?? 1,
status: overrides.status ?? 'todo',
story_id: overrides.story_id,
created_at: overrides.created_at ?? new Date('2026-01-01'),
}
}
function snapshotWith(
pbis: BacklogPbi[],
storiesByPbi: Record<string, BacklogStory[]> = {},
tasksByStory: Record<string, BacklogTask[]> = {},
product?: { id: string; name: string },
): ProductBacklogSnapshot {
return { product, pbis, storiesByPbi, tasksByStory }
}
// G7: mock fetch — never let it fall through to real network
// G8: mockImplementation per call so each fetch gets a fresh Response
function mockFetchSequence(
responses: Array<unknown | ((url: string, init?: RequestInit) => unknown)>,
) {
let i = 0
return vi.spyOn(globalThis, 'fetch').mockImplementation((async (url: string, init?: RequestInit) => {
const r = responses[Math.min(i, responses.length - 1)]
i += 1
const body = typeof r === 'function' ? (r as (u: string, i?: RequestInit) => unknown)(url, init) : r
return new Response(JSON.stringify(body ?? null), { status: 200 })
}) as unknown as typeof fetch)
}
// ─────────────────────────────────────────────────────────────────────────
// hydrateSnapshot
// ─────────────────────────────────────────────────────────────────────────
describe('hydrateSnapshot', () => {
it('vult entities en relations met gesorteerde id-lijsten', () => {
const pbiA = makePbi({ id: 'pbi-a', priority: 2, sort_order: 2 })
const pbiB = makePbi({ id: 'pbi-b', priority: 1, sort_order: 5 })
const pbiC = makePbi({ id: 'pbi-c', priority: 2, sort_order: 1 })
const storyB1 = makeStory({ id: 'st-1', pbi_id: 'pbi-b', sort_order: 2 })
const storyB2 = makeStory({ id: 'st-2', pbi_id: 'pbi-b', sort_order: 1 })
const taskA = makeTask({ id: 'tk-2', story_id: 'st-1', sort_order: 2 })
const taskB = makeTask({ id: 'tk-1', story_id: 'st-1', sort_order: 1 })
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith(
[pbiA, pbiB, pbiC],
{ 'pbi-b': [storyB1, storyB2] },
{ 'st-1': [taskA, taskB] },
{ id: 'prod-1', name: 'Product 1' },
),
)
const s = useProductWorkspaceStore.getState()
expect(s.entities.pbisById['pbi-a']).toBe(pbiA)
expect(s.entities.pbisById['pbi-b']).toBe(pbiB)
expect(s.entities.pbisById['pbi-c']).toBe(pbiC)
// pbi-b heeft priority 1 (komt eerst), dan pbi-c (sort_order 1) en pbi-a (sort_order 2)
expect(s.relations.pbiIds).toEqual(['pbi-b', 'pbi-c', 'pbi-a'])
expect(s.relations.storyIdsByPbi['pbi-b']).toEqual(['st-2', 'st-1'])
expect(s.relations.taskIdsByStory['st-1']).toEqual(['tk-1', 'tk-2'])
expect(s.context.activeProduct).toEqual({ id: 'prod-1', name: 'Product 1' })
expect(s.loading.loadedProductId).toBe('prod-1')
})
it('reset bestaande entities en relations bij her-hydratie', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'old-pbi' })]),
)
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['old-pbi'])
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'new-pbi' })]),
)
const s = useProductWorkspaceStore.getState()
expect(s.entities.pbisById['old-pbi']).toBeUndefined()
expect(s.entities.pbisById['new-pbi']).toBeDefined()
expect(s.relations.pbiIds).toEqual(['new-pbi'])
})
})
// ─────────────────────────────────────────────────────────────────────────
// Selection cascade
// ─────────────────────────────────────────────────────────────────────────
describe('selection cascade', () => {
it('setActivePbi reset story+task; setActiveStory reset task', () => {
useProductWorkspaceStore.setState((s) => {
s.context.activePbiId = 'pbi-old'
s.context.activeStoryId = 'st-old'
s.context.activeTaskId = 'tk-old'
})
useProductWorkspaceStore.getState().setActivePbi('pbi-new')
let s = useProductWorkspaceStore.getState()
expect(s.context.activePbiId).toBe('pbi-new')
expect(s.context.activeStoryId).toBeNull()
expect(s.context.activeTaskId).toBeNull()
useProductWorkspaceStore.setState((draft) => {
draft.context.activeStoryId = 'st-old'
draft.context.activeTaskId = 'tk-old'
})
useProductWorkspaceStore.getState().setActiveStory('st-new')
s = useProductWorkspaceStore.getState()
expect(s.context.activeStoryId).toBe('st-new')
expect(s.context.activeTaskId).toBeNull()
})
it('setActiveProduct(null) ruimt entities en relations op', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith(
[makePbi({ id: 'p-1' })],
{ 'p-1': [makeStory({ id: 's-1', pbi_id: 'p-1' })] },
{ 's-1': [makeTask({ id: 't-1', story_id: 's-1' })] },
{ id: 'prod-1', name: 'Product 1' },
),
)
useProductWorkspaceStore.getState().setActiveProduct(null)
const s = useProductWorkspaceStore.getState()
expect(s.context.activeProduct).toBeNull()
expect(s.context.activePbiId).toBeNull()
expect(s.context.activeStoryId).toBeNull()
expect(s.context.activeTaskId).toBeNull()
expect(s.entities.pbisById).toEqual({})
expect(s.entities.storiesById).toEqual({})
expect(s.entities.tasksById).toEqual({})
expect(s.relations.pbiIds).toEqual([])
expect(s.relations.storyIdsByPbi).toEqual({})
expect(s.relations.taskIdsByStory).toEqual({})
expect(s.loading.loadedProductId).toBeNull()
})
})
// ─────────────────────────────────────────────────────────────────────────
// applyRealtimeEvent
// ─────────────────────────────────────────────────────────────────────────
describe('applyRealtimeEvent — pbi', () => {
beforeEach(() => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
})
})
it('I — voegt PBI toe en sorteert', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'a', priority: 2, sort_order: 5 })]),
)
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'I',
id: 'b',
product_id: 'prod-1',
code: 'B',
title: 'New PBI',
priority: 1,
sort_order: 1,
created_at: new Date('2026-02-01').toISOString(),
status: 'ready',
})
const s = useProductWorkspaceStore.getState()
expect(s.entities.pbisById['b']).toBeDefined()
expect(s.relations.pbiIds).toEqual(['b', 'a'])
})
it('I — idempotent voor bestaande id', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'a' })]),
)
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'I',
id: 'a',
product_id: 'prod-1',
title: 'mutated',
})
const s = useProductWorkspaceStore.getState()
expect(s.entities.pbisById['a'].title).toBe('PBI a') // niet overschreven
expect(s.relations.pbiIds).toEqual(['a'])
})
it('U — patch + her-sorteert', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([
makePbi({ id: 'a', priority: 2, sort_order: 1 }),
makePbi({ id: 'b', priority: 2, sort_order: 2 }),
]),
)
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'U',
id: 'b',
product_id: 'prod-1',
priority: 1,
})
const s = useProductWorkspaceStore.getState()
expect(s.relations.pbiIds).toEqual(['b', 'a'])
})
it('D — verwijdert PBI inclusief child stories en tasks', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith(
[makePbi({ id: 'p1' })],
{ p1: [makeStory({ id: 's1', pbi_id: 'p1' })] },
{ s1: [makeTask({ id: 't1', story_id: 's1' })] },
),
)
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'D',
id: 'p1',
product_id: 'prod-1',
})
const s = useProductWorkspaceStore.getState()
expect(s.entities.pbisById['p1']).toBeUndefined()
expect(s.entities.storiesById['s1']).toBeUndefined()
expect(s.entities.tasksById['t1']).toBeUndefined()
expect(s.relations.pbiIds).toEqual([])
expect(s.relations.storyIdsByPbi['p1']).toBeUndefined()
expect(s.relations.taskIdsByStory['s1']).toBeUndefined()
})
it('D — clear actieve PBI selectie als die onder de verwijderde PBI viel', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'p1' })]),
)
useProductWorkspaceStore.setState((s) => {
s.context.activePbiId = 'p1'
s.context.activeStoryId = 's-x'
s.context.activeTaskId = 't-x'
})
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'D',
id: 'p1',
product_id: 'prod-1',
})
const s = useProductWorkspaceStore.getState()
expect(s.context.activePbiId).toBeNull()
expect(s.context.activeStoryId).toBeNull()
expect(s.context.activeTaskId).toBeNull()
})
})
describe('applyRealtimeEvent — story parent-move', () => {
beforeEach(() => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
})
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith(
[makePbi({ id: 'p1' }), makePbi({ id: 'p2' })],
{
p1: [makeStory({ id: 's1', pbi_id: 'p1' })],
p2: [],
},
),
)
})
it('U met andere pbi_id verplaatst story naar nieuwe parent-lijst', () => {
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'story',
op: 'U',
id: 's1',
product_id: 'prod-1',
pbi_id: 'p2',
})
const s = useProductWorkspaceStore.getState()
expect(s.relations.storyIdsByPbi['p1']).toEqual([])
expect(s.relations.storyIdsByPbi['p2']).toEqual(['s1'])
expect(s.entities.storiesById['s1'].pbi_id).toBe('p2')
})
})
describe('applyRealtimeEvent — task parent-move', () => {
beforeEach(() => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
})
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith(
[makePbi({ id: 'p1' })],
{ p1: [makeStory({ id: 's1', pbi_id: 'p1' }), makeStory({ id: 's2', pbi_id: 'p1' })] },
{
s1: [makeTask({ id: 't1', story_id: 's1' })],
s2: [],
},
),
)
})
it('U met andere story_id verplaatst task naar nieuwe parent', () => {
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'task',
op: 'U',
id: 't1',
product_id: 'prod-1',
story_id: 's2',
})
const s = useProductWorkspaceStore.getState()
expect(s.relations.taskIdsByStory['s1']).toEqual([])
expect(s.relations.taskIdsByStory['s2']).toEqual(['t1'])
expect(s.entities.tasksById['t1'].story_id).toBe('s2')
})
})
describe('applyRealtimeEvent — andere product genegeerd', () => {
it('event met ander product_id raakt de store niet', () => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
})
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'a' })]),
)
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'I',
id: 'b',
product_id: 'prod-2',
title: 'Other product',
priority: 1,
sort_order: 1,
})
const s = useProductWorkspaceStore.getState()
expect(s.entities.pbisById['b']).toBeUndefined()
expect(s.relations.pbiIds).toEqual(['a'])
})
})
describe('applyRealtimeEvent — unknown entity → resync trigger', () => {
function withSpy(): ReturnType<typeof vi.fn> {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
})
const spy = vi.fn().mockResolvedValue(undefined)
useProductWorkspaceStore.setState((s) => {
s.resyncActiveScopes = spy as unknown as typeof s.resyncActiveScopes
})
return spy
}
it('unknown entity (b.v. comment) met matching product triggert resync', () => {
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'comment',
op: 'I',
id: 'cm-1',
product_id: 'prod-1',
} as unknown as Record<string, unknown>)
expect(spy).toHaveBeenCalledWith('unknown-event')
})
it('unknown entity met ander product_id triggert geen resync', () => {
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'comment',
op: 'I',
id: 'cm-1',
product_id: 'prod-2',
} as unknown as Record<string, unknown>)
expect(spy).not.toHaveBeenCalled()
})
it('claude_job_status (type-veld) triggert geen resync', () => {
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
type: 'claude_job_status',
job_id: 'job-1',
product_id: 'prod-1',
status: 'queued',
} as unknown as Record<string, unknown>)
expect(spy).not.toHaveBeenCalled()
})
it('worker_heartbeat (type-veld) triggert geen resync', () => {
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
type: 'worker_heartbeat',
worker_id: 'w-1',
product_id: 'prod-1',
} as unknown as Record<string, unknown>)
expect(spy).not.toHaveBeenCalled()
})
it('claude_job_enqueued (type-veld) triggert geen resync', () => {
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
type: 'claude_job_enqueued',
job_id: 'job-2',
product_id: 'prod-1',
kind: 'PER_TASK',
} as unknown as Record<string, unknown>)
expect(spy).not.toHaveBeenCalled()
})
it('payload zonder entity en zonder type wordt genegeerd', () => {
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
product_id: 'prod-1',
something: 'else',
} as unknown as Record<string, unknown>)
expect(spy).not.toHaveBeenCalled()
})
it('question-event met entity-veld maar zonder pbi/story/task triggert resync', () => {
// question is geen pbi/story/task entity dus telt als unknown wanneer
// hij geen 'type' draagt — dat zou een nieuwe entiteit kunnen zijn die
// we nog niet kennen.
const spy = withSpy()
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'question',
op: 'I',
id: 'q-1',
product_id: 'prod-1',
} as unknown as Record<string, unknown>)
expect(spy).toHaveBeenCalledWith('unknown-event')
})
})
// ─────────────────────────────────────────────────────────────────────────
// ensure*Loaded fetches + race-safe guard + sortering
// ─────────────────────────────────────────────────────────────────────────
describe('ensureProductLoaded', () => {
it('fetcht backlog snapshot en hydreert met sortering', async () => {
const snapshot: ProductBacklogSnapshot = {
product: { id: 'prod-1', name: 'Product 1' },
pbis: [
makePbi({ id: 'a', priority: 2, sort_order: 5 }),
makePbi({ id: 'b', priority: 1, sort_order: 9 }),
],
storiesByPbi: {},
tasksByStory: {},
}
const fetchSpy = mockFetchSequence([snapshot])
await useProductWorkspaceStore.getState().ensureProductLoaded('prod-1')
expect(fetchSpy).toHaveBeenCalledWith(
'/api/products/prod-1/backlog',
expect.objectContaining({ cache: 'no-store' }),
)
const s = useProductWorkspaceStore.getState()
expect(s.relations.pbiIds).toEqual(['b', 'a'])
expect(s.loading.loadedProductId).toBe('prod-1')
expect(s.loading.loadedPbiIds['a']).toBe(true)
expect(s.loading.loadedPbiIds['b']).toBe(true)
})
})
describe('race-safe ensure*Loaded — activeRequestId guard', () => {
it('oudere in-flight ensurePbiLoaded mag nieuwere selectie niet overschrijven', async () => {
let resolveOld: ((stories: BacklogStory[]) => void) | null = null
vi.spyOn(globalThis, 'fetch').mockImplementation((async (url: string) => {
if (url === '/api/pbis/pbi-old/stories') {
const stories = await new Promise<BacklogStory[]>((resolve) => {
resolveOld = resolve
})
return new Response(JSON.stringify(stories), { status: 200 })
}
if (url === '/api/pbis/pbi-new/stories') {
return new Response(
JSON.stringify([makeStory({ id: 'new-st', pbi_id: 'pbi-new' })]),
{ status: 200 },
)
}
return new Response('null', { status: 200 })
}) as unknown as typeof fetch)
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'Product 1' }
s.context.activePbiId = 'pbi-old'
s.loading.activeRequestId = 'req-old'
})
const oldPromise = useProductWorkspaceStore
.getState()
.ensurePbiLoaded('pbi-old', 'req-old')
// gebruiker selecteert ondertussen pbi-new
useProductWorkspaceStore.setState((s) => {
s.context.activePbiId = 'pbi-new'
s.loading.activeRequestId = 'req-new'
})
await useProductWorkspaceStore.getState().ensurePbiLoaded('pbi-new', 'req-new')
expect(useProductWorkspaceStore.getState().entities.storiesById['new-st']).toBeDefined()
// resolve de oude fetch — guard moet de stale data weigeren
resolveOld!([makeStory({ id: 'old-st', pbi_id: 'pbi-old' })])
await oldPromise
const s = useProductWorkspaceStore.getState()
expect(s.context.activePbiId).toBe('pbi-new')
expect(s.entities.storiesById['old-st']).toBeUndefined()
expect(s.entities.storiesById['new-st']).toBeDefined()
})
})
describe('ensureTaskLoaded — zet detail-flag', () => {
it('verrijkt task naar TaskDetail met _detail: true', async () => {
mockFetchSequence([
{
id: 't-1',
title: 'Task 1',
description: 'desc',
priority: 1,
sort_order: 1,
status: 'todo',
story_id: 's-1',
created_at: new Date('2026-02-01').toISOString(),
implementation_plan: 'detailed plan here',
},
])
await useProductWorkspaceStore.getState().ensureTaskLoaded('t-1')
const task = useProductWorkspaceStore.getState().entities.tasksById['t-1'] as TaskDetail
expect(task._detail).toBe(true)
expect(task.implementation_plan).toBe('detailed plan here')
expect(useProductWorkspaceStore.getState().loading.loadedTaskIds['t-1']).toBe(true)
})
})
// ─────────────────────────────────────────────────────────────────────────
// resyncActiveScopes
// ─────────────────────────────────────────────────────────────────────────
describe('resyncActiveScopes', () => {
it('triggert ensure-keten voor alle actieve scopes en zet sync velden', async () => {
const fetchSpy = mockFetchSequence([
// ensureProductLoaded
{ product: { id: 'prod-1', name: 'P' }, pbis: [], storiesByPbi: {}, tasksByStory: {} },
// ensurePbiLoaded
[],
// ensureStoryLoaded
[],
// ensureTaskLoaded
{
id: 't-1',
title: 'T',
description: null,
priority: 1,
sort_order: 1,
status: 'todo',
story_id: 's-1',
created_at: '2026-02-01',
},
])
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'P' }
s.context.activePbiId = 'pbi-1'
s.context.activeStoryId = 's-1'
s.context.activeTaskId = 't-1'
})
await useProductWorkspaceStore.getState().resyncActiveScopes('manual')
const calls = fetchSpy.mock.calls.map(([url]) => url)
expect(calls).toContain('/api/products/prod-1/backlog')
expect(calls).toContain('/api/pbis/pbi-1/stories')
expect(calls).toContain('/api/stories/s-1/tasks')
expect(calls).toContain('/api/tasks/t-1')
const s = useProductWorkspaceStore.getState()
expect(s.sync.lastResyncAt).toBeTypeOf('number')
expect(s.sync.resyncReason).toBe('manual')
})
})
// ─────────────────────────────────────────────────────────────────────────
// Optimistic mutations
// ─────────────────────────────────────────────────────────────────────────
// ─────────────────────────────────────────────────────────────────────────
// Restore-hint integratie (Story 4)
// ─────────────────────────────────────────────────────────────────────────
describe('restore-hint flow — setters persisteren hints', () => {
it('setActiveProduct schrijft lastActiveProductId', () => {
useProductWorkspaceStore.getState().setActiveProduct({ id: 'prod-1', name: 'P1' })
const raw = localStorage.getItem('product-workspace-hints')
expect(raw).not.toBeNull()
const hints = JSON.parse(raw!)
expect(hints.lastActiveProductId).toBe('prod-1')
})
it('setActivePbi schrijft lastActivePbiId per product', () => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'P1' }
})
useProductWorkspaceStore.getState().setActivePbi('pbi-a')
const hints = JSON.parse(localStorage.getItem('product-workspace-hints')!)
expect(hints.perProduct['prod-1'].lastActivePbiId).toBe('pbi-a')
})
it('setActiveStory schrijft lastActiveStoryId per product', () => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'P1' }
})
useProductWorkspaceStore.getState().setActiveStory('story-a')
const hints = JSON.parse(localStorage.getItem('product-workspace-hints')!)
expect(hints.perProduct['prod-1'].lastActiveStoryId).toBe('story-a')
})
it('setActiveTask schrijft lastActiveTaskId per product', () => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'P1' }
})
useProductWorkspaceStore.getState().setActiveTask('task-a')
const hints = JSON.parse(localStorage.getItem('product-workspace-hints')!)
expect(hints.perProduct['prod-1'].lastActiveTaskId).toBe('task-a')
})
})
describe('restore-hint flow — chain triggert na ensure*Loaded', () => {
it('hint die NIET in entities zit wordt genegeerd', async () => {
// Schrijf een hint voor een PBI die niet bestaat
localStorage.setItem(
'product-workspace-hints',
JSON.stringify({
lastActiveProductId: 'prod-1',
perProduct: { 'prod-1': { lastActivePbiId: 'ghost-pbi' } },
}),
)
// Mock ensureProductLoaded zodat hij een lege snapshot terugstuurt — geen
// ghost-pbi in entities.
mockFetchSequence([
{ product: { id: 'prod-1', name: 'P1' }, pbis: [], storiesByPbi: {}, tasksByStory: {} },
])
useProductWorkspaceStore.getState().setActiveProduct({ id: 'prod-1', name: 'P1' })
// Wacht tot async restore-flow afgewikkeld is.
await new Promise((r) => setTimeout(r, 20))
expect(useProductWorkspaceStore.getState().context.activePbiId).toBeNull()
})
it('hint die wel in entities zit wordt toegepast', async () => {
const validPbi = makePbi({ id: 'pbi-known' })
localStorage.setItem(
'product-workspace-hints',
JSON.stringify({
lastActiveProductId: 'prod-1',
perProduct: { 'prod-1': { lastActivePbiId: 'pbi-known' } },
}),
)
mockFetchSequence([
// ensureProductLoaded levert pbi-known
{
product: { id: 'prod-1', name: 'P1' },
pbis: [validPbi],
storiesByPbi: {},
tasksByStory: {},
},
// ensurePbiLoaded triggered door setActivePbi(hint) — geen stories
[],
])
useProductWorkspaceStore.getState().setActiveProduct({ id: 'prod-1', name: 'P1' })
await new Promise((r) => setTimeout(r, 30))
expect(useProductWorkspaceStore.getState().context.activePbiId).toBe('pbi-known')
})
})
describe('optimistic mutations', () => {
it('rollback herstelt vorige pbi-order', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([
makePbi({ id: 'a', priority: 2, sort_order: 1 }),
makePbi({ id: 'b', priority: 2, sort_order: 2 }),
]),
)
const prevOrder = [...useProductWorkspaceStore.getState().relations.pbiIds]
const id = useProductWorkspaceStore.getState().applyOptimisticMutation({
kind: 'pbi-order',
prevPbiIds: prevOrder,
})
// simuleer de optimistic order-wijziging buiten de mutation
useProductWorkspaceStore.setState((s) => {
s.relations.pbiIds = ['b', 'a']
})
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['b', 'a'])
useProductWorkspaceStore.getState().rollbackMutation(id)
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(prevOrder)
expect(useProductWorkspaceStore.getState().pendingMutations[id]).toBeUndefined()
})
it('settle ruimt pending op zonder state te wijzigen', () => {
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'a' })]),
)
const id = useProductWorkspaceStore.getState().applyOptimisticMutation({
kind: 'pbi-order',
prevPbiIds: ['a'],
})
expect(useProductWorkspaceStore.getState().pendingMutations[id]).toBeDefined()
useProductWorkspaceStore.getState().settleMutation(id)
expect(useProductWorkspaceStore.getState().pendingMutations[id]).toBeUndefined()
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['a'])
})
it('SSE-echo van een al-bestaande PBI is idempotent', () => {
useProductWorkspaceStore.setState((s) => {
s.context.activeProduct = { id: 'prod-1', name: 'P' }
})
useProductWorkspaceStore.getState().hydrateSnapshot(
snapshotWith([makePbi({ id: 'a', title: 'Origineel' })]),
)
useProductWorkspaceStore.getState().applyRealtimeEvent({
entity: 'pbi',
op: 'I',
id: 'a',
product_id: 'prod-1',
title: 'echo',
})
expect(useProductWorkspaceStore.getState().entities.pbisById['a'].title).toBe('Origineel')
expect(useProductWorkspaceStore.getState().relations.pbiIds).toEqual(['a'])
})
})

View file

@ -11,6 +11,7 @@ import { StoryPanel } from '@/components/backlog/story-panel'
import type { Story } from '@/components/backlog/story-panel'
import { TaskPanel } from '@/components/backlog/task-panel'
import { BacklogHydrationWrapper } from '@/components/backlog/backlog-hydration-wrapper'
import { UrlTaskSync } from '@/components/backlog/url-task-sync'
import { TaskDialog } from '@/app/_components/tasks/task-dialog'
import { EditTaskLoader } from '@/app/_components/tasks/edit-task-loader'
import { TaskDialogSkeleton } from '@/app/_components/tasks/task-dialog-skeleton'
@ -59,6 +60,7 @@ export default async function ProductBacklogPage({ params, searchParams }: Props
description: true,
acceptance_criteria: true,
priority: true,
sort_order: true,
status: true,
pbi_id: true,
sprint_id: true,
@ -81,7 +83,7 @@ export default async function ProductBacklogPage({ params, searchParams }: Props
}),
])
// Group stories by PBI id
// Group stories by PBI id (status uit DB blijft UPPER_SNAKE in dit hydratie-pad)
const storiesByPbi: Record<string, Story[]> = {}
for (const story of stories) {
if (!storiesByPbi[story.pbi_id]) storiesByPbi[story.pbi_id] = []
@ -150,11 +152,12 @@ export default async function ProductBacklogPage({ params, searchParams }: Props
<BacklogHydrationWrapper
productId={id}
initialData={{
pbis: pbis.map((p) => ({ id: p.id, code: p.code, title: p.title, priority: p.priority, description: p.description, created_at: p.created_at, status: pbiStatusToApi(p.status) })),
pbis: pbis.map((p) => ({ id: p.id, code: p.code, title: p.title, priority: p.priority, sort_order: p.sort_order, description: p.description, created_at: p.created_at, status: pbiStatusToApi(p.status) })),
storiesByPbi,
tasksByStory,
}}
>
<UrlTaskSync />
<BacklogSplitPane
cookieKey={`backlog-${id}`}
defaultSplit={[20, 45, 35]}

View file

@ -97,6 +97,7 @@ export default async function SprintBoardPage({ params, searchParams }: Props) {
sprint_id: s.sprint_id,
created_at: s.created_at,
priority: s.priority,
sort_order: s.sort_order,
status: s.status,
taskCount: s.tasks.length,
doneCount: s.tasks.filter(t => t.status === 'DONE').length,
@ -148,6 +149,7 @@ export default async function SprintBoardPage({ params, searchParams }: Props) {
sprint_id: s.sprint_id,
created_at: s.created_at,
priority: s.priority,
sort_order: s.sort_order,
status: s.status,
taskCount: 0,
doneCount: 0,

View file

@ -15,6 +15,7 @@ import { StoryPanel } from '@/components/backlog/story-panel'
import type { Story } from '@/components/backlog/story-panel'
import { TaskPanel } from '@/components/backlog/task-panel'
import { BacklogHydrationWrapper } from '@/components/backlog/backlog-hydration-wrapper'
import { UrlTaskSync } from '@/components/backlog/url-task-sync'
import { TaskDialog } from '@/app/_components/tasks/task-dialog'
import { EditTaskLoader } from '@/app/_components/tasks/edit-task-loader'
import { TaskDialogSkeleton } from '@/app/_components/tasks/task-dialog-skeleton'
@ -49,6 +50,7 @@ export default async function MobileProductBacklogPage({ params, searchParams }:
description: true,
acceptance_criteria: true,
priority: true,
sort_order: true,
status: true,
pbi_id: true,
sprint_id: true,
@ -90,11 +92,12 @@ export default async function MobileProductBacklogPage({ params, searchParams }:
<BacklogHydrationWrapper
productId={id}
initialData={{
pbis: pbis.map((p) => ({ id: p.id, code: p.code, title: p.title, priority: p.priority, description: p.description, created_at: p.created_at, status: pbiStatusToApi(p.status) })),
pbis: pbis.map((p) => ({ id: p.id, code: p.code, title: p.title, priority: p.priority, sort_order: p.sort_order, description: p.description, created_at: p.created_at, status: pbiStatusToApi(p.status) })),
storiesByPbi,
tasksByStory,
}}
>
<UrlTaskSync />
<BacklogSplitPane
cookieKey={`backlog-${id}-mobile`}
defaultSplit={[20, 45, 35]}

View file

@ -0,0 +1,52 @@
// PBI-74 / T-870: GET /api/pbis/:id/stories
//
// Levert stories binnen een PBI voor ensurePbiLoaded. Access-control via
// product-eigenaarschap van het bovenliggende PBI.
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { storyStatusToApi } from '@/lib/task-status'
export const dynamic = 'force-dynamic'
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id } = await params
const pbi = await prisma.pbi.findFirst({
where: { id, product: productAccessFilter(auth.userId) },
select: { id: true },
})
if (!pbi) {
return Response.json({ error: 'PBI niet gevonden' }, { status: 404 })
}
const stories = await prisma.story.findMany({
where: { pbi_id: id },
orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }, { created_at: 'asc' }],
select: {
id: true,
code: true,
title: true,
description: true,
acceptance_criteria: true,
priority: true,
sort_order: true,
status: true,
pbi_id: true,
sprint_id: true,
created_at: true,
},
})
return Response.json(
stories.map((s) => ({ ...s, status: storyStatusToApi(s.status) })),
)
}

View file

@ -0,0 +1,100 @@
// PBI-74 / T-870: GET /api/products/:id/backlog
//
// Levert een volledige ProductBacklogSnapshot voor de workspace-store
// (ensureProductLoaded). Auth + access-control consistent met andere
// product-routes (authenticateApiRequest + productAccessFilter).
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { pbiStatusToApi, storyStatusToApi, taskStatusToApi } from '@/lib/task-status'
export const dynamic = 'force-dynamic'
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id } = await params
const product = await prisma.product.findFirst({
where: { id, ...productAccessFilter(auth.userId) },
select: { id: true, name: true },
})
if (!product) {
return Response.json({ error: 'Product niet gevonden' }, { status: 404 })
}
const [pbis, stories, tasks] = await Promise.all([
prisma.pbi.findMany({
where: { product_id: id },
orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }, { created_at: 'asc' }],
select: {
id: true,
code: true,
title: true,
priority: true,
sort_order: true,
description: true,
created_at: true,
status: true,
},
}),
prisma.story.findMany({
where: { product_id: id },
orderBy: [{ priority: 'asc' }, { sort_order: 'asc' }, { created_at: 'asc' }],
select: {
id: true,
code: true,
title: true,
description: true,
acceptance_criteria: true,
priority: true,
sort_order: true,
status: true,
pbi_id: true,
sprint_id: true,
created_at: true,
},
}),
prisma.task.findMany({
where: { story: { product_id: id } },
orderBy: [{ sort_order: 'asc' }, { created_at: 'asc' }],
select: {
id: true,
title: true,
description: true,
priority: true,
sort_order: true,
status: true,
story_id: true,
created_at: true,
},
}),
])
const storiesByPbi: Record<string, unknown[]> = {}
for (const story of stories) {
const apiStory = { ...story, status: storyStatusToApi(story.status) }
if (!storiesByPbi[story.pbi_id]) storiesByPbi[story.pbi_id] = []
storiesByPbi[story.pbi_id].push(apiStory)
}
const tasksByStory: Record<string, unknown[]> = {}
for (const task of tasks) {
const apiTask = { ...task, status: taskStatusToApi(task.status) }
if (!tasksByStory[task.story_id]) tasksByStory[task.story_id] = []
tasksByStory[task.story_id].push(apiTask)
}
return Response.json({
product,
pbis: pbis.map((p) => ({ ...p, status: pbiStatusToApi(p.status) })),
storiesByPbi,
tasksByStory,
})
}

View file

@ -0,0 +1,49 @@
// PBI-74 / T-870: GET /api/stories/:id/tasks
//
// Levert tasks binnen een story voor ensureStoryLoaded. Access-control via
// product-eigenaarschap van de bovenliggende story.
import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { taskStatusToApi } from '@/lib/task-status'
export const dynamic = 'force-dynamic'
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id } = await params
const story = await prisma.story.findFirst({
where: { id, product: productAccessFilter(auth.userId) },
select: { id: true },
})
if (!story) {
return Response.json({ error: 'Story niet gevonden' }, { status: 404 })
}
const tasks = await prisma.task.findMany({
where: { story_id: id },
orderBy: [{ sort_order: 'asc' }, { created_at: 'asc' }],
select: {
id: true,
title: true,
description: true,
priority: true,
sort_order: true,
status: true,
story_id: true,
created_at: true,
},
})
return Response.json(
tasks.map((t) => ({ ...t, status: taskStatusToApi(t.status) })),
)
}

View file

@ -3,6 +3,56 @@ import { prisma } from '@/lib/prisma'
import { z } from 'zod'
import { TASK_STATUS_API_VALUES, taskStatusFromApi, taskStatusToApi } from '@/lib/task-status'
import { propagateStatusUpwards } from '@/lib/tasks-status-update'
import { productAccessFilter } from '@/lib/product-access'
// PBI-74 / T-869: force-dynamic zodat Next geen response-cache hangt aan
// deze route — workspace-store leest hier verse data via ensureTaskLoaded.
export const dynamic = 'force-dynamic'
// PBI-74 / T-870: GET-handler voor ensureTaskLoaded. Levert TaskDetail-shape
// (extends BacklogTask met implementation_plan etc.). Access-control via
// product van de parent-story.
export async function GET(
request: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const auth = await authenticateApiRequest(request)
if ('error' in auth) {
return Response.json({ error: auth.error }, { status: auth.status })
}
const { id } = await params
const task = await prisma.task.findFirst({
where: {
id,
story: { product: productAccessFilter(auth.userId) },
},
select: {
id: true,
title: true,
description: true,
priority: true,
sort_order: true,
status: true,
story_id: true,
created_at: true,
implementation_plan: true,
requires_opus: true,
verify_only: true,
verify_required: true,
},
})
if (!task) {
return Response.json({ error: 'Task niet gevonden' }, { status: 404 })
}
return Response.json({
...task,
status: taskStatusToApi(task.status),
_detail: true,
})
}
// `review` is a valid TaskStatus in the DB and the kanban-board UI, but the
// sprint task list (components/sprint/task-list.tsx) does not yet render it.

View file

@ -1,8 +1,15 @@
'use client'
import { useEffect, useRef } from 'react'
import { useBacklogStore, type BacklogPbi, type BacklogStory, type BacklogTask } from '@/stores/backlog-store'
import { useBacklogRealtime } from '@/lib/realtime/use-backlog-realtime'
import { useWorkspaceResync } from '@/lib/realtime/use-workspace-resync'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type {
BacklogPbi,
BacklogStory,
BacklogTask,
ProductBacklogSnapshot,
} from '@/stores/product-workspace/types'
interface InitialData {
pbis: BacklogPbi[]
@ -13,6 +20,7 @@ interface InitialData {
interface BacklogHydrationWrapperProps {
initialData: InitialData
productId: string
productName?: string
children: React.ReactNode
}
@ -27,19 +35,40 @@ function fingerprint(data: InitialData): string {
return `${pbiPart}|${storyPart}|${taskPart}`
}
export function BacklogHydrationWrapper({ initialData, productId, children }: BacklogHydrationWrapperProps) {
const setInitialData = useBacklogStore((s) => s.setInitialData)
// PBI-74 / Story 8: workspace-store is nu enige bron — dual-dispatch weg.
function toWorkspaceSnapshot(
data: InitialData,
productId: string,
productName: string | undefined,
): ProductBacklogSnapshot {
return {
product: { id: productId, name: productName ?? '' },
pbis: data.pbis,
storiesByPbi: data.storiesByPbi,
tasksByStory: data.tasksByStory,
}
}
export function BacklogHydrationWrapper({
initialData,
productId,
productName,
children,
}: BacklogHydrationWrapperProps) {
const lastFingerprint = useRef<string>('')
useEffect(() => {
const fp = fingerprint(initialData)
if (fp !== lastFingerprint.current) {
lastFingerprint.current = fp
setInitialData(initialData)
useProductWorkspaceStore
.getState()
.hydrateSnapshot(toWorkspaceSnapshot(initialData, productId, productName))
}
}, [initialData, setInitialData])
}, [initialData, productId, productName])
useBacklogRealtime(productId)
useWorkspaceResync()
return <>{children}</>
}

View file

@ -1,13 +1,16 @@
'use client'
import { useState } from 'react'
import { useSelectionStore } from '@/stores/selection-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { SplitPane, type SplitPaneProps } from '@/components/split-pane/split-pane'
type Props = Omit<SplitPaneProps, 'activeTab' | 'onActiveTabChange'>
// PBI-74 / T-848: leest active PBI/story-ids uit workspace-store. Primitives,
// dus geen useShallow nodig.
export function BacklogSplitPane(props: Props) {
const { selectedPbiId, selectedStoryId } = useSelectionStore()
const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId)
const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId)
const [activeTab, setActiveTab] = useState(0)
// React-recommended "derived state from props" pattern: update state during render

View file

@ -25,9 +25,10 @@ import { CheckSquare, Square } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { useSelectionStore } from '@/stores/selection-store'
import { usePlannerStore } from '@/stores/planner-store'
import { useBacklogStore } from '@/stores/backlog-store'
import { useShallow } from 'zustand/react/shallow'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { selectVisiblePbis } from '@/stores/product-workspace/selectors'
import type { BacklogPbi as WorkspacePbi } from '@/stores/product-workspace/types'
import { deletePbiAction } from '@/actions/pbis'
import { reorderPbisAction, updatePbiPriorityAction } from '@/actions/stories'
import { cn } from '@/lib/utils'
@ -235,10 +236,13 @@ function SortablePbiRow({
}
// --- Main component ---
// PBI-74 / T-849: leest pbis + actieve selectie uit workspace-store via
// useShallow-selector. DnD-mutaties via applyOptimisticMutation/rollback/settle.
export function PbiList({ productId, isDemo }: PbiListProps) {
const pbis = useBacklogStore((s) => s.pbis)
const { selectedPbiId, selectPbi } = useSelectionStore()
const { pbiOrder, pbiPriority, initPbis, reorderPbis, rollbackPbis, updatePbiPriority } = usePlannerStore()
// selectVisiblePbis is gesorteerd op priority/sort_order; useShallow
// voorkomt re-render op ongerelateerde store-mutaties (G2).
const pbis = useProductWorkspaceStore(useShallow(selectVisiblePbis)) as WorkspacePbi[]
const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId)
// Defaults match SSR; persisted values applied post-mount in the loader effect below.
// This avoids hydration mismatch when localStorage holds non-default values.
const [filterPriority, setFilterPriority] = useState<number | 'all'>('all')
@ -295,22 +299,10 @@ export function PbiList({ productId, isDemo }: PbiListProps) {
useEffect(() => { if (prefsLoaded) localStorage.setItem('scrum4me:pbi_filter_status', filterStatus) }, [filterStatus, prefsLoaded])
useEffect(() => { if (prefsLoaded) localStorage.setItem('scrum4me:pbi_sort_dir', sortDir) }, [sortDir, prefsLoaded])
// Sync server data into store — use stable string dep to avoid infinite loop
const pbiIdKey = pbis.map(p => p.id).join(',')
useEffect(() => {
initPbis(productId, pbiIdKey ? pbiIdKey.split(',') : [])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [productId, pbiIdKey])
// Build ordered PBI list from store (or fall back to server order)
const order = pbiOrder[productId] ?? pbis.map(p => p.id)
// pbis komen al gesorteerd binnen via selectVisiblePbis (priority + sort_order).
// Geen aparte order/priority maps meer — workspace-store entities zijn de waarheid.
const pbiMap = Object.fromEntries(pbis.map(p => [p.id, p]))
// Apply priority overrides from store
const orderedPbis = order
.map(id => pbiMap[id])
.filter(Boolean)
.map(p => ({ ...p, priority: pbiPriority[p.id] ?? p.priority }))
const orderedPbis = pbis
const base = orderedPbis.filter(p => {
if (filterPriority !== 'all' && p.priority !== filterPriority) return false
@ -353,30 +345,58 @@ export function PbiList({ productId, isDemo }: PbiListProps) {
const overPbi = pbiMap[over.id as string]
if (!activePbi || !overPbi) return
const prevOrder = [...order]
const oldIndex = order.indexOf(active.id as string)
const newIndex = order.indexOf(over.id as string)
const newOrder = arrayMove([...order], oldIndex, newIndex)
const store = useProductWorkspaceStore.getState()
const prevOrder = [...store.relations.pbiIds]
const oldIndex = prevOrder.indexOf(active.id as string)
const newIndex = prevOrder.indexOf(over.id as string)
if (oldIndex === -1 || newIndex === -1) return
const newOrder = arrayMove([...prevOrder], oldIndex, newIndex)
// Optimistic update
reorderPbis(productId, newOrder)
// Snapshot rollback-info en pas optimistisch toe.
const orderMutationId = store.applyOptimisticMutation({
kind: 'pbi-order',
prevPbiIds: prevOrder,
})
useProductWorkspaceStore.setState((s) => {
s.relations.pbiIds = newOrder
})
const priorityChanged = activePbi.priority !== overPbi.priority
let priorityMutationId: string | null = null
if (priorityChanged) {
priorityMutationId = store.applyOptimisticMutation({
kind: 'entity-patch',
entity: 'pbi',
id: active.id as string,
prev: store.entities.pbisById[active.id as string],
})
useProductWorkspaceStore.setState((s) => {
const pbi = s.entities.pbisById[active.id as string]
if (pbi) pbi.priority = overPbi.priority
})
}
startTransition(async () => {
const settle = () => {
const st = useProductWorkspaceStore.getState()
if (priorityMutationId) st.settleMutation(priorityMutationId)
st.settleMutation(orderMutationId)
}
const rollback = (msg: string) => {
const st = useProductWorkspaceStore.getState()
if (priorityMutationId) st.rollbackMutation(priorityMutationId)
st.rollbackMutation(orderMutationId)
toast.error(msg)
}
if (priorityChanged) {
updatePbiPriority(active.id as string, overPbi.priority)
const result = await updatePbiPriorityAction(active.id as string, overPbi.priority, productId)
if (!result.success) {
rollbackPbis(productId, prevOrder)
toast.error('Prioriteit opslaan mislukt')
}
if (result.success) settle()
else rollback('Prioriteit opslaan mislukt')
} else {
const result = await reorderPbisAction(productId, newOrder)
if (!result.success) {
rollbackPbis(productId, prevOrder)
toast.error('Volgorde opslaan mislukt')
}
if (result.success) settle()
else rollback('Volgorde opslaan mislukt')
}
})
}
@ -384,7 +404,9 @@ export function PbiList({ productId, isDemo }: PbiListProps) {
function handleDelete(id: string) {
startTransition(async () => {
await deletePbiAction(id)
if (selectedPbiId === id) selectPbi(null)
if (selectedPbiId === id) {
useProductWorkspaceStore.getState().setActivePbi(null)
}
})
}
@ -561,7 +583,7 @@ export function PbiList({ productId, isDemo }: PbiListProps) {
isDemo={isDemo}
selectionMode={selectionMode}
isChecked={selectedIds.has(pbi.id)}
onSelect={() => selectPbi(pbi.id)}
onSelect={() => useProductWorkspaceStore.getState().setActivePbi(pbi.id)}
onToggleCheck={() => toggleCheck(pbi.id)}
onEdit={() => setDialogState({ mode: 'edit', productId, pbi })}
onDelete={() => handleDelete(pbi.id)}

View file

@ -25,9 +25,10 @@ import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { PanelNavBar } from '@/components/shared/panel-nav-bar'
import { useSelectionStore } from '@/stores/selection-store'
import { usePlannerStore } from '@/stores/planner-store'
import { useBacklogStore } from '@/stores/backlog-store'
import { useShallow } from 'zustand/react/shallow'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { selectStoriesForActivePbi } from '@/stores/product-workspace/selectors'
import type { BacklogStory as WorkspaceStory } from '@/stores/product-workspace/types'
import { reorderStoriesAction } from '@/actions/stories'
import { StoryDialog, type StoryDialogState } from './story-dialog'
import { debugProps } from '@/lib/debug'
@ -55,6 +56,7 @@ export interface Story {
description: string | null
acceptance_criteria: string | null
priority: number
sort_order: number
status: string
pbi_id: string
sprint_id: string | null
@ -122,10 +124,12 @@ function SortableStoryBlock({
}
// --- Main component ---
// PBI-74 / T-850: leest stories voor active PBI via selectStoriesForActivePbi
// (useShallow). DnD via applyOptimisticMutation('story-order').
export function StoryPanel({ productId, isDemo }: StoryPanelProps) {
const { selectedPbiId, selectedStoryId, selectStory } = useSelectionStore()
const storiesByPbi = useBacklogStore((s) => s.storiesByPbi)
const { storyOrder, initStories, reorderStories, rollbackStories } = usePlannerStore()
const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId)
const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId)
const rawStories = useProductWorkspaceStore(useShallow(selectStoriesForActivePbi)) as WorkspaceStory[]
const [filterStatus, setFilterStatus] = useState<string | null>(null)
const [filterPriority, setFilterPriority] = useState<number | null>(null)
const [sortMode, setSortMode] = useState<SortMode>(() => {
@ -138,20 +142,9 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) {
useEffect(() => { localStorage.setItem('scrum4me:story_sort', sortMode) }, [sortMode])
const rawStories = selectedPbiId ? (storiesByPbi[selectedPbiId] ?? []) : []
// Sync into store — use stable string dep to avoid infinite loop
const storyIdKey = rawStories.map(s => s.id).join(',')
useEffect(() => {
if (selectedPbiId) {
initStories(selectedPbiId, storyIdKey ? storyIdKey.split(',') : [])
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedPbiId, storyIdKey])
// rawStories komt al gesorteerd binnen via selectStoriesForActivePbi.
const storyMap = Object.fromEntries(rawStories.map(s => [s.id, s]))
const order = (selectedPbiId ? storyOrder[selectedPbiId] : null) ?? rawStories.map(s => s.id)
const orderedStories = order.map(id => storyMap[id]).filter(Boolean)
const orderedStories = rawStories
const base = orderedStories
.filter(s => !filterStatus || s.status === filterStatus)
@ -185,14 +178,36 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) {
const overStory = storyMap[over.id as string]
if (!activeStory || !overStory) return
const prevOrder = [...order]
const oldIndex = order.indexOf(active.id as string)
const newIndex = order.indexOf(over.id as string)
const newOrder = arrayMove([...order], oldIndex, newIndex)
const store = useProductWorkspaceStore.getState()
const prevOrder = [...(store.relations.storyIdsByPbi[selectedPbiId] ?? [])]
const oldIndex = prevOrder.indexOf(active.id as string)
const newIndex = prevOrder.indexOf(over.id as string)
if (oldIndex === -1 || newIndex === -1) return
const newOrder = arrayMove([...prevOrder], oldIndex, newIndex)
reorderStories(selectedPbiId, newOrder)
const orderMutationId = store.applyOptimisticMutation({
kind: 'story-order',
pbiId: selectedPbiId,
prevStoryIds: prevOrder,
})
useProductWorkspaceStore.setState((s) => {
s.relations.storyIdsByPbi[selectedPbiId] = newOrder
})
const priorityChanged = activeStory.priority !== overStory.priority
let priorityMutationId: string | null = null
if (priorityChanged) {
priorityMutationId = store.applyOptimisticMutation({
kind: 'entity-patch',
entity: 'story',
id: active.id as string,
prev: store.entities.storiesById[active.id as string],
})
useProductWorkspaceStore.setState((s) => {
const story = s.entities.storiesById[active.id as string]
if (story) story.priority = overStory.priority
})
}
startTransition(async () => {
const result = await reorderStoriesAction(
@ -201,8 +216,13 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) {
newOrder,
priorityChanged ? overStory.priority : undefined
)
if (!result.success) {
rollbackStories(selectedPbiId, prevOrder)
const st = useProductWorkspaceStore.getState()
if (result.success) {
if (priorityMutationId) st.settleMutation(priorityMutationId)
st.settleMutation(orderMutationId)
} else {
if (priorityMutationId) st.rollbackMutation(priorityMutationId)
st.rollbackMutation(orderMutationId)
toast.error('Volgorde opslaan mislukt')
}
})
@ -284,7 +304,7 @@ export function StoryPanel({ productId, isDemo }: StoryPanelProps) {
key={story.id}
story={story}
isSelected={selectedStoryId === story.id}
onSelect={() => selectStory(story.id)}
onSelect={() => useProductWorkspaceStore.getState().setActiveStory(story.id)}
onEdit={() => setStoryDialogState({ mode: 'edit', story, productId })}
/>
))}

View file

@ -26,8 +26,13 @@ import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { PanelNavBar } from '@/components/shared/panel-nav-bar'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { useSelectionStore } from '@/stores/selection-store'
import { useBacklogStore, type BacklogTask } from '@/stores/backlog-store'
import { useShallow } from 'zustand/react/shallow'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { selectTasksForActiveStory } from '@/stores/product-workspace/selectors'
import type {
BacklogTask,
TaskDetail,
} from '@/stores/product-workspace/types'
import { reorderTasksAction } from '@/actions/tasks'
import { BacklogCard } from './backlog-card'
import { debugProps } from '@/lib/debug'
@ -52,7 +57,7 @@ function SortableTaskCard({
isDemo,
onClick,
}: {
task: BacklogTask
task: BacklogTask | TaskDetail
isDemo: boolean
onClick: () => void
}) {
@ -94,22 +99,20 @@ interface TaskPanelProps {
closePath: string
}
// PBI-74 / T-851: leest tasks voor active story via selectTasksForActiveStory
// (useShallow). DnD via applyOptimisticMutation('task-order'). Detail-view
// (ensureTaskLoaded + isDetail()) zit in de task-dialog, niet in deze lijst.
export function TaskPanel({ isDemo, closePath }: TaskPanelProps) {
const router = useRouter()
const [, startTransition] = useTransition()
const selectedStoryId = useSelectionStore((s) => s.selectedStoryId)
const tasksByStory = useBacklogStore((s) => s.tasksByStory)
const selectedStoryId = useProductWorkspaceStore((s) => s.context.activeStoryId)
const rawTasks = useProductWorkspaceStore(useShallow(selectTasksForActiveStory)) as
| (BacklogTask | TaskDetail)[]
const [activeDragId, setActiveDragId] = useState<string | null>(null)
const [localOrder, setLocalOrder] = useState<string[] | null>(null)
const rawTasks = selectedStoryId ? (tasksByStory[selectedStoryId] ?? []) : null
// Merge local order with rawTasks for optimistic reorder
const tasks: BacklogTask[] | null = rawTasks === null
? null
: localOrder
? localOrder.map((id) => rawTasks.find((t) => t.id === id)).filter(Boolean) as BacklogTask[]
: rawTasks
const tasks: (BacklogTask | TaskDetail)[] | null = selectedStoryId
? rawTasks
: null
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
@ -126,19 +129,30 @@ export function TaskPanel({ isDemo, closePath }: TaskPanelProps) {
const { active, over } = event
if (!over || active.id === over.id) return
const ids = tasks.map((t) => t.id)
const oldIndex = ids.indexOf(active.id as string)
const newIndex = ids.indexOf(over.id as string)
const store = useProductWorkspaceStore.getState()
const prevOrder = [...(store.relations.taskIdsByStory[selectedStoryId] ?? [])]
const oldIndex = prevOrder.indexOf(active.id as string)
const newIndex = prevOrder.indexOf(over.id as string)
if (oldIndex === -1 || newIndex === -1) return
const newOrder = arrayMove([...prevOrder], oldIndex, newIndex)
const newOrder = arrayMove(ids, oldIndex, newIndex)
setLocalOrder(newOrder)
const orderMutationId = store.applyOptimisticMutation({
kind: 'task-order',
storyId: selectedStoryId,
prevTaskIds: prevOrder,
})
useProductWorkspaceStore.setState((s) => {
s.relations.taskIdsByStory[selectedStoryId] = newOrder
})
startTransition(async () => {
const result = await reorderTasksAction(selectedStoryId, newOrder)
const st = useProductWorkspaceStore.getState()
if (result?.error) {
setLocalOrder(null)
st.rollbackMutation(orderMutationId)
toast.error(result.error)
} else {
st.settleMutation(orderMutationId)
}
})
}

View file

@ -0,0 +1,32 @@
'use client'
// PBI-74 / T-859: URL-prioriteit boven restore-hint.
//
// Als de route `?editTask=<id>` draagt, wint dat boven de localStorage-hint
// die de restore-flow normaal zou toepassen. We schrijven de URL-id direct
// naar de task-hint en roepen setActiveTask aan; de restore-flow leest de
// task-hint pas na drie ensure*Loaded-awaits, dus onze schrijfactie wint
// in de praktijk altijd.
import { useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { writeTaskHint } from '@/stores/product-workspace/restore'
export function UrlTaskSync() {
const searchParams = useSearchParams()
const editTask = searchParams.get('editTask')
useEffect(() => {
if (!editTask) return
const productId = useProductWorkspaceStore.getState().context.activeProduct?.id
if (productId) {
// Hint overschrijven zodat restore-flow's setActiveTask op deze id eindigt
// (mocht hij na onze directe call komen).
writeTaskHint(productId, editTask)
}
useProductWorkspaceStore.getState().setActiveTask(editTask)
}, [editTask])
return null
}

View file

@ -1,16 +1,18 @@
'use client'
import { useEffect } from 'react'
import { useProductStore } from '@/stores/product-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import { debugProps } from '@/lib/debug'
// PBI-74 / T-853: workspace-store is nu enige bron voor active product.
// De voorganger (stores/product-store.ts) wordt in Story 8 (T-876) verwijderd.
export function SetCurrentProduct({ id, name }: { id: string; name: string }) {
const { setCurrentProduct, clearCurrentProduct } = useProductStore()
useEffect(() => {
setCurrentProduct(id, name)
return () => clearCurrentProduct()
}, [id, name, setCurrentProduct, clearCurrentProduct])
useProductWorkspaceStore.getState().setActiveProduct({ id, name })
return () => {
useProductWorkspaceStore.getState().setActiveProduct(null)
}
}, [id, name])
return <span {...debugProps('set-current-product')} hidden />
}

View file

@ -45,6 +45,7 @@ export interface SprintStory {
sprint_id: string | null
created_at: Date
priority: number
sort_order: number
status: string
taskCount: number
doneCount: number

View file

@ -21,8 +21,12 @@ import {
entityDialogHeaderClasses,
} from '@/components/shared/entity-dialog-layout'
import { createSprintAction } from '@/actions/sprints'
import { useSelectionStore } from '@/stores/selection-store'
import { useBacklogStore } from '@/stores/backlog-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import {
selectActivePbi,
selectStoriesForActivePbi,
} from '@/stores/product-workspace/selectors'
import { useShallow } from 'zustand/react/shallow'
interface StartSprintButtonProps {
productId: string
@ -46,14 +50,11 @@ export function StartSprintButton({ productId, isDemo = false }: StartSprintButt
const [dirty, setDirty] = useState(false)
const formRef = useRef<HTMLFormElement>(null)
const router = useRouter()
const selectedPbiId = useSelectionStore((s) => s.selectedPbiId)
const selectedPbi = useBacklogStore((s) =>
selectedPbiId ? s.pbis.find((p) => p.id === selectedPbiId) ?? null : null,
)
const freeStoryCount = useBacklogStore((s) => {
if (!selectedPbiId) return 0
return (s.storiesByPbi[selectedPbiId] ?? []).filter((story) => story.sprint_id === null).length
})
// PBI-74 / T-852: actief PBI + free-story count via workspace-store selectors.
const selectedPbiId = useProductWorkspaceStore((s) => s.context.activePbiId)
const selectedPbi = useProductWorkspaceStore(selectActivePbi)
const stories = useProductWorkspaceStore(useShallow(selectStoriesForActivePbi))
const freeStoryCount = stories.filter((story) => story.sprint_id === null).length
const [state, formAction, pending] = useActionState<ActionResult | undefined, FormData>(
async (_prev, fd) => {

View file

@ -2,7 +2,7 @@
# Documentation Index
Auto-generated on 2026-05-09 from front-matter and headings.
Auto-generated on 2026-05-10 from front-matter and headings.
## Architecture Decision Records
@ -62,6 +62,7 @@ Auto-generated on 2026-05-09 from front-matter and headings.
| [Tweede Claude Agent — Planning Agent](./plans/tweede-claude-agent-planning.md) | proposal | 2026-05-03 |
| [Scrum4Me — v1.0 readiness](./plans/v1-readiness.md) | active | 2026-05-04 |
| [Zustand store rearchitecture - active context, realtime en resync](./plans/zustand-store-rearchitecture.md) | ready-to-execute | 2026-05-09 |
| [Zustand workspace-store implementatieplan (PBI-74)](./plans/zustand-workspace-store-implementation.md) | ready-to-execute | 2026-05-09 |
### Archive
@ -89,7 +90,8 @@ Auto-generated on 2026-05-09 from front-matter and headings.
| [Float sort_order (drag-and-drop volgorde)](./patterns/sort-order.md) | active | 2026-05-03 |
| [Story met UI-component](./patterns/story-with-ui-component.md) | active | 2026-05-03 |
| [Web Push](./patterns/web-push.md) | active | 2026-05-07 |
| [Zustand optimistische update + rollback](./patterns/zustand-optimistic.md) | active | 2026-05-03 |
| [Workspace-store + realtime — bounded-context patroon](./patterns/workspace-store.md) | active | 2026-05-10 |
| [Zustand optimistische update + rollback](./patterns/zustand-optimistic.md) | active | 2026-05-10 |
## Other Docs

View file

@ -527,6 +527,38 @@ curl -X POST -H "Authorization: Bearer $CRON_SECRET" \
---
## Workspace store endpoint audit (PBI-74)
`product-workspace-store` heeft vier `ensure*Loaded`-loaders. Deze tabel
documenteert welke routes al bestaan en welke in Story 7 (T-870) toegevoegd
worden. Tot dan retourneert de stub-default in vitest een lege response.
| Loader | URL | Status | Op te leveren in |
|---|---|---|---|
| `ensureProductLoaded(productId)` | `GET /api/products/:id/backlog` | **ontbreekt** | T-870 (Story 7) |
| `ensurePbiLoaded(pbiId)` | `GET /api/pbis/:id/stories` | **ontbreekt** (en `/api/pbis` route-folder bestaat nog niet) | T-870 (Story 7) |
| `ensureStoryLoaded(storyId)` | `GET /api/stories/:id/tasks` | **ontbreekt** (alleen `tasks/reorder` bestaat) | T-870 (Story 7) |
| `ensureTaskLoaded(taskId)` | `GET /api/tasks/:id` | **ontbreekt** (alleen `PATCH` bestaat) | T-870 (Story 7) |
Vereisten voor de toe te voegen routes:
- Auth via `authenticateApiRequest` (Bearer-token), conform bestaande patroon.
- Access-control via `getAccessibleProduct(productId, userId)` uit
`lib/product-access.ts` waar de route product-context heeft.
- `export const dynamic = 'force-dynamic'` zodat Next geen response-cache
introduceert (T-869 in Story 7).
- Response-shape:
- `GET /api/products/:id/backlog``ProductBacklogSnapshot` (`{ product?, pbis[], storiesByPbi, tasksByStory }`).
- `GET /api/pbis/:id/stories``BacklogStory[]`.
- `GET /api/stories/:id/tasks``BacklogTask[]`.
- `GET /api/tasks/:id``TaskDetail` (extends `BacklogTask` met `_detail: true` plus extra velden zoals `implementation_plan`, `acceptance_criteria`, `requires_opus`, `estimated_minutes`).
- Type-bron: `stores/product-workspace/types.ts`.
Auth/access-control wijzigt niet — de rearchitecture raakt alleen
client-state, niet serverlaag-security.
---
## Voorbeeldworkflow voor Claude Code
1. **Probe:** `GET /api/health?db=1` — bevestig dat de service en DB bereikbaar zijn.

View file

@ -0,0 +1,414 @@
---
title: "Workspace-store + realtime — bounded-context patroon"
status: active
audience: [ai-agent, contributor]
language: nl
last_updated: 2026-05-10
when_to_read: "When adding a new bounded-context client store backed by SSE, or when modifying product/sprint workspace state."
---
# Patroon: workspace-store + realtime
Sinds PBI-74 is `product-workspace-store` de blueprint voor client-state op een
**bounded context** (één coherente workflow). Andere bounded contexts mogen
hetzelfde patroon volgen — `sprint-workspace-store`, `solo-store`,
`notifications-store`. Dit document beschrijft wanneer je een workspace-store
opzet, hoe je 'm structureert, hoe SSE en de store samenwerken, en welke
gotchas in code-comments hoort.
Bron-ontwerp: [zustand-store-rearchitecture.md](../plans/zustand-store-rearchitecture.md).
Referentie-implementatie: [stores/product-workspace/](../../stores/product-workspace/).
---
## Wanneer een workspace-store
Eén store **per bounded context**, niet per pagina en niet één megastore.
| Workflow | Store |
|---|---|
| Product backlog (PBI/story/task selectie + DnD) | `product-workspace-store` |
| Sprint board | `sprint-workspace-store` (toekomstig, PBI > 74) |
| Solo execution | `solo-store` |
| Notifications/questions | `notifications-store` |
| Idea grill/plan-flow | `idea-store` |
| Lijst van producten | `products-store` (≠ active product) |
Splits niet per panel; bundel niet over workflows.
---
## State-shape
Vlak en **genormaliseerd**. Vijf slices:
```ts
{
context: { active*Id } // huidige selectie
entities: { *ById } // entity-maps per kind
relations: { ids[], idsByParent } // gesorteerde id-lijsten
loading: { loaded*Ids, activeRequestId } // race-safe markers
sync: { realtimeStatus, lastResyncAt, resyncReason }
pendingMutations: { [id]: { mutation, createdAt } }
}
```
**Acties** zijn in dezelfde store:
`hydrateSnapshot`, `setActive*`, `ensure*Loaded`, `applyRealtimeEvent`,
`resyncActiveScopes`, `resyncLoadedScopes`,
`applyOptimisticMutation`/`rollbackMutation`/`settleMutation`.
Gebruik `zustand/middleware/immer`. Mutation-style (G3 — return nooit een
nieuwe state uit een immer-recipe; muteer de draft).
---
## Selectors
Module-level **`EMPTY`**-refs (G1) en `useShallow` voor lijsten (G2).
```ts
// stores/product-workspace/selectors.ts
const EMPTY_PBIS: BacklogPbi[] = []
export function selectVisiblePbis(s: Store): BacklogPbi[] {
if (s.relations.pbiIds.length === 0) return EMPTY_PBIS
return s.relations.pbiIds.map((id) => s.entities.pbisById[id]).filter(Boolean)
}
```
```tsx
// component
import { useShallow } from 'zustand/react/shallow'
import { selectVisiblePbis } from '@/stores/product-workspace/selectors'
const pbis = useStore(useShallow(selectVisiblePbis))
const activePbiId = useStore((s) => s.context.activePbiId) // primitive — geen useShallow
```
Single-value selectors (`selectActivePbi`) hebben geen `useShallow` nodig.
---
## ensure*Loaded — race-safe loaders
Elke setter genereert een nieuwe `requestId`, schrijft 'm in
`loading.activeRequestId`, en triggert de loader. De loader checkt **na de
fetch** of de guard nog matcht — anders bail-out.
```ts
setActivePbi(pbiId) {
const requestId = newRequestId()
set((s) => {
s.context.activePbiId = pbiId
s.context.activeStoryId = null
s.context.activeTaskId = null
s.loading.activeRequestId = requestId
})
if (pbiId) void get().ensurePbiLoaded(pbiId, requestId)
}
async ensurePbiLoaded(pbiId, requestId) {
const stories = await fetchJson(`/api/pbis/${pbiId}/stories`)
if (requestId && get().loading.activeRequestId !== requestId) return
if (!Array.isArray(stories)) return
set((s) => { /* apply */ })
}
```
**Belangrijke regels:**
- Gebruik `get().method()` per call (G4) — nooit `state.method()` via een
gecaptured snapshot. Method-refs zijn niet stabiel over immer state-versies.
- `fetch(url, { cache: 'no-store' })` op alle client-fetches.
- Server read-routes: `export const dynamic = 'force-dynamic'`.
---
## SSE-hook beheert transport, store beheert betekenis
```txt
useXxxRealtime(activeId)
-> opent /api/realtime/xxx?...
-> parsed event
-> dispatcht naar store.applyRealtimeEvent(event)
-> beheert reconnect/backoff/status
-> op 'ready' na (re)connect: telt cycles; latere ready triggert resync('reconnect')
```
```ts
// applyRealtimeEvent regels
known pbi/story/task event
→ upsert + sort, parent-move bij wijziging parent_id
→ idempotent: bestaande id bij INSERT → return
→ DELETE → ruim child entities op + clear actieve selectie als die viel
unknown entity met matching product_id, geen 'type' veld
→ resyncActiveScopes('unknown-event')
job/worker/heartbeat (heeft 'type' veld)
→ negeer
```
**Idempotent:** een event dat al via een optimistic mutation is toegepast,
mag geen dubbele insert of verkeerde rollback veroorzaken. INSERTs checken
`if (entity exists) return`. UPDATEs zijn altijd merge-into-existing.
Payload-contract: zie [realtime-notify-payload.md](./realtime-notify-payload.md).
---
## Hidden tab + reconnect resync
EventSource blijft open als de tab `hidden` wordt — gemiste events worden
opgehaald via een expliciete resync-laag.
```ts
// In de realtime-hook
const onVisibility = () => {
if (document.visibilityState === 'visible' && sourceRef.current === null) {
connect() // alleen als de stream weg is (b.v. server hard-close na 240s)
}
}
// Geen close() bij hidden.
source.addEventListener('ready', () => {
readyCountRef.current += 1
if (readyCountRef.current > 1) {
void store.resyncActiveScopes('reconnect')
}
})
```
```ts
// useWorkspaceResync — visibility + online
useEffect(() => {
const onVisibility = () => {
if (document.visibilityState === 'visible') {
void store.resyncActiveScopes('visible')
}
}
const onOnline = () => void store.resyncActiveScopes('reconnect')
document.addEventListener('visibilitychange', onVisibility)
window.addEventListener('online', onOnline)
return () => { /* remove */ }
}, [])
```
**Mount in dezelfde wrapper als de realtime-hook.** Doe nooit alleen het
sluiten-op-hidden weghalen zonder de resync-laag erbij — dan verlies je het
vangnet.
`resyncActiveScopes` triggert alleen de loaders die gekoppeld zijn aan de
huidige selectie:
```ts
async resyncActiveScopes(reason) {
const ctx = get().context
const tasks: Promise<void>[] = []
if (ctx.activeProduct?.id) tasks.push(get().ensureProductLoaded(ctx.activeProduct.id))
if (ctx.activePbiId) tasks.push(get().ensurePbiLoaded(ctx.activePbiId))
if (ctx.activeStoryId) tasks.push(get().ensureStoryLoaded(ctx.activeStoryId))
if (ctx.activeTaskId) tasks.push(get().ensureTaskLoaded(ctx.activeTaskId))
set((s) => { s.sync.lastResyncAt = Date.now(); s.sync.resyncReason = reason })
await Promise.allSettled(tasks)
}
```
---
## LocalStorage = restore-hint, niet waarheid
Selectie-id's worden gepersisteerd om bij cold reload de vorige selectie te
herstellen, **maar de hint wordt pas toegepast nadat ensure-load is gelukt
en de hint-id bevestigd is in `entities.byId`**.
```ts
setActiveProduct(product) {
set((s) => { s.context.activeProduct = product; ... })
writeProductHint(product?.id ?? null)
if (product) {
void (async () => {
await get().ensureProductLoaded(product.id, requestId)
if (get().loading.activeRequestId !== requestId) return
const hint = readHints().perProduct[product.id]?.lastActivePbiId
if (hint && get().entities.pbisById[hint]) {
get().setActivePbi(hint) // cascade — die doet zelfde voor story
}
})()
}
}
```
**Geen `setTimeout(0)` of microtask-trick.** De fetch is dan nog niet klaar,
de validatie `entities.byId[hint]` faalt altijd. Chain altijd `await
ensureXxxLoaded` en valideer in dezelfde `requestId`-cycle.
**URL wint van hint.** Maak een client-component (b.v.
[`UrlTaskSync`](../../components/backlog/url-task-sync.tsx)) die op mount
`useSearchParams().get('editTask')` leest, de hint overschrijft via
`writeTaskHint`, en `setActiveTask` aanroept. De restore-flow leest de
task-hint pas na drie ensure-awaits, dus de URL-write komt altijd eerder.
---
## Optimistic mutations
Voor DnD en status-toggles. De store registreert alleen het rollback-snapshot;
de component muteert state direct én roept de server aan.
```tsx
function handleDragEnd(event) {
const store = useStore.getState()
const prevOrder = [...store.relations.pbiIds]
const newOrder = arrayMove(prevOrder, oldIndex, newIndex)
// 1. Snapshot voor rollback
const mutationId = store.applyOptimisticMutation({
kind: 'pbi-order',
prevPbiIds: prevOrder,
})
// 2. Optimistisch toepassen
useStore.setState((s) => { s.relations.pbiIds = newOrder })
// 3. Server bevestigt (of niet)
startTransition(async () => {
const result = await reorderPbisAction(productId, newOrder)
const st = useStore.getState()
if (result.success) {
st.settleMutation(mutationId)
} else {
st.rollbackMutation(mutationId)
toast.error('Volgorde opslaan mislukt')
}
})
}
```
**Cross-priority drag** vereist twee mutaties: een `pbi-order` voor de lijst
plus een `entity-patch` voor de priority op de PBI zelf. Beide settle/rollback
samen.
**SSE-echo van een net optimistisch toegepaste wijziging** moet idempotent
zijn — INSERT → bestaat al → return; UPDATE → merge into existing.
---
## API endpoints
Voor elke `ensure*Loaded` een GET-route met:
- Auth via `authenticateApiRequest` (Bearer-token of iron-session cookie).
- Access-control via `productAccessFilter(userId)` voor product-context;
`getAccessibleProduct` voor explicit guards.
- `export const dynamic = 'force-dynamic'`.
- Status-vertaling via `taskStatusToApi` / `storyStatusToApi` /
`pbiStatusToApi` (DB UPPER_SNAKE → API lowercase).
Referentie:
[GET /api/products/:id/backlog](../../app/api/products/[id]/backlog/route.ts),
[GET /api/pbis/:id/stories](../../app/api/pbis/[id]/stories/route.ts),
[GET /api/stories/:id/tasks](../../app/api/stories/[id]/tasks/route.ts),
[GET /api/tasks/:id](../../app/api/tasks/[id]/route.ts).
`TaskDetail` shape extends `BacklogTask` met `_detail: true` plus extra
velden (`implementation_plan`, `acceptance_criteria`, `requires_opus`,
`verify_only`, `verify_required`). Gebruik de `isDetail()` typeguard om de
extra velden te tonen.
---
## Tests
Vitest + jsdom; setup in [`tests/setup.ts`](../../tests/setup.ts):
- `MemoryStorage` shim voor localStorage (G6 — vitest 4 + jsdom 29 mist 'm
als configurable global).
- `globalThis.fetch` herconfigureerbaar gemaakt zodat `vi.spyOn` werkt
(anders krijg je `Cannot redefine property: fetch`).
- Default fetch-stub die `null` JSON returnt — voorkomt unhandled rejections
uit fire-and-forget `ensure*Loaded` calls die in tests niet expliciet
gemockt zijn. Tests overrulen met `vi.spyOn(globalThis, 'fetch')` per case.
- `mockImplementation` (G8) — niet `mockResolvedValue` — anders is de
Response-body na de eerste `.json()` weg.
```ts
// G5: snapshot original actions module-level, restore in beforeEach
const originalActions = (() => {
const s = useStore.getState()
return { /* alle action-refs */ }
})()
function resetStore() {
useStore.setState((s) => {
Object.assign(s, initialDataSlices)
Object.assign(s, originalActions)
})
}
beforeEach(resetStore)
```
**Acties mocken:** gebruik `setState((s) => { s.method = vi.fn() })`. Niet
`vi.spyOn(state, 'method')` — de immer-frozen state is niet redefinable.
**Verplichte test-cases per workspace-store:**
- `hydrateSnapshot` vult entities + relations met sortering.
- Selection cascade: `setActivePbi` reset story+task; `setActiveStory` reset
task.
- `setActiveProduct(null)` ruimt entities en relations op.
- `applyRealtimeEvent` pbi/story/task `I|U|D` met sortering en parent-move.
- Event voor ander `product_id` wordt genegeerd.
- Unknown entity met matching product → `resyncActiveScopes('unknown-event')`
trigger.
- Job/worker/heartbeat/question events met `type`-veld → geen resync.
- Delete-cleanup van actieve selectie.
- Race-safe `ensure*Loaded` met requestId-guard (oude in-flight mag niet
nieuwere selectie overschrijven).
- `ensureTaskLoaded` zet `_detail: true`.
- `resyncActiveScopes` triggert ensure-keten met juiste URLs en zet
`lastResyncAt` + `resyncReason`.
- localStorage restore-hints per setter.
- Hint die niet (meer) in entities zit wordt genegeerd.
- Optimistic mutation rollback/settle/SSE-echo idempotent.
---
## Gotchas — comment-template voor in code
Documenteer deze in code via comments boven de fix.
| # | Symptoom | Fix |
|---|---|---|
| **G1** | "Maximum update depth exceeded" — `s.byId[x] ?? []` levert nieuwe array per render | Module-level `EMPTY` const als fallback |
| **G2** | Component re-rendert op iedere store-mutatie ondanks dat z'n data niet wijzigt | `useShallow(selectXxx)` voor lijsten |
| **G3** | Hele state lijkt gewist na een `setState((s) => ({ context: ... }))` | Gebruik mutation-style: `setState((s) => { s.context.x = y })` (immer recipe muteert draft) |
| **G4** | "method is not a function" in async context, of inconsistente state-mutaties | `get().method()` per call; nooit `const m = state.method` cachen |
| **G5** | Tests beïnvloeden elkaar via `setState({ resyncActiveScopes: vi.fn() })` | `originalActions` snapshot op module-load + restore in `beforeEach` |
| **G6** | `localStorage.clear is not a function` in vitest | `MemoryStorage` shim in `tests/setup.ts` |
| **G7** | "Failed to parse URL from /api/..." in test-fetch | Mock fetch via `vi.spyOn(globalThis, 'fetch')` of stub in setup |
| **G8** | "Body is unusable: Body has already been read" | `vi.fn().mockImplementation(() => Promise.resolve(new Response(...)))` — niet `mockResolvedValue` met een vooraf-gemaakte Response |
---
## Migratiepad voor een nieuwe workspace-store
Volg dezelfde 8 stappen als PBI-74 (zie
[zustand-workspace-store-implementation.md](../plans/zustand-workspace-store-implementation.md)):
1. Skelet — types, store, selectors, restore + tests; geen UI-impact.
2. Hydratie overstappen (parallel naast bestaande store).
3. Componenten omzetten — `useShallow` voor lijsten, `setActiveX` setters.
4. Race-safe loaders + restore-hints + URL-prioriteit.
5. Hidden-tab + reconnect-resync (één PR — anders verlies je vangnet).
6. Unknown-event filter (`isUnknownEntityEvent`).
7. Cache-headers + LIST-endpoints (`force-dynamic`, `cache: 'no-store'`).
8. Oude store opruimen.
Stap 9 ("sprint-workspace-store") is de toepassing van dit patroon op de
sprint-flow — kan starten zodra `product-workspace-store` enkele weken
stabiel in productie staat.

View file

@ -3,34 +3,99 @@ title: "Zustand optimistische update + rollback"
status: active
audience: [ai-agent, contributor]
language: nl
last_updated: 2026-05-03
when_to_read: "When adding client-side state mutations that need optimistic UI and rollback."
last_updated: 2026-05-10
when_to_read: "When adding client-side state mutations that need optimistic UI and rollback (DnD, status toggles)."
---
# Patroon: Zustand optimistische update + rollback
Gebruik dit patroon bij elke dnd-kit `onDragEnd` handler.
Sinds PBI-74 lopen optimistic mutations via `applyOptimisticMutation`/
`rollbackMutation`/`settleMutation` op de **workspace-store**. Het bredere
patroon (store-design, SSE-integratie, restore-hints, tests) staat in
[workspace-store.md](./workspace-store.md). Dit document beschrijft het
DnD/status-mutation flow specifiek.
```ts
const { pbiOrder, reorderPbis, rollbackPbis } = usePlannerStore()
## Patroon
async function handleDragEnd(event: DragEndEvent) {
1. Snapshot rollback-info via `applyOptimisticMutation` — krijgt `mutationId`.
2. Pas state direct aan via `setState`.
3. Server-actie aanroepen.
4. Op success: `settleMutation(mutationId)` (ruimt pending-record op).
5. Op error: `rollbackMutation(mutationId)` (herstelt vorige state + toast).
Cross-priority drag vereist twee mutaties (order + entity-patch) die samen
settlen of rollbacken.
## Voorbeeld — PBI reorder
```tsx
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
function handleDragEnd(event: DragEndEvent) {
const { active, over } = event
if (!over || active.id === over.id) return
const prevOrder = [...pbiOrder[productId]]
const newOrder = arrayMove(prevOrder, oldIndex, newIndex)
const store = useProductWorkspaceStore.getState()
const prevOrder = [...store.relations.pbiIds]
const oldIndex = prevOrder.indexOf(active.id as string)
const newIndex = prevOrder.indexOf(over.id as string)
if (oldIndex === -1 || newIndex === -1) return
const newOrder = arrayMove([...prevOrder], oldIndex, newIndex)
// 1. Optimistisch updaten (direct zichtbaar voor gebruiker)
reorderPbis(productId, newOrder)
// 1. Snapshot rollback-info
const mutationId = store.applyOptimisticMutation({
kind: 'pbi-order',
prevPbiIds: prevOrder,
})
// 2. Persisteren via Server Action
const result = await reorderPbisAction(productId, newOrder)
// 2. Optimistisch toepassen
useProductWorkspaceStore.setState((s) => {
s.relations.pbiIds = newOrder
})
// 3. Rollback bij fout
if (!result.success) {
rollbackPbis(productId, prevOrder)
toast.error('Volgorde opslaan mislukt')
}
// 3-5. Server bevestigt of niet
startTransition(async () => {
const result = await reorderPbisAction(productId, newOrder)
const st = useProductWorkspaceStore.getState()
if (result.success) {
st.settleMutation(mutationId)
} else {
st.rollbackMutation(mutationId)
toast.error('Volgorde opslaan mislukt')
}
})
}
```
## Voorbeeld — entity-patch (priority-wijziging)
```tsx
const prevPbi = store.entities.pbisById[id]
const patchMutationId = store.applyOptimisticMutation({
kind: 'entity-patch',
entity: 'pbi',
id,
prev: prevPbi,
})
useProductWorkspaceStore.setState((s) => {
const pbi = s.entities.pbisById[id]
if (pbi) pbi.priority = newPriority
})
// settle/rollback identiek aan order-flow
```
## Mutation-soorten
| `kind` | Rollback-data | Use-case |
|---|---|---|
| `pbi-order` | `prevPbiIds` | DnD reorder van PBI's |
| `story-order` | `pbiId` + `prevStoryIds` | DnD reorder van stories binnen een PBI |
| `task-order` | `storyId` + `prevTaskIds` | DnD reorder van tasks binnen een story |
| `entity-patch` | `entity` + `id` + `prev` (volledig vorig record of `undefined` voor delete-rollback) | Property-wijzigingen (priority, status), of optimistic delete/undelete |
## SSE-echo idempotent verwerken
Wanneer de server bevestigt en de NOTIFY-trigger het bijbehorende event
emitteert, mag `applyRealtimeEvent` **geen dubbele insert** veroorzaken en
**geen rollback triggeren**. INSERTs checken bestaan; UPDATEs mergen
into-existing. Zie `applyRealtimeEvent` in [`stores/product-workspace/store.ts`](../../stores/product-workspace/store.ts).

View file

@ -1,8 +1,16 @@
# Scrum4Me-Research — Zustand rearchitecture (reset + execute)
> **Scope:** dit plan is geschreven voor de research-repo
> [`madhura68/Scrum4Me-Research`](https://github.com/madhura68/Scrum4Me-Research),
> niet voor dit hoofdproject. Bestandsverwijzingen die naar
> `stores/data-store.ts`, `hooks/use-event-stream.ts`,
> `components/*-select.tsx` etc. wijzen, bestaan in de research-repo —
> niet hier. Ze staan in `code`-tags zodat de doc-link-checker ze niet
> probeert te resolven.
## Context
Het bestaande [docs/plans/zustand-store-rearchitecture.md](docs/plans/zustand-store-rearchitecture.md) beschrijft een doel-architectuur (`product-workspace-store` met genormaliseerde entities, race-safe loaders, resync-laag, optimistic mutations). De research-repo is dé plek om dat eerst te testen voordat het in `Scrum4Me/` belandt.
Het bestaande [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) beschrijft een doel-architectuur (`product-workspace-store` met genormaliseerde entities, race-safe loaders, resync-laag, optimistic mutations). De research-repo is dé plek om dat eerst te testen voordat het in `Scrum4Me/` belandt.
Probleem nu: de research-repo wijkt af van het hoofdproject. Mijn custom `data-store.ts` lijkt qua vorm op de doel-architectuur, maar springt over de baseline heen. We willen aantonen dat de migratie *vanaf* de huidige Scrum4Me-patronen werkt, niet vanaf een verzonnen tussenvorm.
@ -10,8 +18,8 @@ Dus: eerst de research-repo terugbrengen naar dezelfde stores/hooks/routes als S
## Bron-documenten
- **Doel-architectuur**: [docs/plans/zustand-store-rearchitecture.md](docs/plans/zustand-store-rearchitecture.md) (in research-repo). Dit plan voert dat document uit; herhaalt het niet.
- **Conventies**: [CLAUDE.md](../Scrum4Me/CLAUDE.md) hoofdproject. Taal NL, MD3 tokens, `@base-ui/react` render-prop, `*-server.ts`, enum UPPER_SNAKE↔lowercase via `lib/task-status.ts`.
- **Doel-architectuur**: [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) (in research-repo). Dit plan voert dat document uit; herhaalt het niet.
- **Conventies**: [CLAUDE.md](../../CLAUDE.md) hoofdproject. Taal NL, MD3 tokens, `@base-ui/react` render-prop, `*-server.ts`, enum UPPER_SNAKE↔lowercase via `lib/task-status.ts`.
## Drie-faseplan
@ -20,10 +28,10 @@ Dus: eerst de research-repo terugbrengen naar dezelfde stores/hooks/routes als S
Doel: onze research-pagina werkt op exact dezelfde store/hook/route-vorm als het hoofdproject, met identiek gedrag.
**Verwijderen** (research-repo):
- [stores/data-store.ts](stores/data-store.ts) — mijn megastore
- [hooks/use-event-stream.ts](hooks/use-event-stream.ts) — vervangen door `use-backlog-realtime.ts`
- [hooks/use-browser-presence.ts](hooks/use-browser-presence.ts) — niet in main, drop voor reset
- [app/api/realtime/events/route.ts](app/api/realtime/events/route.ts) — vervangen door `app/api/realtime/backlog/route.ts`
- `stores/data-store.ts` (research-repo) — mijn megastore
- `hooks/use-event-stream.ts` (research-repo) — vervangen door `use-backlog-realtime.ts`
- `hooks/use-browser-presence.ts` (research-repo) — niet in main, drop voor reset
- `app/api/realtime/events/route.ts` (research-repo) — vervangen door `app/api/realtime/backlog/route.ts`
- Mijn custom `loadX/resyncAll`-paden in selectie-componenten
**Kopiëren uit `/Users/janpetervisser/Development/Scrum4Me/`** (1-op-1 of stripped van auth):
@ -48,12 +56,12 @@ Doel: onze research-pagina werkt op exact dezelfde store/hook/route-vorm als het
- `GET /api/tasks/[id]`
**Componenten herschrijven**:
- [components/product-select.tsx](components/product-select.tsx) → leest `useProductsStore`, schrijft naar `useProductStore.setCurrentProduct`
- [components/pbi-select.tsx](components/pbi-select.tsx) → leest `useBacklogStore` (filter op currentProduct), `useSelectionStore.selectPbi`. Triggert fetch op product-mount via een `useBacklogLoader`-helper die initial data binnenhaalt.
- [components/story-select.tsx](components/story-select.tsx) → idem voor stories
- [components/tasks-table.tsx](components/tasks-table.tsx) → leest `tasksByStory[selectedStoryId]`. **Max 10 rijen, scrollbaar** (al ingebouwd, behouden)
- [components/task-detail-card.tsx](components/task-detail-card.tsx) → fetcht task detail apart (geen full-fat backlog veld; matcht main's `tasks/[id]` route)
- [components/event-stream-panel.tsx](components/event-stream-panel.tsx) → blijft bestaan voor research-doel (event-tap), maar luistert nu mee op dezelfde EventSource via `use-backlog-realtime` (of een tweede readonly listener); selecteerbare events met JSON-detail rechts blijven. Twee checkboxes (Postgres / Browser). Truncate met ellipsis in de lijst.
- `components/product-select.tsx` (research-repo) → leest `useProductsStore`, schrijft naar `useProductStore.setCurrentProduct`
- `components/pbi-select.tsx` (research-repo) → leest `useBacklogStore` (filter op currentProduct), `useSelectionStore.selectPbi`. Triggert fetch op product-mount via een `useBacklogLoader`-helper die initial data binnenhaalt.
- `components/story-select.tsx` (research-repo) → idem voor stories
- `components/tasks-table.tsx` (research-repo) → leest `tasksByStory[selectedStoryId]`. **Max 10 rijen, scrollbaar** (al ingebouwd, behouden)
- `components/task-detail-card.tsx` (research-repo) → fetcht task detail apart (geen full-fat backlog veld; matcht main's `tasks/[id]` route)
- `components/event-stream-panel.tsx` (research-repo) → blijft bestaan voor research-doel (event-tap), maar luistert nu mee op dezelfde EventSource via `use-backlog-realtime` (of een tweede readonly listener); selecteerbare events met JSON-detail rechts blijven. Twee checkboxes (Postgres / Browser). Truncate met ellipsis in de lijst.
**Werkwijzen (verifiëren tijdens reset)**:
- Comments en UI-tekst NL
@ -69,7 +77,7 @@ Doel: onze research-pagina werkt op exact dezelfde store/hook/route-vorm als het
### Fase B — Rearchitecture uitvoeren
Volgt de 15 stappen uit [docs/plans/zustand-store-rearchitecture.md](docs/plans/zustand-store-rearchitecture.md) §Implementatiepad. Concreet voor de research-repo:
Volgt de 15 stappen uit [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) §Implementatiepad. Concreet voor de research-repo:
1. **Map** `stores/product-workspace/` aanmaken (factory + provider + selectors).
2. **`activeProduct`** wordt nu nog gespiegeld vanuit `useProductStore`; voor de research-pagina geen layout/server-side bepaling — we lezen het uit de pulldown-state.
@ -134,10 +142,10 @@ Volgt de 15 stappen uit [docs/plans/zustand-store-rearchitecture.md](docs/plans/
## Bestandsmutaties (overzicht)
### Verwijderen na Fase A
- [stores/data-store.ts](stores/data-store.ts)
- [hooks/use-event-stream.ts](hooks/use-event-stream.ts)
- [hooks/use-browser-presence.ts](hooks/use-browser-presence.ts) — komt deels terug in Fase B als helper voor visibility/online resync trigger
- [app/api/realtime/events/route.ts](app/api/realtime/events/route.ts)
- `stores/data-store.ts` (research-repo)
- `hooks/use-event-stream.ts` (research-repo)
- `hooks/use-browser-presence.ts` (research-repo) — komt deels terug in Fase B als helper voor visibility/online resync trigger
- `app/api/realtime/events/route.ts` (research-repo)
### Toevoegen Fase A (uit Scrum4Me)
- `stores/backlog-store.ts`
@ -174,7 +182,7 @@ Volgt de 15 stappen uit [docs/plans/zustand-store-rearchitecture.md](docs/plans/
6. Vergelijk: `diff Scrum4Me/stores/backlog-store.ts Scrum4Me-Research/stores/backlog-store.ts` → identiek (modulo lokale interface-uitbreidingen waar gedocumenteerd)
### Na Fase B (target)
Alle acceptatiecriteria uit [docs/plans/zustand-store-rearchitecture.md §Acceptatiecriteria](docs/plans/zustand-store-rearchitecture.md):
Alle acceptatiecriteria uit [zustand-store-rearchitecture.md §Acceptatiecriteria](./zustand-store-rearchitecture.md):
- Eén waarheid per entity in de store ✓
- Selectors als enige UI-leesweg ✓
- SSE patcht zonder full-page refresh ✓

View file

@ -0,0 +1,177 @@
---
title: "Zustand workspace-store implementatieplan (PBI-74)"
status: ready-to-execute
audience: [maintainer, contributor, ai-agent]
language: nl
last_updated: 2026-05-09
revision: 1
---
# Zustand workspace-store implementatieplan
PBI in Scrum4Me-MCP: **PBI-74**_Zustand store rearchitecture — product- en sprint-workspace_.
Bron-ontwerp (architectuur en gotchas): [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) revisie 3.
Dit document koppelt de stories en taken in MCP aan de implementatie. Per story acceptatiecriteria; per taak een concrete deliverable. Alle items staan in MCP op `OPEN`/`TO_DO`. Geen executie tot expliciete trigger ("voer Story 1 uit").
## Context
De client-state ligt over vier los gegroeide stores: `backlog-store`, `planner-store`, `selection-store`, `product-store`. Vier zwakheden:
- SSE sluit op tab `hidden` zonder resync bij `visible` — gemiste events blijven gemist.
- Geen reconcile bij reconnect (Postgres NOTIFY heeft geen replay).
- Onbekende entity-events worden stil genegeerd.
- LocalStorage soms behandeld als waarheid i.p.v. restore-hint.
- Geen race-safe loaders — trage fetch van oude selectie kan nieuwste overschrijven.
De rearchitecture lost dit op via één `product-workspace-store` (en analoog `sprint-workspace-store`) met genormaliseerde entity-maps, race-safe `ensure*Loaded` met `activeRequestId`-guard, expliciete resync-laag (visible/reconnect/unknown-event), idempotente SSE-application en localStorage als pure restore-hint.
## Aanpak
- Eén PBI ([PBI-74](./zustand-store-rearchitecture.md)).
- Negen stories die mappen op de stappen 1-9 in het bron-ontwerp.
- Granulariteit Story 3 = één story met taken per component.
- Story 5 in één PR (visibility-handling + resync horen samen).
- Per story: PR, `npm run verify && npm run build` groen, status DONE pas na merge.
- Branch: `feat/zustand-workspace-store` (één branch voor alle stories).
## Stories en taken
| # | Story | MCP | Taken |
|---|---|---|---|
| 1 | Skelet + test-infrastructuur | [ST-1318](./zustand-store-rearchitecture.md) | T-837 … T-843 (7) |
| 2 | Hydratie overstappen (parallel-running) | ST-1319 | T-844 … T-847 (4) |
| 3 | Componenten omzetten naar workspace-store | ST-1320 | T-848 … T-855 (8) |
| 4 | Race-safe loaders en restore-hints | ST-1321 | T-856 … T-860 (5) |
| 5 | Hidden-tab + reconnect resync (één PR) | ST-1322 | T-861 … T-864 (4) |
| 6 | Unknown-event fallback | ST-1323 | T-865 … T-867 (3) |
| 7 | Cache-headers en read-routes | ST-1324 | T-868 … T-871 (4) |
| 8 | Oude stores opruimen | ST-1325 | T-872 … T-878 (7) |
| 9 | Sprint-workspace-store | ST-1326 | T-879 … T-884 (6) |
Totaal: 48 taken.
### Story 1 — Skelet + test-infrastructuur
**Doel:** nieuwe store + selectors + restore-utils met volledige unit-test-suite, nog zonder UI-consumenten.
**Belangrijkste taken:**
- T-837 — Vitest naar jsdom + `tests/setup.ts` met MemoryStorage (G6).
- T-838/839/840/841 — `stores/product-workspace/{types,store,selectors,restore}.ts`.
- T-842 — Volledige test-suite per §Testing setup-checklist (G5/G7/G8).
- T-843 — API endpoint-audit voor `ensure*Loaded` URLs.
**Acceptatie:** alle test-cases groen, geen UI-impact.
### Story 2 — Hydratie overstappen
**Doel:** `BacklogHydrationWrapper` en `useBacklogRealtime` voeden zowel oude store als nieuwe store. Componenten lezen nog uit oude.
**Taken:** T-844 (wrapper dual-dispatch), T-845 (realtime dual-dispatch), T-846 (dev-only fingerprint verifyer), T-847 (productpicker → setActiveProduct).
**Acceptatie:** schaduw-store inhoud matcht oude store na elk SSE-event.
### Story 3 — Componenten omzetten
**Doel:** componenten lezen uit nieuwe workspace-store; oude stores hebben geen UI-consumenten meer.
**Taken per component:** T-848 (split-pane), T-849 (pbi-list), T-850 (story-panel), T-851 (task-panel), T-852 (start-sprint-button), T-853 (set-current-product). Plus T-854 (G1/G2-audit) en T-855 (integration-tests bijwerken).
**Acceptatie:** geen "Maximum update depth" warnings; oude store-imports alleen nog in tests die in Story 8 verdwijnen.
### Story 4 — Race-safe loaders en restore-hints
**Doel:** `ensure*Loaded` met `activeRequestId`-guard; localStorage hints met validatie.
**Taken:** T-856 (guard), T-857 (restore-flow met await ensure-chain), T-858 (hint-persistentie), T-859 (URL-prioriteit), T-860 (race-safety tests).
**Acceptatie:** trage fetch + her-selectie corrumpeert nooit; cold reload restoret zonder fout.
### Story 5 — Hidden-tab + reconnect resync (één PR)
**Doel:** SSE blijft open op hidden; resync via expliciete laag.
**Taken:** T-861 (geen close op hidden), T-862 (ready-event triggert resync na reconnect), T-863 (`useWorkspaceResync` hook), T-864 (tests).
**Acceptatie:** hidden→visible en reconnect herstellen gemiste wijzigingen in één cyclus.
### Story 6 — Unknown-event fallback
**Doel:** onbekende entity-events triggeren resync; job/worker noise wordt genegeerd.
**Taken:** T-865 (`isUnknownEntityEvent` filter), T-866 (resync-trigger), T-867 (negatieve filter-tests).
**Acceptatie:** directe DB UPDATE zonder herkenbare delta-event wordt zichtbaar binnen één resync; job-events triggeren geen resync.
### Story 7 — Cache-headers en read-routes
**Doel:** geen stale data uit Next/browser cache.
**Taken:** T-868 (`cache: 'no-store'`), T-869 (`force-dynamic` audit), T-870 (LIST-endpoints toevoegen waar nodig), T-871 (SSE-route ready-event coverage).
**Acceptatie:** response headers in productie tonen `cache-control: no-store`; LIST-endpoints bestaan voor alle `ensure*Loaded`.
### Story 8 — Oude stores opruimen
**Doel:** vier oude stores verwijderd.
**Taken:** T-872 (grep), T-873/874/875/876 (delete vier files), T-877 (oude tests migreren), T-878 (`stores/products-store.ts` blijft + dev-fingerprint cleanup).
**Acceptatie:** grep `useBacklogStore|usePlannerStore|useSelectionStore|useProductStore` = 0; `npm run verify && npm run build` groen.
### Story 9 — Sprint-workspace-store
**Doel:** zelfde patroon op sprint-workflow toegepast.
**Taken:** T-879 (skelet), T-880 (hydratie+realtime), T-881 (componenten), T-882 (race-safe + restore + resync + unknown-event in één keer), T-883 (cleanup oude sprint-state), T-884 (E2E sprint-board verificatie).
> **Aanbeveling per ontwerpdoc:** start Story 9 pas nadat product-workspace enkele weken stabiel in productie staat. PBI-74 sluit pas wanneer Story 9 ook merged is.
## Critical files
**Te wijzigen:**
- `vitest.config.ts` — env naar jsdom, setupFiles
- nieuw: `tests/setup.ts` — MemoryStorage, restoreAllMocks
- nieuw: `stores/product-workspace/{types,store,selectors,restore}.ts`
- nieuw: `stores/sprint-workspace/{types,store,selectors,restore}.ts`
- nieuw: `lib/realtime/use-workspace-resync.ts`
- `components/backlog/backlog-hydration-wrapper.tsx`
- `lib/realtime/use-backlog-realtime.ts`
- `components/backlog/backlog-split-pane.tsx`, `pbi-list.tsx`, `story-panel.tsx`, `task-panel.tsx`
- `components/.../start-sprint-button.tsx`, `set-current-product.tsx`
- read-routes onder `app/api/...` voor PBI/story/task LIST + detail
- te verwijderen in Story 8: `stores/{backlog,planner,selection,product}-store.ts`
**Te hergebruiken (geen wijziging):**
- `lib/product-access.ts``getAccessibleProduct`, blijft auth/access-bron
- `app/api/realtime/backlog/route.ts``ready`-event al aanwezig
- `docs/patterns/realtime-notify-payload.md` — payload-contract
- `docs/patterns/route-handler.md` — REST patroon
- `stores/products-store.ts`, `stores/solo-store.ts`, `stores/notifications-store.ts`, `stores/idea-store.ts`, `stores/jobs-store.ts` — blijven ongewijzigd
## Verificatie per story
- **Story 1:** Vitest groen voor alle test-cases (hydrate, cascade, realtime, ensureLoaded race, resync, restore-hints, optimistic mutation).
- **Story 2:** dev-server, productpagina, fingerprint match in console.
- **Story 3:** klik door 3 panels, DnD test, geen "Maximum update depth"-warnings.
- **Story 4:** staging — cold reload, throttle fetch + her-selecteer.
- **Story 5:** tab hidden > 30s + terug → resync zichtbaar; netwerk uit/aan → reconnect+resync.
- **Story 6:** DB UPDATE op story zonder delta-event → zichtbaar binnen 1 resync; job-events negeren resync.
- **Story 7:** response headers `cache-control: no-store`; tweede pageload toont verse data.
- **Story 8:** grep oude store-imports = 0; `npm run verify && npm run build` groen.
- **Story 9:** sprint-board flow analoog Story 1-8 verifications.
**Eind-acceptatie PBI-74:** alle items uit §Acceptatiecriteria van [zustand-store-rearchitecture.md](./zustand-store-rearchitecture.md) (regels 727-746) behaald.
## Workflow per story
1. `git checkout -b feat/zustand-workspace-store` (eerste story); blijf op deze branch tot expliciete cut.
2. `mcp__scrum4me__get_claude_context` → pak next story uit PBI-74.
3. Voer taken uit in `sort_order`; update status per taak via `mcp__scrum4me__update_task_status`.
4. Lees relevante bestanden + patronen vóór begin (zie §Critical files).
5. `npm run verify && npm run build` per laag.
6. Commit per laag (`git add -A && git commit`); geen push tussendoor.
7. Story-status sluit zodra alle taken `DONE`.
8. Lege story-queue → `git push -u origin feat/zustand-workspace-store` + `gh pr create`.
9. Per story een eigen PR; merge één voor één.

View file

@ -1,11 +1,19 @@
'use client'
// ST-1115: Client hook for the backlog 3-pane SSE stream.
// ST-1115 / PBI-74: Client hook for the backlog 3-pane SSE stream.
// Mounts in BacklogHydrationWrapper so it survives Server Action refreshes.
// Dispatches pbi/story/task change events into useBacklogStore.applyChange.
// Dispatches pbi/story/task change events into useProductWorkspaceStore.
//
// T-861: stream blijft open op tab hidden. Per spec werkt EventSource gewoon
// door als de browser het toelaat — gemiste events worden opgehaald via
// resyncActiveScopes('visible') uit useWorkspaceResync.
// T-862: bij latere 'ready' events (post-reconnect) triggeren we
// resyncActiveScopes('reconnect') zodat events die tijdens disconnect zijn
// gemist, alsnog binnenkomen.
import { useEffect, useRef } from 'react'
import { useBacklogStore } from '@/stores/backlog-store'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
import type { ProductRealtimeEvent } from '@/stores/product-workspace/types'
const BACKOFF_START_MS = 1_000
const BACKOFF_MAX_MS = 30_000
@ -20,6 +28,7 @@ export function useBacklogRealtime(productId: string | null) {
const sourceRef = useRef<EventSource | null>(null)
const backoffRef = useRef<number>(BACKOFF_START_MS)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const readyCountRef = useRef<number>(0)
useEffect(() => {
if (!productId) return
@ -44,15 +53,22 @@ export function useBacklogRealtime(productId: string | null) {
source.addEventListener('ready', () => {
backoffRef.current = BACKOFF_START_MS
readyCountRef.current += 1
// T-862: eerste ready = initial connect; latere ready = reconnect.
if (readyCountRef.current > 1) {
void useProductWorkspaceStore
.getState()
.resyncActiveScopes('reconnect')
}
})
source.onmessage = (e) => {
if (!e.data) return
try {
const payload = JSON.parse(e.data) as EntityPayload
useBacklogStore
useProductWorkspaceStore
.getState()
.applyChange(payload.entity, payload.op, payload as Record<string, unknown>)
.applyRealtimeEvent(payload as unknown as ProductRealtimeEvent)
} catch (err) {
if (process.env.NODE_ENV !== 'production') {
console.error('[realtime/backlog] failed to parse event', err, e.data)
@ -70,23 +86,22 @@ export function useBacklogRealtime(productId: string | null) {
}
}
// T-861: stream blijft open op hidden. Reconnect alleen als source weg
// is (b.v. na netwerkfout) en de tab visible is.
const onVisibility = () => {
if (document.visibilityState === 'hidden') {
close()
} else if (sourceRef.current === null) {
if (document.visibilityState === 'visible' && sourceRef.current === null) {
backoffRef.current = BACKOFF_START_MS
connect()
}
}
if (document.visibilityState === 'visible') {
connect()
}
connect()
document.addEventListener('visibilitychange', onVisibility)
return () => {
document.removeEventListener('visibilitychange', onVisibility)
close()
readyCountRef.current = 0
}
}, [productId])
}

View file

@ -191,21 +191,30 @@ export function useNotificationsRealtime() {
})
}
// PBI-74: stream blijft open op hidden. Reconnect alleen als hij door
// netwerkfout/server-close weg is. Bij visible-overgang en bij online
// triggeren we router.refresh() zodat de notifications-bel verse state
// pakt — gemiste vraag-events via NOTIFY-throttling worden hierdoor
// alsnog zichtbaar.
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') {
if (!sourceRef.current || sourceRef.current.readyState === EventSource.CLOSED) {
connect()
}
} else {
close()
if (document.visibilityState !== 'visible') return
if (!sourceRef.current || sourceRef.current.readyState === EventSource.CLOSED) {
connect()
}
router.refresh()
}
const onOnline = () => {
router.refresh()
}
connect()
document.addEventListener('visibilitychange', onVisibilityChange)
window.addEventListener('online', onOnline)
return () => {
document.removeEventListener('visibilitychange', onVisibilityChange)
window.removeEventListener('online', onOnline)
close()
}
}, [router])

View file

@ -6,7 +6,12 @@
// - Opent EventSource('/api/realtime/solo?product_id=...') wanneer
// productId niet null is; sluit de stream als productId null wordt.
// - Reconnect met exponential backoff (1s → 30s, reset bij ready).
// - Pauseert bij document.visibilityState === 'hidden', resumes bij visible.
// - PBI-74: stream blijft open op tab hidden (geen close meer). Bij
// hidden→visible en bij window 'online' triggeren we router.refresh()
// zodat gemiste events alsnog binnenkomen via een verse server-render
// (re-fetcht initialTasks → initTasks reset solo-store). Postgres NOTIFY
// heeft geen replay, dus zonder deze resync zouden hidden-tab events
// permanent verloren zijn — zelfde fix als Story 5 voor backlog-realtime.
// - Cleanup op unmount.
// - Connection-status (status, showConnectingIndicator) wordt naar de
// solo-store geschreven; UI-componenten lezen daar uit.
@ -19,6 +24,7 @@
import { useEffect, useRef } from 'react'
import { flushSync } from 'react-dom'
import { useRouter } from 'next/navigation'
import { useSoloStore } from '@/stores/solo-store'
import type { ClaudeJobEvent, JobState, RealtimeEvent, RealtimeStatus } from '@/stores/solo-store'
@ -27,10 +33,12 @@ const BACKOFF_MAX_MS = 30_000
const CONNECTING_INDICATOR_DELAY_MS = 4_000
export function useSoloRealtime(productId: string | null) {
const router = useRouter()
const sourceRef = useRef<EventSource | null>(null)
const backoffRef = useRef<number>(BACKOFF_START_MS)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const indicatorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const readyCountRef = useRef<number>(0)
useEffect(() => {
const setStatus = useSoloStore.getState().setRealtimeStatus
@ -88,6 +96,12 @@ export function useSoloRealtime(productId: string | null) {
source.addEventListener('ready', () => {
backoffRef.current = BACKOFF_START_MS
scheduleIndicator('open')
readyCountRef.current += 1
// PBI-74: latere ready = post-reconnect → resync via router.refresh()
// zodat gemiste tasks-state via re-render initial-prop binnenkomt.
if (readyCountRef.current > 1) {
router.refresh()
}
})
source.addEventListener('claude_jobs_initial', (e) => {
@ -173,25 +187,33 @@ export function useSoloRealtime(productId: string | null) {
}
}
// PBI-74: stream blijft open op hidden. Reconnect alleen als de stream
// door netwerkfout/server-close weg is en de tab visible is. Bij iedere
// visible-overgang triggeren we router.refresh() — gemiste events tijdens
// throttling/freeze worden via een verse server-render alsnog opgepakt.
const onVisibility = () => {
if (document.visibilityState === 'hidden') {
close()
scheduleIndicator('disconnected')
} else if (sourceRef.current === null) {
if (document.visibilityState !== 'visible') return
if (sourceRef.current === null) {
backoffRef.current = BACKOFF_START_MS
connect()
}
router.refresh()
}
if (document.visibilityState === 'visible') {
connect()
const onOnline = () => {
router.refresh()
}
connect()
document.addEventListener('visibilitychange', onVisibility)
window.addEventListener('online', onOnline)
return () => {
document.removeEventListener('visibilitychange', onVisibility)
window.removeEventListener('online', onOnline)
if (indicatorTimerRef.current) clearTimeout(indicatorTimerRef.current)
close()
readyCountRef.current = 0
}
}, [productId])
}, [productId, router])
}

View file

@ -0,0 +1,40 @@
'use client'
// PBI-74 / T-863: useWorkspaceResync hook.
//
// Trigger resyncActiveScopes bij:
// - hidden→visible (browser-throttled events kunnen gemist zijn)
// - online (netwerk hersteld na disconnect)
//
// Hoort gemount te worden naast useBacklogRealtime in BacklogHydrationWrapper.
import { useEffect } from 'react'
import { useProductWorkspaceStore } from '@/stores/product-workspace/store'
export function useWorkspaceResync(): void {
useEffect(() => {
if (typeof document === 'undefined') return
const onVisibility = () => {
if (document.visibilityState === 'visible') {
void useProductWorkspaceStore
.getState()
.resyncActiveScopes('visible')
}
}
const onOnline = () => {
void useProductWorkspaceStore
.getState()
.resyncActiveScopes('reconnect')
}
document.addEventListener('visibilitychange', onVisibility)
window.addEventListener('online', onOnline)
return () => {
document.removeEventListener('visibilitychange', onVisibility)
window.removeEventListener('online', onOnline)
}
}, [])
}

View file

@ -1,143 +0,0 @@
import { create } from 'zustand'
import type { PbiStatusApi } from '@/lib/task-status'
export interface BacklogPbi {
id: string
code: string | null
title: string
priority: number
description?: string | null
created_at: Date
status: PbiStatusApi
}
export interface BacklogStory {
id: string
code: string | null
title: string
description: string | null
acceptance_criteria: string | null
priority: number
status: string
pbi_id: string
sprint_id: string | null
created_at: Date
}
export interface BacklogTask {
id: string
title: string
description: string | null
priority: number
status: string
sort_order: number
story_id: string
created_at: Date
}
type Entity = 'pbi' | 'story' | 'task'
type Op = 'I' | 'U' | 'D'
interface InitialData {
pbis: BacklogPbi[]
storiesByPbi: Record<string, BacklogStory[]>
tasksByStory: Record<string, BacklogTask[]>
}
interface BacklogStore extends InitialData {
setInitialData: (data: InitialData) => void
applyChange: (entity: Entity, op: Op, data: Record<string, unknown>) => void
}
export const useBacklogStore = create<BacklogStore>((set) => ({
pbis: [],
storiesByPbi: {},
tasksByStory: {},
setInitialData: (data) => set(data),
applyChange: (entity, op, data) =>
set((state) => {
if (entity === 'pbi') {
const id = data.id as string
if (op === 'D') {
return { pbis: state.pbis.filter((p) => p.id !== id) }
}
if (op === 'U') {
return {
pbis: state.pbis.map((p) =>
p.id === id ? { ...p, ...(data as Partial<BacklogPbi>) } : p
),
}
}
// I — idempotent: skip if already present (optimistic update may have arrived first)
if (state.pbis.some((p) => p.id === id)) return {}
return { pbis: [...state.pbis, data as unknown as BacklogPbi] }
}
if (entity === 'story') {
const id = data.id as string
if (op === 'D') {
const storiesByPbi = { ...state.storiesByPbi }
for (const pbiId of Object.keys(storiesByPbi)) {
storiesByPbi[pbiId] = storiesByPbi[pbiId].filter((s) => s.id !== id)
}
return { storiesByPbi }
}
if (op === 'U') {
const storiesByPbi = { ...state.storiesByPbi }
for (const pbiId of Object.keys(storiesByPbi)) {
const idx = storiesByPbi[pbiId].findIndex((s) => s.id === id)
if (idx !== -1) {
storiesByPbi[pbiId] = storiesByPbi[pbiId].map((s) =>
s.id === id ? { ...s, ...(data as Partial<BacklogStory>) } : s
)
break
}
}
return { storiesByPbi }
}
// I — idempotent: skip if already present
const pbiId = data.pbi_id as string
if ((state.storiesByPbi[pbiId] ?? []).some((s) => s.id === id)) return {}
return {
storiesByPbi: {
...state.storiesByPbi,
[pbiId]: [...(state.storiesByPbi[pbiId] ?? []), data as unknown as BacklogStory],
},
}
}
// task
const id = data.id as string
if (op === 'D') {
const tasksByStory = { ...state.tasksByStory }
for (const storyId of Object.keys(tasksByStory)) {
tasksByStory[storyId] = tasksByStory[storyId].filter((t) => t.id !== id)
}
return { tasksByStory }
}
if (op === 'U') {
const tasksByStory = { ...state.tasksByStory }
for (const storyId of Object.keys(tasksByStory)) {
const idx = tasksByStory[storyId].findIndex((t) => t.id === id)
if (idx !== -1) {
tasksByStory[storyId] = tasksByStory[storyId].map((t) =>
t.id === id ? { ...t, ...(data as Partial<BacklogTask>) } : t
)
break
}
}
return { tasksByStory }
}
// I — idempotent: skip if already present
const storyId = data.story_id as string
if ((state.tasksByStory[storyId] ?? []).some((t) => t.id === id)) return {}
return {
tasksByStory: {
...state.tasksByStory,
[storyId]: [...(state.tasksByStory[storyId] ?? []), data as unknown as BacklogTask],
},
}
}),
}))

View file

@ -1,46 +0,0 @@
import { create } from 'zustand'
interface PlannerStore {
// Order maps: productId → pbiId[]
pbiOrder: Record<string, string[]>
// Order maps: pbiId → storyId[]
storyOrder: Record<string, string[]>
// Priority maps: pbiId → priority
pbiPriority: Record<string, number>
initPbis: (productId: string, ids: string[]) => void
reorderPbis: (productId: string, ids: string[]) => void
rollbackPbis: (productId: string, ids: string[]) => void
updatePbiPriority: (pbiId: string, priority: number) => void
initStories: (pbiId: string, ids: string[]) => void
reorderStories: (pbiId: string, ids: string[]) => void
rollbackStories: (pbiId: string, ids: string[]) => void
}
export const usePlannerStore = create<PlannerStore>((set) => ({
pbiOrder: {},
storyOrder: {},
pbiPriority: {},
initPbis: (productId, ids) =>
set((state) => ({ pbiOrder: { ...state.pbiOrder, [productId]: ids } })),
reorderPbis: (productId, ids) =>
set((state) => ({ pbiOrder: { ...state.pbiOrder, [productId]: ids } })),
rollbackPbis: (productId, ids) =>
set((state) => ({ pbiOrder: { ...state.pbiOrder, [productId]: ids } })),
updatePbiPriority: (pbiId, priority) =>
set((state) => ({ pbiPriority: { ...state.pbiPriority, [pbiId]: priority } })),
initStories: (pbiId, ids) =>
set((state) => ({ storyOrder: { ...state.storyOrder, [pbiId]: ids } })),
reorderStories: (pbiId, ids) =>
set((state) => ({ storyOrder: { ...state.storyOrder, [pbiId]: ids } })),
rollbackStories: (pbiId, ids) =>
set((state) => ({ storyOrder: { ...state.storyOrder, [pbiId]: ids } })),
}))

View file

@ -1,13 +0,0 @@
import { create } from 'zustand'
interface ProductStore {
currentProduct: { id: string; name: string } | null
setCurrentProduct: (id: string, name: string) => void
clearCurrentProduct: () => void
}
export const useProductStore = create<ProductStore>((set) => ({
currentProduct: null,
setCurrentProduct: (id, name) => set({ currentProduct: { id, name } }),
clearCurrentProduct: () => set({ currentProduct: null }),
}))

View file

@ -0,0 +1,110 @@
const STORAGE_KEY = 'product-workspace-hints'
interface PerProductHint {
lastActivePbiId?: string | null
lastActiveStoryId?: string | null
lastActiveTaskId?: string | null
}
export interface WorkspaceHints {
lastActiveProductId: string | null
perProduct: Record<string, PerProductHint>
}
const EMPTY_HINTS: WorkspaceHints = {
lastActiveProductId: null,
perProduct: {},
}
function safeStorage(): Storage | null {
if (typeof globalThis === 'undefined') return null
try {
const ls = (globalThis as { localStorage?: Storage }).localStorage
return ls ?? null
} catch {
return null
}
}
export function readHints(): WorkspaceHints {
const storage = safeStorage()
if (!storage) return { ...EMPTY_HINTS, perProduct: {} }
try {
const raw = storage.getItem(STORAGE_KEY)
if (!raw) return { ...EMPTY_HINTS, perProduct: {} }
const parsed = JSON.parse(raw) as Partial<WorkspaceHints> | null
if (!parsed || typeof parsed !== 'object') {
return { ...EMPTY_HINTS, perProduct: {} }
}
return {
lastActiveProductId: parsed.lastActiveProductId ?? null,
perProduct:
parsed.perProduct && typeof parsed.perProduct === 'object'
? parsed.perProduct
: {},
}
} catch {
return { ...EMPTY_HINTS, perProduct: {} }
}
}
function writeHints(hints: WorkspaceHints): void {
const storage = safeStorage()
if (!storage) return
try {
storage.setItem(STORAGE_KEY, JSON.stringify(hints))
} catch {
// ignore quota or serialization errors
}
}
export function writeProductHint(productId: string | null): void {
const hints = readHints()
hints.lastActiveProductId = productId
writeHints(hints)
}
function ensurePerProduct(hints: WorkspaceHints, productId: string): PerProductHint {
if (!hints.perProduct[productId]) {
hints.perProduct[productId] = {}
}
return hints.perProduct[productId]
}
export function writePbiHint(productId: string, pbiId: string | null): void {
const hints = readHints()
const entry = ensurePerProduct(hints, productId)
entry.lastActivePbiId = pbiId
if (pbiId === null) {
entry.lastActiveStoryId = null
entry.lastActiveTaskId = null
}
writeHints(hints)
}
export function writeStoryHint(productId: string, storyId: string | null): void {
const hints = readHints()
const entry = ensurePerProduct(hints, productId)
entry.lastActiveStoryId = storyId
if (storyId === null) {
entry.lastActiveTaskId = null
}
writeHints(hints)
}
export function writeTaskHint(productId: string, taskId: string | null): void {
const hints = readHints()
const entry = ensurePerProduct(hints, productId)
entry.lastActiveTaskId = taskId
writeHints(hints)
}
export function clearHints(): void {
const storage = safeStorage()
if (!storage) return
try {
storage.removeItem(STORAGE_KEY)
} catch {
// ignore
}
}

View file

@ -0,0 +1,102 @@
import type { ProductWorkspaceStore } from './store'
import type { BacklogPbi, BacklogStory, BacklogTask, TaskDetail } from './types'
// G1: stable EMPTY-references zodat selectors geen nieuwe array per call retourneren.
const EMPTY_PBIS: BacklogPbi[] = []
const EMPTY_STORIES: BacklogStory[] = []
const EMPTY_TASKS: (BacklogTask | TaskDetail)[] = []
/**
* Lijst-selector. Vereist `useShallow` in componenten (G2) anders re-rendert
* elke ongerelateerde store-mutatie het component.
*/
export function selectVisiblePbis(s: ProductWorkspaceStore): BacklogPbi[] {
if (s.relations.pbiIds.length === 0) return EMPTY_PBIS
const out: BacklogPbi[] = []
for (const id of s.relations.pbiIds) {
const pbi = s.entities.pbisById[id]
if (pbi) out.push(pbi)
}
return out.length === 0 ? EMPTY_PBIS : out
}
/**
* Lijst-selector. Vereist `useShallow` in componenten (G2).
*/
export function selectStoriesForActivePbi(s: ProductWorkspaceStore): BacklogStory[] {
const pbiId = s.context.activePbiId
if (!pbiId) return EMPTY_STORIES
const ids = s.relations.storyIdsByPbi[pbiId]
if (!ids || ids.length === 0) return EMPTY_STORIES
const out: BacklogStory[] = []
for (const id of ids) {
const story = s.entities.storiesById[id]
if (story) out.push(story)
}
return out.length === 0 ? EMPTY_STORIES : out
}
/**
* Lijst-selector. Vereist `useShallow` in componenten (G2).
*/
export function selectTasksForActiveStory(
s: ProductWorkspaceStore,
): (BacklogTask | TaskDetail)[] {
const storyId = s.context.activeStoryId
if (!storyId) return EMPTY_TASKS
const ids = s.relations.taskIdsByStory[storyId]
if (!ids || ids.length === 0) return EMPTY_TASKS
const out: (BacklogTask | TaskDetail)[] = []
for (const id of ids) {
const task = s.entities.tasksById[id]
if (task) out.push(task)
}
return out.length === 0 ? EMPTY_TASKS : out
}
/**
* Single-value selector. `useShallow` niet vereist retourneert stable
* entity-reference (zelfde object zolang entity ongewijzigd).
*/
export function selectActivePbi(s: ProductWorkspaceStore): BacklogPbi | null {
const id = s.context.activePbiId
if (!id) return null
return s.entities.pbisById[id] ?? null
}
/**
* Single-value selector. `useShallow` niet vereist.
*/
export function selectActiveStory(s: ProductWorkspaceStore): BacklogStory | null {
const id = s.context.activeStoryId
if (!id) return null
return s.entities.storiesById[id] ?? null
}
/**
* Single-value selector. `useShallow` niet vereist.
*/
export function selectActiveTask(
s: ProductWorkspaceStore,
): BacklogTask | TaskDetail | null {
const id = s.context.activeTaskId
if (!id) return null
return s.entities.tasksById[id] ?? null
}
/**
* Single-value selector voor stories binnen een specifiek PBI (niet per se actief).
*/
export function selectStoriesForPbi(
s: ProductWorkspaceStore,
pbiId: string,
): BacklogStory[] {
const ids = s.relations.storyIdsByPbi[pbiId]
if (!ids || ids.length === 0) return EMPTY_STORIES
const out: BacklogStory[] = []
for (const id of ids) {
const story = s.entities.storiesById[id]
if (story) out.push(story)
}
return out.length === 0 ? EMPTY_STORIES : out
}

View file

@ -0,0 +1,841 @@
import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import {
isDetail,
type ActiveProduct,
type BacklogPbi,
type BacklogStory,
type BacklogTask,
type OptimisticMutation,
type PendingOptimisticMutation,
type ProductBacklogSnapshot,
type ProductRealtimeEvent,
type RealtimeStatus,
type ResyncReason,
type TaskDetail,
} from './types'
import {
readHints,
writePbiHint,
writeProductHint,
writeStoryHint,
writeTaskHint,
} from './restore'
interface ContextSlice {
activeProduct: ActiveProduct | null
activePbiId: string | null
activeStoryId: string | null
activeTaskId: string | null
}
interface EntitiesSlice {
pbisById: Record<string, BacklogPbi>
storiesById: Record<string, BacklogStory>
tasksById: Record<string, BacklogTask | TaskDetail>
}
interface RelationsSlice {
pbiIds: string[]
storyIdsByPbi: Record<string, string[]>
taskIdsByStory: Record<string, string[]>
}
interface LoadingSlice {
loadedProductId: string | null
loadingProductId: string | null
loadedPbiIds: Record<string, true>
loadedStoryIds: Record<string, true>
loadedTaskIds: Record<string, true>
activeRequestId: string | null
}
interface SyncSlice {
realtimeStatus: RealtimeStatus
lastEventAt: number | null
lastResyncAt: number | null
resyncReason: ResyncReason | null
}
interface State {
context: ContextSlice
entities: EntitiesSlice
relations: RelationsSlice
loading: LoadingSlice
sync: SyncSlice
pendingMutations: Record<string, PendingOptimisticMutation>
}
interface Actions {
hydrateSnapshot(snapshot: ProductBacklogSnapshot): void
setActiveProduct(product: ActiveProduct | null): void
setActivePbi(pbiId: string | null): void
setActiveStory(storyId: string | null): void
setActiveTask(taskId: string | null): void
ensureProductLoaded(productId: string, requestId?: string): Promise<void>
ensurePbiLoaded(pbiId: string, requestId?: string): Promise<void>
ensureStoryLoaded(storyId: string, requestId?: string): Promise<void>
ensureTaskLoaded(taskId: string, requestId?: string): Promise<void>
applyRealtimeEvent(event: ProductRealtimeEvent | Record<string, unknown>): void
resyncActiveScopes(reason: ResyncReason): Promise<void>
resyncLoadedScopes(reason: ResyncReason): Promise<void>
applyOptimisticMutation(mutation: OptimisticMutation): string
rollbackMutation(mutationId: string): void
settleMutation(mutationId: string): void
setRealtimeStatus(status: RealtimeStatus): void
}
export type ProductWorkspaceStore = State & Actions
const initialState: State = {
context: {
activeProduct: null,
activePbiId: null,
activeStoryId: null,
activeTaskId: null,
},
entities: {
pbisById: {},
storiesById: {},
tasksById: {},
},
relations: {
pbiIds: [],
storyIdsByPbi: {},
taskIdsByStory: {},
},
loading: {
loadedProductId: null,
loadingProductId: null,
loadedPbiIds: {},
loadedStoryIds: {},
loadedTaskIds: {},
activeRequestId: null,
},
sync: {
realtimeStatus: 'connecting',
lastEventAt: null,
lastResyncAt: null,
resyncReason: null,
},
pendingMutations: {},
}
function comparePbi(a: BacklogPbi, b: BacklogPbi): number {
if (a.priority !== b.priority) return a.priority - b.priority
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
}
function compareStory(a: BacklogStory, b: BacklogStory): number {
if (a.priority !== b.priority) return a.priority - b.priority
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
}
function compareTask(a: BacklogTask, b: BacklogTask): number {
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
}
function newRequestId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID()
}
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
}
function isKnownEntity(entity: unknown): entity is 'pbi' | 'story' | 'task' {
return entity === 'pbi' || entity === 'story' || entity === 'task'
}
function isUnknownEntityEvent(p: Record<string, unknown>): boolean {
if (typeof p.entity !== 'string') return false
if (isKnownEntity(p.entity)) return false
if ('type' in p) return false
return true
}
async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, { cache: 'no-store', ...init })
if (!response.ok) {
throw new Error(`Fetch ${url} failed with ${response.status}`)
}
return (await response.json()) as T
}
export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
immer((set, get) => ({
...initialState,
hydrateSnapshot(snapshot) {
set((s) => {
if (snapshot.product) s.context.activeProduct = snapshot.product
s.entities.pbisById = {}
s.entities.storiesById = {}
s.entities.tasksById = {}
s.relations.pbiIds = []
s.relations.storyIdsByPbi = {}
s.relations.taskIdsByStory = {}
for (const pbi of snapshot.pbis) {
s.entities.pbisById[pbi.id] = pbi
}
s.relations.pbiIds = [...snapshot.pbis].sort(comparePbi).map((p) => p.id)
for (const [pbiId, stories] of Object.entries(snapshot.storiesByPbi)) {
for (const story of stories) {
s.entities.storiesById[story.id] = story
}
s.relations.storyIdsByPbi[pbiId] = [...stories]
.sort(compareStory)
.map((st) => st.id)
}
for (const [storyId, tasks] of Object.entries(snapshot.tasksByStory)) {
for (const task of tasks) {
s.entities.tasksById[task.id] = task
}
s.relations.taskIdsByStory[storyId] = [...tasks]
.sort(compareTask)
.map((t) => t.id)
}
if (snapshot.product) {
s.loading.loadedProductId = snapshot.product.id
}
})
},
setActiveProduct(product) {
const requestId = newRequestId()
const productChanged = get().context.activeProduct?.id !== product?.id
set((s) => {
s.context.activeProduct = product
s.context.activePbiId = null
s.context.activeStoryId = null
s.context.activeTaskId = null
s.loading.activeRequestId = requestId
if (productChanged) {
s.entities.pbisById = {}
s.entities.storiesById = {}
s.entities.tasksById = {}
s.relations.pbiIds = []
s.relations.storyIdsByPbi = {}
s.relations.taskIdsByStory = {}
s.loading.loadedProductId = null
s.loading.loadedPbiIds = {}
s.loading.loadedStoryIds = {}
s.loading.loadedTaskIds = {}
}
})
// T-858: persisteer product-hint zodat een volgende cold reload deze
// selectie kan herstellen. T-857: restore-flow start na ensureProductLoaded.
writeProductHint(product?.id ?? null)
if (product) {
const productId = product.id
void (async () => {
await get().ensureProductLoaded(productId, requestId)
if (get().loading.activeRequestId !== requestId) return
// T-857: cascade-restore — alleen toepassen als hint-id nog in
// entities zit (entiteit accessible).
const hint = readHints().perProduct[productId]?.lastActivePbiId
if (hint && get().entities.pbisById[hint]) {
get().setActivePbi(hint)
}
})()
}
},
setActivePbi(pbiId) {
const requestId = newRequestId()
const productId = get().context.activeProduct?.id ?? null
set((s) => {
s.context.activePbiId = pbiId
s.context.activeStoryId = null
s.context.activeTaskId = null
s.loading.activeRequestId = requestId
})
// T-858: persisteer pbi-hint per product. null wist child-hints (zie
// restore.ts writePbiHint).
if (productId) writePbiHint(productId, pbiId)
if (pbiId) {
void (async () => {
await get().ensurePbiLoaded(pbiId, requestId)
if (get().loading.activeRequestId !== requestId) return
if (!productId) return
// T-857: cascade-restore
const hint = readHints().perProduct[productId]?.lastActiveStoryId
if (hint && get().entities.storiesById[hint]) {
get().setActiveStory(hint)
}
})()
}
},
setActiveStory(storyId) {
const requestId = newRequestId()
const productId = get().context.activeProduct?.id ?? null
set((s) => {
s.context.activeStoryId = storyId
s.context.activeTaskId = null
s.loading.activeRequestId = requestId
})
if (productId) writeStoryHint(productId, storyId)
if (storyId) {
void (async () => {
await get().ensureStoryLoaded(storyId, requestId)
if (get().loading.activeRequestId !== requestId) return
if (!productId) return
const hint = readHints().perProduct[productId]?.lastActiveTaskId
if (hint && get().entities.tasksById[hint]) {
get().setActiveTask(hint)
}
})()
}
},
setActiveTask(taskId) {
const productId = get().context.activeProduct?.id ?? null
set((s) => {
s.context.activeTaskId = taskId
})
if (productId) writeTaskHint(productId, taskId)
if (taskId) {
void get().ensureTaskLoaded(taskId)
}
},
async ensureProductLoaded(productId, requestId) {
set((s) => {
s.loading.loadingProductId = productId
})
try {
const snapshot = await fetchJson<ProductBacklogSnapshot | null>(
`/api/products/${encodeURIComponent(productId)}/backlog`,
)
if (requestId && get().loading.activeRequestId !== requestId) return
if (!snapshot || !Array.isArray(snapshot.pbis)) return
get().hydrateSnapshot(snapshot)
set((s) => {
s.loading.loadedProductId = productId
for (const pbi of snapshot.pbis) {
s.loading.loadedPbiIds[pbi.id] = true
}
})
} finally {
set((s) => {
if (s.loading.loadingProductId === productId) {
s.loading.loadingProductId = null
}
})
}
},
async ensurePbiLoaded(pbiId, requestId) {
const stories = await fetchJson<BacklogStory[] | null>(
`/api/pbis/${encodeURIComponent(pbiId)}/stories`,
)
if (requestId && get().loading.activeRequestId !== requestId) return
if (!Array.isArray(stories)) return
set((s) => {
for (const story of stories) {
s.entities.storiesById[story.id] = story
}
s.relations.storyIdsByPbi[pbiId] = [...stories]
.sort(compareStory)
.map((st) => st.id)
s.loading.loadedPbiIds[pbiId] = true
})
},
async ensureStoryLoaded(storyId, requestId) {
const tasks = await fetchJson<BacklogTask[] | null>(
`/api/stories/${encodeURIComponent(storyId)}/tasks`,
)
if (requestId && get().loading.activeRequestId !== requestId) return
if (!Array.isArray(tasks)) return
set((s) => {
for (const task of tasks) {
const existing = s.entities.tasksById[task.id]
if (existing && isDetail(existing)) {
s.entities.tasksById[task.id] = { ...existing, ...task }
} else {
s.entities.tasksById[task.id] = task
}
}
s.relations.taskIdsByStory[storyId] = [...tasks]
.sort(compareTask)
.map((t) => t.id)
s.loading.loadedStoryIds[storyId] = true
})
},
async ensureTaskLoaded(taskId, requestId) {
const detail = await fetchJson<TaskDetail | null>(
`/api/tasks/${encodeURIComponent(taskId)}`,
)
if (requestId && get().loading.activeRequestId !== requestId) return
if (!detail || typeof detail !== 'object') return
set((s) => {
s.entities.tasksById[taskId] = { ...detail, _detail: true }
s.loading.loadedTaskIds[taskId] = true
})
},
applyRealtimeEvent(event) {
const payload = event as Record<string, unknown>
const activeProductId = get().context.activeProduct?.id ?? null
set((s) => {
s.sync.lastEventAt = Date.now()
})
if (
typeof payload.product_id === 'string' &&
activeProductId &&
payload.product_id !== activeProductId
) {
return
}
if (isUnknownEntityEvent(payload)) {
if (payload.product_id === activeProductId) {
void get().resyncActiveScopes('unknown-event')
}
return
}
const entity = payload.entity
const op = payload.op
if (!isKnownEntity(entity)) return
if (op !== 'I' && op !== 'U' && op !== 'D') return
const id = payload.id
if (typeof id !== 'string') return
if (entity === 'pbi') {
applyPbiEvent(id, op, payload, set, get)
} else if (entity === 'story') {
applyStoryEvent(id, op, payload, set, get)
} else if (entity === 'task') {
applyTaskEvent(id, op, payload, set, get)
}
},
async resyncActiveScopes(reason) {
const ctx = get().context
const tasks: Promise<void>[] = []
if (ctx.activeProduct?.id) {
tasks.push(get().ensureProductLoaded(ctx.activeProduct.id))
}
if (ctx.activePbiId) tasks.push(get().ensurePbiLoaded(ctx.activePbiId))
if (ctx.activeStoryId) tasks.push(get().ensureStoryLoaded(ctx.activeStoryId))
if (ctx.activeTaskId) tasks.push(get().ensureTaskLoaded(ctx.activeTaskId))
set((s) => {
s.sync.lastResyncAt = Date.now()
s.sync.resyncReason = reason
})
await Promise.allSettled(tasks)
},
async resyncLoadedScopes(reason) {
const loading = get().loading
const tasks: Promise<void>[] = []
if (loading.loadedProductId) {
tasks.push(get().ensureProductLoaded(loading.loadedProductId))
}
for (const pbiId of Object.keys(loading.loadedPbiIds)) {
tasks.push(get().ensurePbiLoaded(pbiId))
}
for (const storyId of Object.keys(loading.loadedStoryIds)) {
tasks.push(get().ensureStoryLoaded(storyId))
}
for (const taskId of Object.keys(loading.loadedTaskIds)) {
tasks.push(get().ensureTaskLoaded(taskId))
}
set((s) => {
s.sync.lastResyncAt = Date.now()
s.sync.resyncReason = reason
})
await Promise.allSettled(tasks)
},
applyOptimisticMutation(mutation) {
const id = newRequestId()
set((s) => {
s.pendingMutations[id] = {
id,
mutation,
createdAt: Date.now(),
}
switch (mutation.kind) {
case 'pbi-order':
// store-call passes new order via separate set, snapshot is prevPbiIds
break
case 'story-order':
break
case 'task-order':
break
case 'entity-patch':
break
}
})
return id
},
rollbackMutation(mutationId) {
const pending = get().pendingMutations[mutationId]
if (!pending) return
const { mutation } = pending
set((s) => {
switch (mutation.kind) {
case 'pbi-order':
s.relations.pbiIds = [...mutation.prevPbiIds]
break
case 'story-order':
s.relations.storyIdsByPbi[mutation.pbiId] = [...mutation.prevStoryIds]
break
case 'task-order':
s.relations.taskIdsByStory[mutation.storyId] = [...mutation.prevTaskIds]
break
case 'entity-patch': {
const { entity, id, prev } = mutation
if (prev) {
if (entity === 'pbi') s.entities.pbisById[id] = prev as BacklogPbi
else if (entity === 'story') s.entities.storiesById[id] = prev as BacklogStory
else s.entities.tasksById[id] = prev as BacklogTask | TaskDetail
} else {
if (entity === 'pbi') delete s.entities.pbisById[id]
else if (entity === 'story') delete s.entities.storiesById[id]
else delete s.entities.tasksById[id]
}
break
}
}
delete s.pendingMutations[mutationId]
})
},
settleMutation(mutationId) {
set((s) => {
delete s.pendingMutations[mutationId]
})
},
setRealtimeStatus(status) {
set((s) => {
s.sync.realtimeStatus = status
})
},
})),
)
type ImmerSet = Parameters<Parameters<typeof immer<ProductWorkspaceStore>>[0]>[0]
type ImmerGet = () => ProductWorkspaceStore
function applyPbiEvent(
id: string,
op: 'I' | 'U' | 'D',
payload: Record<string, unknown>,
set: ImmerSet,
get: ImmerGet,
) {
if (op === 'D') {
set((s) => {
const childStoryIds = s.relations.storyIdsByPbi[id] ?? []
for (const sid of childStoryIds) {
const childTaskIds = s.relations.taskIdsByStory[sid] ?? []
for (const tid of childTaskIds) {
delete s.entities.tasksById[tid]
}
delete s.relations.taskIdsByStory[sid]
delete s.entities.storiesById[sid]
}
delete s.relations.storyIdsByPbi[id]
delete s.entities.pbisById[id]
s.relations.pbiIds = s.relations.pbiIds.filter((p) => p !== id)
if (s.context.activePbiId === id) {
s.context.activePbiId = null
s.context.activeStoryId = null
s.context.activeTaskId = null
}
})
return
}
if (op === 'U') {
if (!get().entities.pbisById[id]) return
set((s) => {
const existing = s.entities.pbisById[id]
if (!existing) return
Object.assign(existing, sanitizePbiPayload(payload))
s.relations.pbiIds = sortPbiIds(s.entities.pbisById, s.relations.pbiIds)
})
return
}
// I
if (get().entities.pbisById[id]) return
set((s) => {
const pbi = coercePbiPayload(id, payload)
s.entities.pbisById[id] = pbi
s.relations.pbiIds.push(id)
s.relations.pbiIds = sortPbiIds(s.entities.pbisById, s.relations.pbiIds)
})
}
function applyStoryEvent(
id: string,
op: 'I' | 'U' | 'D',
payload: Record<string, unknown>,
set: ImmerSet,
get: ImmerGet,
) {
if (op === 'D') {
set((s) => {
const childTaskIds = s.relations.taskIdsByStory[id] ?? []
for (const tid of childTaskIds) {
delete s.entities.tasksById[tid]
}
delete s.relations.taskIdsByStory[id]
const story = s.entities.storiesById[id]
delete s.entities.storiesById[id]
if (story) {
const ids = s.relations.storyIdsByPbi[story.pbi_id]
if (ids) {
s.relations.storyIdsByPbi[story.pbi_id] = ids.filter((sid) => sid !== id)
}
} else {
for (const pbiId of Object.keys(s.relations.storyIdsByPbi)) {
s.relations.storyIdsByPbi[pbiId] = s.relations.storyIdsByPbi[pbiId].filter(
(sid) => sid !== id,
)
}
}
if (s.context.activeStoryId === id) {
s.context.activeStoryId = null
s.context.activeTaskId = null
}
})
return
}
if (op === 'U') {
const existing = get().entities.storiesById[id]
if (!existing) return
set((s) => {
const story = s.entities.storiesById[id]
if (!story) return
const oldPbiId = story.pbi_id
Object.assign(story, sanitizeStoryPayload(payload))
const newPbiId = story.pbi_id
if (oldPbiId !== newPbiId) {
const oldList = s.relations.storyIdsByPbi[oldPbiId]
if (oldList) {
s.relations.storyIdsByPbi[oldPbiId] = oldList.filter((sid) => sid !== id)
}
const targetList = s.relations.storyIdsByPbi[newPbiId] ?? []
if (!targetList.includes(id)) targetList.push(id)
s.relations.storyIdsByPbi[newPbiId] = sortStoryIds(s.entities.storiesById, targetList)
} else if (s.relations.storyIdsByPbi[oldPbiId]) {
s.relations.storyIdsByPbi[oldPbiId] = sortStoryIds(
s.entities.storiesById,
s.relations.storyIdsByPbi[oldPbiId],
)
}
})
return
}
// I
if (get().entities.storiesById[id]) return
set((s) => {
const story = coerceStoryPayload(id, payload)
s.entities.storiesById[id] = story
const list = s.relations.storyIdsByPbi[story.pbi_id] ?? []
list.push(id)
s.relations.storyIdsByPbi[story.pbi_id] = sortStoryIds(s.entities.storiesById, list)
})
}
function applyTaskEvent(
id: string,
op: 'I' | 'U' | 'D',
payload: Record<string, unknown>,
set: ImmerSet,
get: ImmerGet,
) {
if (op === 'D') {
set((s) => {
const task = s.entities.tasksById[id]
delete s.entities.tasksById[id]
if (task) {
const ids = s.relations.taskIdsByStory[task.story_id]
if (ids) {
s.relations.taskIdsByStory[task.story_id] = ids.filter((tid) => tid !== id)
}
} else {
for (const storyId of Object.keys(s.relations.taskIdsByStory)) {
s.relations.taskIdsByStory[storyId] = s.relations.taskIdsByStory[storyId].filter(
(tid) => tid !== id,
)
}
}
if (s.context.activeTaskId === id) {
s.context.activeTaskId = null
}
})
return
}
if (op === 'U') {
const existing = get().entities.tasksById[id]
if (!existing) return
set((s) => {
const task = s.entities.tasksById[id]
if (!task) return
const oldStoryId = task.story_id
Object.assign(task, sanitizeTaskPayload(payload))
const newStoryId = task.story_id
if (oldStoryId !== newStoryId) {
const oldList = s.relations.taskIdsByStory[oldStoryId]
if (oldList) {
s.relations.taskIdsByStory[oldStoryId] = oldList.filter((tid) => tid !== id)
}
const targetList = s.relations.taskIdsByStory[newStoryId] ?? []
if (!targetList.includes(id)) targetList.push(id)
s.relations.taskIdsByStory[newStoryId] = sortTaskIds(s.entities.tasksById, targetList)
} else if (s.relations.taskIdsByStory[oldStoryId]) {
s.relations.taskIdsByStory[oldStoryId] = sortTaskIds(
s.entities.tasksById,
s.relations.taskIdsByStory[oldStoryId],
)
}
})
return
}
// I
if (get().entities.tasksById[id]) return
set((s) => {
const task = coerceTaskPayload(id, payload)
s.entities.tasksById[id] = task
const list = s.relations.taskIdsByStory[task.story_id] ?? []
list.push(id)
s.relations.taskIdsByStory[task.story_id] = sortTaskIds(s.entities.tasksById, list)
})
}
function sortPbiIds(byId: Record<string, BacklogPbi>, ids: string[]): string[] {
return [...new Set(ids)]
.filter((id) => byId[id] !== undefined)
.sort((a, b) => comparePbi(byId[a], byId[b]))
}
function sortStoryIds(byId: Record<string, BacklogStory>, ids: string[]): string[] {
return [...new Set(ids)]
.filter((id) => byId[id] !== undefined)
.sort((a, b) => compareStory(byId[a], byId[b]))
}
function sortTaskIds(
byId: Record<string, BacklogTask | TaskDetail>,
ids: string[],
): string[] {
return [...new Set(ids)]
.filter((id) => byId[id] !== undefined)
.sort((a, b) => compareTask(byId[a], byId[b]))
}
function sanitizePbiPayload(p: Record<string, unknown>): Partial<BacklogPbi> {
const { entity: _e, op: _o, ...rest } = p
void _e
void _o
return rest as Partial<BacklogPbi>
}
function sanitizeStoryPayload(p: Record<string, unknown>): Partial<BacklogStory> {
const { entity: _e, op: _o, ...rest } = p
void _e
void _o
return rest as Partial<BacklogStory>
}
function sanitizeTaskPayload(p: Record<string, unknown>): Partial<BacklogTask> {
const { entity: _e, op: _o, ...rest } = p
void _e
void _o
return rest as Partial<BacklogTask>
}
function coercePbiPayload(id: string, p: Record<string, unknown>): BacklogPbi {
return {
id,
code: (p.code as string | null) ?? null,
title: String(p.title ?? ''),
priority: Number(p.priority ?? 4),
sort_order: Number(p.sort_order ?? 0),
description: (p.description as string | null | undefined) ?? null,
created_at:
p.created_at instanceof Date
? p.created_at
: new Date(String(p.created_at ?? Date.now())),
status: (p.status as BacklogPbi['status']) ?? 'ready',
}
}
function coerceStoryPayload(id: string, p: Record<string, unknown>): BacklogStory {
return {
id,
code: (p.code as string | null) ?? null,
title: String(p.title ?? ''),
description: (p.description as string | null | undefined) ?? null,
acceptance_criteria: (p.acceptance_criteria as string | null | undefined) ?? null,
priority: Number(p.priority ?? 4),
sort_order: Number(p.sort_order ?? 0),
status: String(p.status ?? 'open'),
pbi_id: String(p.pbi_id ?? ''),
sprint_id: (p.sprint_id as string | null | undefined) ?? null,
created_at:
p.created_at instanceof Date
? p.created_at
: new Date(String(p.created_at ?? Date.now())),
}
}
function coerceTaskPayload(id: string, p: Record<string, unknown>): BacklogTask {
return {
id,
title: String(p.title ?? ''),
description: (p.description as string | null | undefined) ?? null,
priority: Number(p.priority ?? 4),
sort_order: Number(p.sort_order ?? 0),
status: String(p.status ?? 'todo'),
story_id: String(p.story_id ?? ''),
created_at:
p.created_at instanceof Date
? p.created_at
: new Date(String(p.created_at ?? Date.now())),
}
}

View file

@ -0,0 +1,140 @@
import type { PbiStatusApi } from '@/lib/task-status'
export interface BacklogPbi {
id: string
code: string | null
title: string
priority: number
sort_order: number
description?: string | null
created_at: Date
status: PbiStatusApi
}
export interface BacklogStory {
id: string
code: string | null
title: string
description: string | null
acceptance_criteria: string | null
priority: number
sort_order: number
status: string
pbi_id: string
sprint_id: string | null
created_at: Date
}
export interface BacklogTask {
id: string
title: string
description: string | null
priority: number
status: string
sort_order: number
story_id: string
created_at: Date
}
export interface TaskDetail extends BacklogTask {
_detail: true
implementation_plan?: string | null
acceptance_criteria?: string | null
requires_opus?: boolean
estimated_minutes?: number | null
}
export function isDetail(task: BacklogTask | TaskDetail): task is TaskDetail {
return (task as TaskDetail)._detail === true
}
export interface ActiveProduct {
id: string
name: string
}
export interface ProductBacklogSnapshot {
product?: ActiveProduct
pbis: BacklogPbi[]
storiesByPbi: Record<string, BacklogStory[]>
tasksByStory: Record<string, BacklogTask[]>
}
export type Op = 'I' | 'U' | 'D'
export interface PbiRealtimeEvent {
entity: 'pbi'
op: Op
id: string
product_id: string
[key: string]: unknown
}
export interface StoryRealtimeEvent {
entity: 'story'
op: Op
id: string
product_id: string
pbi_id?: string
[key: string]: unknown
}
export interface TaskRealtimeEvent {
entity: 'task'
op: Op
id: string
product_id: string
story_id?: string
[key: string]: unknown
}
export type ProductRealtimeEvent =
| PbiRealtimeEvent
| StoryRealtimeEvent
| TaskRealtimeEvent
export type ResyncReason =
| 'visible'
| 'reconnect'
| 'manual'
| 'unknown-event'
| 'stale-scope'
| 'mutation-settled'
export type RealtimeStatus = 'connecting' | 'open' | 'disconnected'
export interface OptimisticPbiOrderMutation {
kind: 'pbi-order'
prevPbiIds: string[]
}
export interface OptimisticStoryOrderMutation {
kind: 'story-order'
pbiId: string
prevStoryIds: string[]
}
export interface OptimisticTaskOrderMutation {
kind: 'task-order'
storyId: string
prevTaskIds: string[]
}
export interface OptimisticEntityPatchMutation {
kind: 'entity-patch'
entity: 'pbi' | 'story' | 'task'
id: string
prev: BacklogPbi | BacklogStory | BacklogTask | TaskDetail | undefined
}
export type OptimisticMutation =
| OptimisticPbiOrderMutation
| OptimisticStoryOrderMutation
| OptimisticTaskOrderMutation
| OptimisticEntityPatchMutation
export interface PendingOptimisticMutation {
id: string
mutation: OptimisticMutation
createdAt: number
}

View file

@ -1,17 +0,0 @@
import { create } from 'zustand'
interface SelectionStore {
selectedPbiId: string | null
selectedStoryId: string | null
selectPbi: (id: string | null) => void
selectStory: (id: string | null) => void
clearSelection: () => void
}
export const useSelectionStore = create<SelectionStore>((set) => ({
selectedPbiId: null,
selectedStoryId: null,
selectPbi: (id) => set({ selectedPbiId: id, selectedStoryId: null }),
selectStory: (id) => set({ selectedStoryId: id }),
clearSelection: () => set({ selectedPbiId: null, selectedStoryId: null }),
}))

84
tests/setup.ts Normal file
View file

@ -0,0 +1,84 @@
import { beforeEach, vi } from 'vitest'
// G6: vitest 4 + jsdom 29 mist localStorage/sessionStorage op globalThis.
// MemoryStorage-binding zodat tests zonder echte browser draaien.
class MemoryStorage implements Storage {
private store = new Map<string, string>()
get length(): number {
return this.store.size
}
clear(): void {
this.store.clear()
}
getItem(key: string): string | null {
return this.store.has(key) ? this.store.get(key)! : null
}
key(index: number): string | null {
return Array.from(this.store.keys())[index] ?? null
}
removeItem(key: string): void {
this.store.delete(key)
}
setItem(key: string, value: string): void {
this.store.set(key, String(value))
}
}
const localStorageMemory = new MemoryStorage()
const sessionStorageMemory = new MemoryStorage()
Object.defineProperty(globalThis, 'localStorage', {
value: localStorageMemory,
configurable: true,
writable: true,
})
Object.defineProperty(globalThis, 'sessionStorage', {
value: sessionStorageMemory,
configurable: true,
writable: true,
})
if (typeof window !== 'undefined') {
Object.defineProperty(window, 'localStorage', {
value: localStorageMemory,
configurable: true,
writable: true,
})
Object.defineProperty(window, 'sessionStorage', {
value: sessionStorageMemory,
configurable: true,
writable: true,
})
}
// G7: maak globalThis.fetch herconfigureerbaar zodat vi.spyOn / vi.fn-stubs
// de eigenschap kunnen redefineren. Default Node 24 / jsdom 29 binding is
// vaak non-configurable, wat vi.spyOn(globalThis, 'fetch') laat falen.
const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch
Object.defineProperty(globalThis, 'fetch', {
value: originalFetch,
configurable: true,
writable: true,
})
beforeEach(() => {
localStorageMemory.clear()
sessionStorageMemory.clear()
vi.restoreAllMocks()
// Default fetch-stub voorkomt dat fire-and-forget ensure*Loaded calls
// (b.v. via setActivePbi) lekken naar het echte network. Tests die
// specifieke responses willen overrulen dit met vi.spyOn/vi.fn.
// G8: mockImplementation (niet mockResolvedValue) zodat elke call een
// verse Response krijgt — body wordt anders maar één keer leesbaar.
;(globalThis as { fetch: typeof fetch }).fetch = vi
.fn()
.mockImplementation(() =>
Promise.resolve(new Response('null', { status: 200 })),
) as unknown as typeof fetch
})

View file

@ -0,0 +1 @@
export {}

View file

@ -3,12 +3,14 @@ import path from 'path'
export default defineConfig({
test: {
environment: 'node',
environment: 'jsdom',
globals: true,
setupFiles: ['tests/setup.ts'],
},
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
'server-only': path.resolve(__dirname, 'tests/stubs/server-only.ts'),
},
},
})