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

@ -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 }),
}))