Load/render workspace alignment (#182)
* docs: plan load render workspace alignment * fix: normalize workspace status hydration * fix: avoid duplicate backlog hydration load * refactor: use sprint store active story * refactor: migrate solo to workspace store * chore: stabilize verification ignores
This commit is contained in:
parent
98ee05d458
commit
3b5cee823c
28 changed files with 1845 additions and 577 deletions
|
|
@ -22,6 +22,14 @@ import {
|
|||
writeStoryHint,
|
||||
writeTaskHint,
|
||||
} from './restore'
|
||||
import {
|
||||
normalizeBacklogStory,
|
||||
normalizeBacklogTask,
|
||||
normalizeProductBacklogSnapshot,
|
||||
normalizePbiStatusForStore,
|
||||
normalizeStoryStatusForStore,
|
||||
normalizeTaskStatusForStore,
|
||||
} from '@/stores/workspace-status-adapter'
|
||||
|
||||
interface ContextSlice {
|
||||
activeProduct: ActiveProduct | null
|
||||
|
|
@ -70,7 +78,10 @@ interface State {
|
|||
interface Actions {
|
||||
hydrateSnapshot(snapshot: ProductBacklogSnapshot): void
|
||||
|
||||
setActiveProduct(product: ActiveProduct | null): void
|
||||
setActiveProduct(
|
||||
product: ActiveProduct | null,
|
||||
options?: { load?: boolean; preserveSelection?: boolean },
|
||||
): void
|
||||
setActivePbi(pbiId: string | null): void
|
||||
setActiveStory(storyId: string | null): void
|
||||
setActiveTask(taskId: string | null): void
|
||||
|
|
@ -174,7 +185,8 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
immer((set, get) => ({
|
||||
...initialState,
|
||||
|
||||
hydrateSnapshot(snapshot) {
|
||||
hydrateSnapshot(inputSnapshot) {
|
||||
const snapshot = normalizeProductBacklogSnapshot(inputSnapshot)
|
||||
set((s) => {
|
||||
if (snapshot.product) s.context.activeProduct = snapshot.product
|
||||
|
||||
|
|
@ -214,15 +226,18 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
})
|
||||
},
|
||||
|
||||
setActiveProduct(product) {
|
||||
setActiveProduct(product, options) {
|
||||
const requestId = newRequestId()
|
||||
const productChanged = get().context.activeProduct?.id !== product?.id
|
||||
const shouldResetSelection = productChanged || !options?.preserveSelection
|
||||
|
||||
set((s) => {
|
||||
s.context.activeProduct = product
|
||||
s.context.activePbiId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
if (shouldResetSelection) {
|
||||
s.context.activePbiId = null
|
||||
s.context.activeStoryId = null
|
||||
s.context.activeTaskId = null
|
||||
}
|
||||
s.loading.activeRequestId = requestId
|
||||
|
||||
if (productChanged) {
|
||||
|
|
@ -243,7 +258,7 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
// selectie kan herstellen. T-857: restore-flow start na ensureProductLoaded.
|
||||
writeProductHint(product?.id ?? null)
|
||||
|
||||
if (product) {
|
||||
if (product && options?.load !== false) {
|
||||
const productId = product.id
|
||||
void (async () => {
|
||||
await get().ensureProductLoaded(productId, requestId)
|
||||
|
|
@ -358,11 +373,12 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!Array.isArray(stories)) return
|
||||
const normalizedStories = stories.map(normalizeBacklogStory)
|
||||
set((s) => {
|
||||
for (const story of stories) {
|
||||
for (const story of normalizedStories) {
|
||||
s.entities.storiesById[story.id] = story
|
||||
}
|
||||
s.relations.storyIdsByPbi[pbiId] = [...stories]
|
||||
s.relations.storyIdsByPbi[pbiId] = [...normalizedStories]
|
||||
.sort(compareStory)
|
||||
.map((st) => st.id)
|
||||
s.loading.loadedPbiIds[pbiId] = true
|
||||
|
|
@ -375,8 +391,9 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!Array.isArray(tasks)) return
|
||||
const normalizedTasks = tasks.map(normalizeBacklogTask)
|
||||
set((s) => {
|
||||
for (const task of tasks) {
|
||||
for (const task of normalizedTasks) {
|
||||
const existing = s.entities.tasksById[task.id]
|
||||
if (existing && isDetail(existing)) {
|
||||
s.entities.tasksById[task.id] = { ...existing, ...task }
|
||||
|
|
@ -384,7 +401,7 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
s.entities.tasksById[task.id] = task
|
||||
}
|
||||
}
|
||||
s.relations.taskIdsByStory[storyId] = [...tasks]
|
||||
s.relations.taskIdsByStory[storyId] = [...normalizedTasks]
|
||||
.sort(compareTask)
|
||||
.map((t) => t.id)
|
||||
s.loading.loadedStoryIds[storyId] = true
|
||||
|
|
@ -397,8 +414,9 @@ export const useProductWorkspaceStore = create<ProductWorkspaceStore>()(
|
|||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!detail || typeof detail !== 'object') return
|
||||
const normalizedDetail = normalizeBacklogTask(detail)
|
||||
set((s) => {
|
||||
s.entities.tasksById[taskId] = { ...detail, _detail: true }
|
||||
s.entities.tasksById[taskId] = { ...normalizedDetail, _detail: true }
|
||||
s.loading.loadedTaskIds[taskId] = true
|
||||
})
|
||||
},
|
||||
|
|
@ -772,20 +790,65 @@ function sanitizePbiPayload(p: Record<string, unknown>): Partial<BacklogPbi> {
|
|||
const { entity: _e, op: _o, ...rest } = p
|
||||
void _e
|
||||
void _o
|
||||
if (typeof rest.status === 'string') {
|
||||
rest.status = normalizePbiStatusForStore(rest.status)
|
||||
}
|
||||
return rest as Partial<BacklogPbi>
|
||||
}
|
||||
|
||||
function sanitizeStoryPayload(p: Record<string, unknown>): Partial<BacklogStory> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
const {
|
||||
entity: _e,
|
||||
op: _o,
|
||||
story_status,
|
||||
story_sort_order,
|
||||
story_title,
|
||||
story_code,
|
||||
...rest
|
||||
} = p
|
||||
void _e
|
||||
void _o
|
||||
if (rest.status === undefined && typeof story_status === 'string') {
|
||||
rest.status = story_status
|
||||
}
|
||||
if (rest.sort_order === undefined && typeof story_sort_order === 'number') {
|
||||
rest.sort_order = story_sort_order
|
||||
}
|
||||
if (rest.title === undefined && typeof story_title === 'string') {
|
||||
rest.title = story_title
|
||||
}
|
||||
if (rest.code === undefined && (typeof story_code === 'string' || story_code === null)) {
|
||||
rest.code = story_code
|
||||
}
|
||||
if (typeof rest.status === 'string') {
|
||||
rest.status = normalizeStoryStatusForStore(rest.status)
|
||||
}
|
||||
return rest as Partial<BacklogStory>
|
||||
}
|
||||
|
||||
function sanitizeTaskPayload(p: Record<string, unknown>): Partial<BacklogTask> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
const {
|
||||
entity: _e,
|
||||
op: _o,
|
||||
task_status,
|
||||
task_sort_order,
|
||||
task_title,
|
||||
...rest
|
||||
} = p
|
||||
void _e
|
||||
void _o
|
||||
if (rest.status === undefined && typeof task_status === 'string') {
|
||||
rest.status = task_status
|
||||
}
|
||||
if (rest.sort_order === undefined && typeof task_sort_order === 'number') {
|
||||
rest.sort_order = task_sort_order
|
||||
}
|
||||
if (rest.title === undefined && typeof task_title === 'string') {
|
||||
rest.title = task_title
|
||||
}
|
||||
if (typeof rest.status === 'string') {
|
||||
rest.status = normalizeTaskStatusForStore(rest.status)
|
||||
}
|
||||
return rest as Partial<BacklogTask>
|
||||
}
|
||||
|
||||
|
|
@ -801,20 +864,24 @@ function coercePbiPayload(id: string, p: Record<string, unknown>): BacklogPbi {
|
|||
p.created_at instanceof Date
|
||||
? p.created_at
|
||||
: new Date(String(p.created_at ?? Date.now())),
|
||||
status: (p.status as BacklogPbi['status']) ?? 'ready',
|
||||
status: normalizePbiStatusForStore(String(p.status ?? 'ready')),
|
||||
}
|
||||
}
|
||||
|
||||
function coerceStoryPayload(id: string, p: Record<string, unknown>): BacklogStory {
|
||||
const status = p.status ?? p.story_status ?? 'OPEN'
|
||||
const sortOrder = p.sort_order ?? p.story_sort_order ?? 0
|
||||
const title = p.title ?? p.story_title ?? ''
|
||||
const code = p.code ?? p.story_code ?? null
|
||||
return {
|
||||
id,
|
||||
code: (p.code as string | null) ?? null,
|
||||
title: String(p.title ?? ''),
|
||||
code: (code as string | null) ?? null,
|
||||
title: String(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'),
|
||||
sort_order: Number(sortOrder),
|
||||
status: normalizeStoryStatusForStore(String(status)),
|
||||
pbi_id: String(p.pbi_id ?? ''),
|
||||
sprint_id: (p.sprint_id as string | null | undefined) ?? null,
|
||||
created_at:
|
||||
|
|
@ -825,13 +892,16 @@ function coerceStoryPayload(id: string, p: Record<string, unknown>): BacklogStor
|
|||
}
|
||||
|
||||
function coerceTaskPayload(id: string, p: Record<string, unknown>): BacklogTask {
|
||||
const status = p.status ?? p.task_status ?? 'TO_DO'
|
||||
const sortOrder = p.sort_order ?? p.task_sort_order ?? 0
|
||||
const title = p.title ?? p.task_title ?? ''
|
||||
return {
|
||||
id,
|
||||
title: String(p.title ?? ''),
|
||||
title: String(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'),
|
||||
sort_order: Number(sortOrder),
|
||||
status: normalizeTaskStatusForStore(String(status)),
|
||||
story_id: String(p.story_id ?? ''),
|
||||
created_at:
|
||||
p.created_at instanceof Date
|
||||
|
|
|
|||
|
|
@ -1,283 +1,8 @@
|
|||
import { create } from 'zustand'
|
||||
import type { SoloTask } from '@/components/solo/solo-board'
|
||||
import type { ClaudeJobStatusApi } from '@/lib/job-status'
|
||||
|
||||
type TaskStatus = SoloTask['status']
|
||||
|
||||
export type VerifyResultApi = 'aligned' | 'partial' | 'empty' | 'divergent'
|
||||
|
||||
export interface JobState {
|
||||
job_id: string
|
||||
task_id: string
|
||||
status: ClaudeJobStatusApi
|
||||
branch?: string
|
||||
pushed_at?: string | null
|
||||
pr_url?: string | null
|
||||
verify_result?: VerifyResultApi | null
|
||||
summary?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type ClaudeJobEvent =
|
||||
| { type: 'claude_job_enqueued'; job_id: string; task_id: string; user_id: string; product_id: string; status: 'queued' }
|
||||
| { type: 'claude_job_status'; job_id: string; task_id: string; user_id: string; product_id: string; status: ClaudeJobStatusApi; branch?: string; pushed_at?: string; pr_url?: string; verify_result?: VerifyResultApi; summary?: string; error?: string }
|
||||
|
||||
// Payload-shape gepubliceerd door de Postgres-trigger via pg_notify (ST-801
|
||||
// + ST-804 prereq). Komt het Solo Paneel binnen via de SSE-stream uit
|
||||
// /api/realtime/solo (ST-802).
|
||||
export interface RealtimeEvent {
|
||||
op: 'I' | 'U' | 'D'
|
||||
entity: 'task' | 'story'
|
||||
id: string
|
||||
story_id?: string
|
||||
product_id: string
|
||||
sprint_id: string | null
|
||||
assignee_id: string | null
|
||||
// Task-specifieke velden (alleen aanwezig als entity === 'task')
|
||||
task_status?: TaskStatus
|
||||
task_sort_order?: number
|
||||
task_title?: string
|
||||
// Story-specifieke velden (alleen aanwezig als entity === 'story')
|
||||
story_status?: 'OPEN' | 'IN_SPRINT' | 'DONE'
|
||||
story_sort_order?: number
|
||||
story_title?: string
|
||||
story_code?: string | null
|
||||
// Op UPDATE: lijst van kolommen die zijn veranderd
|
||||
changed_fields?: string[]
|
||||
}
|
||||
|
||||
export type RealtimeStatus = 'connecting' | 'open' | 'disconnected'
|
||||
|
||||
interface SoloStore {
|
||||
tasks: Record<string, SoloTask>
|
||||
/** Task-ids die op dit moment een eigen optimistic write in de lucht hebben.
|
||||
* Realtime echos voor deze ids worden onderdrukt zodat de eigen update niet
|
||||
* twee keer toegepast wordt of door een latere echo overschreven. */
|
||||
pendingOps: Set<string>
|
||||
|
||||
/** Realtime-connection state, beheerd door useSoloRealtime in de
|
||||
* (app)-layout. Hier in de store omdat de UI-indicator in SoloBoard zit en
|
||||
* de hook niet direct in dezelfde subtree draait. */
|
||||
realtimeStatus: RealtimeStatus
|
||||
showConnectingIndicator: boolean
|
||||
|
||||
claudeJobsByTaskId: Record<string, JobState>
|
||||
connectedWorkers: number
|
||||
|
||||
// M13: laatste quota-rapport van een actieve worker. null = geen
|
||||
// worker actief of nog geen heartbeat met quota ontvangen.
|
||||
workerQuotaPct: number | null
|
||||
workerQuotaCheckAt: string | null
|
||||
|
||||
initTasks: (tasks: SoloTask[]) => void
|
||||
optimisticMove: (taskId: string, toStatus: TaskStatus) => TaskStatus | null
|
||||
rollback: (taskId: string, prevStatus: TaskStatus) => void
|
||||
updatePlan: (taskId: string, plan: string | null) => void
|
||||
updateVerifyOnly: (taskId: string, value: boolean) => void
|
||||
updateVerifyRequired: (taskId: string, value: 'ALIGNED' | 'ALIGNED_OR_PARTIAL' | 'ANY') => void
|
||||
|
||||
markPending: (taskId: string) => void
|
||||
clearPending: (taskId: string) => void
|
||||
|
||||
setRealtimeStatus: (status: RealtimeStatus, showConnectingIndicator: boolean) => void
|
||||
|
||||
initJobs: (jobs: JobState[]) => void
|
||||
handleJobEvent: (event: ClaudeJobEvent) => void
|
||||
|
||||
setWorkers: (count: number) => void
|
||||
incrementWorkers: () => void
|
||||
decrementWorkers: () => void
|
||||
setWorkerQuota: (pct: number, checkAt: string) => void
|
||||
|
||||
handleRealtimeEvent: (event: RealtimeEvent) => void
|
||||
}
|
||||
|
||||
export const useSoloStore = create<SoloStore>((set, get) => ({
|
||||
tasks: {},
|
||||
pendingOps: new Set<string>(),
|
||||
realtimeStatus: 'connecting',
|
||||
showConnectingIndicator: false,
|
||||
claudeJobsByTaskId: {},
|
||||
connectedWorkers: 0,
|
||||
workerQuotaPct: null,
|
||||
workerQuotaCheckAt: null,
|
||||
|
||||
initTasks: (tasks) =>
|
||||
set({ tasks: Object.fromEntries(tasks.map(t => [t.id, t])) }),
|
||||
|
||||
optimisticMove: (taskId, toStatus) => {
|
||||
const prev = get().tasks[taskId]?.status ?? null
|
||||
if (!prev) return null
|
||||
set((s) => ({ tasks: { ...s.tasks, [taskId]: { ...s.tasks[taskId], status: toStatus } } }))
|
||||
return prev
|
||||
},
|
||||
|
||||
rollback: (taskId, prevStatus) =>
|
||||
set((s) => ({ tasks: { ...s.tasks, [taskId]: { ...s.tasks[taskId], status: prevStatus } } })),
|
||||
|
||||
updatePlan: (taskId, plan) =>
|
||||
set((s) => ({ tasks: { ...s.tasks, [taskId]: { ...s.tasks[taskId], implementation_plan: plan } } })),
|
||||
|
||||
updateVerifyOnly: (taskId, value) =>
|
||||
set((s) => ({ tasks: { ...s.tasks, [taskId]: { ...s.tasks[taskId], verify_only: value } } })),
|
||||
|
||||
updateVerifyRequired: (taskId, value) =>
|
||||
set((s) => ({ tasks: { ...s.tasks, [taskId]: { ...s.tasks[taskId], verify_required: value } } })),
|
||||
|
||||
markPending: (taskId) =>
|
||||
set((s) => {
|
||||
if (s.pendingOps.has(taskId)) return s
|
||||
const next = new Set(s.pendingOps)
|
||||
next.add(taskId)
|
||||
return { pendingOps: next }
|
||||
}),
|
||||
|
||||
clearPending: (taskId) =>
|
||||
set((s) => {
|
||||
if (!s.pendingOps.has(taskId)) return s
|
||||
const next = new Set(s.pendingOps)
|
||||
next.delete(taskId)
|
||||
return { pendingOps: next }
|
||||
}),
|
||||
|
||||
setRealtimeStatus: (status, showConnectingIndicator) =>
|
||||
set((s) => {
|
||||
if (s.realtimeStatus === status && s.showConnectingIndicator === showConnectingIndicator) {
|
||||
return s
|
||||
}
|
||||
return { realtimeStatus: status, showConnectingIndicator }
|
||||
}),
|
||||
|
||||
initJobs: (jobs) =>
|
||||
set({ claudeJobsByTaskId: Object.fromEntries(jobs.map(j => [j.task_id, j])) }),
|
||||
|
||||
setWorkers: (count) => set({ connectedWorkers: Math.max(0, count) }),
|
||||
incrementWorkers: () => set(s => ({ connectedWorkers: s.connectedWorkers + 1 })),
|
||||
decrementWorkers: () =>
|
||||
set((s) => ({
|
||||
connectedWorkers: Math.max(0, s.connectedWorkers - 1),
|
||||
// Reset quota-state als alle workers weg zijn — pct van een vertrokken
|
||||
// worker is niet meer actueel.
|
||||
workerQuotaPct: s.connectedWorkers - 1 <= 0 ? null : s.workerQuotaPct,
|
||||
workerQuotaCheckAt: s.connectedWorkers - 1 <= 0 ? null : s.workerQuotaCheckAt,
|
||||
})),
|
||||
setWorkerQuota: (pct, checkAt) => set({ workerQuotaPct: pct, workerQuotaCheckAt: checkAt }),
|
||||
|
||||
handleJobEvent: (event) => {
|
||||
const { job_id, task_id } = event
|
||||
if (event.type === 'claude_job_enqueued') {
|
||||
set((s) => ({
|
||||
claudeJobsByTaskId: {
|
||||
...s.claudeJobsByTaskId,
|
||||
[task_id]: { job_id, task_id, status: 'queued' },
|
||||
},
|
||||
}))
|
||||
return
|
||||
}
|
||||
if (event.type === 'claude_job_status') {
|
||||
const { status, branch, pushed_at, pr_url, verify_result, summary, error } = event
|
||||
if (status === 'cancelled') {
|
||||
set((s) => {
|
||||
const next = { ...s.claudeJobsByTaskId }
|
||||
delete next[task_id]
|
||||
return { claudeJobsByTaskId: next }
|
||||
})
|
||||
return
|
||||
}
|
||||
set((s) => ({
|
||||
claudeJobsByTaskId: {
|
||||
...s.claudeJobsByTaskId,
|
||||
[task_id]: { job_id, task_id, status, branch, pushed_at, pr_url, verify_result, summary, error },
|
||||
},
|
||||
}))
|
||||
}
|
||||
},
|
||||
|
||||
handleRealtimeEvent: (event) => {
|
||||
if (event.entity === 'task') {
|
||||
const { id, op } = event
|
||||
|
||||
if (op === 'D') {
|
||||
set((s) => {
|
||||
if (!(id in s.tasks)) return s
|
||||
const next = { ...s.tasks }
|
||||
delete next[id]
|
||||
return { tasks: next }
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// INSERT en UPDATE: alleen bestaande taken bijwerken. Nieuwe taken
|
||||
// zonder story-context (story_title, story_code) renderen we niet
|
||||
// — gebruiker ziet ze pas na een refresh. Acceptabel voor v1.
|
||||
const existing = get().tasks[id]
|
||||
if (!existing) return
|
||||
|
||||
if (get().pendingOps.has(id)) {
|
||||
// Echo van een eigen optimistic move — laat de optimistic-state staan
|
||||
return
|
||||
}
|
||||
|
||||
const updates: Partial<SoloTask> = {}
|
||||
if (event.task_status !== undefined && event.task_status !== existing.status) {
|
||||
updates.status = event.task_status
|
||||
}
|
||||
if (
|
||||
event.task_sort_order !== undefined &&
|
||||
event.task_sort_order !== existing.sort_order
|
||||
) {
|
||||
updates.sort_order = event.task_sort_order
|
||||
}
|
||||
if (event.task_title !== undefined && event.task_title !== existing.title) {
|
||||
updates.title = event.task_title
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) return
|
||||
set((s) => ({ tasks: { ...s.tasks, [id]: { ...s.tasks[id], ...updates } } }))
|
||||
return
|
||||
}
|
||||
|
||||
if (event.entity === 'story') {
|
||||
const { id, op } = event
|
||||
|
||||
if (op === 'D') {
|
||||
// Story-cascade pakt tasks ook in de DB; verwijder de bijbehorende
|
||||
// SoloTask-records uit de store.
|
||||
set((s) => {
|
||||
const next: Record<string, SoloTask> = {}
|
||||
for (const [taskId, task] of Object.entries(s.tasks)) {
|
||||
if (task.story_id !== id) next[taskId] = task
|
||||
}
|
||||
return { tasks: next }
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const tasks = get().tasks
|
||||
const affectedIds = Object.entries(tasks)
|
||||
.filter(([, t]) => t.story_id === id)
|
||||
.map(([taskId]) => taskId)
|
||||
|
||||
if (affectedIds.length === 0) return
|
||||
|
||||
const newTitle = event.story_title
|
||||
const newCode = event.story_code ?? null
|
||||
|
||||
set((s) => {
|
||||
const next = { ...s.tasks }
|
||||
for (const taskId of affectedIds) {
|
||||
const t = next[taskId]
|
||||
const titleChanged = newTitle !== undefined && t.story_title !== newTitle
|
||||
const codeChanged = newCode !== t.story_code
|
||||
if (!titleChanged && !codeChanged) continue
|
||||
next[taskId] = {
|
||||
...t,
|
||||
...(titleChanged && newTitle !== undefined && { story_title: newTitle }),
|
||||
...(codeChanged && { story_code: newCode }),
|
||||
}
|
||||
}
|
||||
return { tasks: next }
|
||||
})
|
||||
}
|
||||
},
|
||||
}))
|
||||
export { useSoloWorkspaceStore as useSoloStore } from '@/stores/solo-workspace/store'
|
||||
export type {
|
||||
ClaudeJobEvent,
|
||||
JobState,
|
||||
RealtimeEvent,
|
||||
RealtimeStatus,
|
||||
VerifyResultApi,
|
||||
} from '@/stores/solo-workspace/types'
|
||||
|
|
|
|||
39
stores/solo-workspace/selectors.ts
Normal file
39
stores/solo-workspace/selectors.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import type { SoloWorkspaceStore } from './store'
|
||||
import type { SoloColumnStatus, SoloTask, SoloUnassignedStory } from './types'
|
||||
|
||||
const EMPTY_TASKS: SoloTask[] = []
|
||||
const EMPTY_STORIES: SoloUnassignedStory[] = []
|
||||
|
||||
export function selectSoloTasksForColumn(
|
||||
status: SoloColumnStatus,
|
||||
): (s: SoloWorkspaceStore) => SoloTask[] {
|
||||
return (s) => {
|
||||
const ids = s.relations.taskIdsByColumn[status]
|
||||
if (!ids || ids.length === 0) return EMPTY_TASKS
|
||||
const out: SoloTask[] = []
|
||||
for (const id of ids) {
|
||||
const task = s.entities.tasksById[id]
|
||||
if (task) out.push(task)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_TASKS : out
|
||||
}
|
||||
}
|
||||
|
||||
export function selectSoloUnassignedStories(s: SoloWorkspaceStore): SoloUnassignedStory[] {
|
||||
if (s.relations.unassignedStoryIds.length === 0) return EMPTY_STORIES
|
||||
const out: SoloUnassignedStory[] = []
|
||||
for (const id of s.relations.unassignedStoryIds) {
|
||||
const story = s.entities.unassignedStoriesById[id]
|
||||
if (story) out.push(story)
|
||||
}
|
||||
return out.length === 0 ? EMPTY_STORIES : out
|
||||
}
|
||||
|
||||
export function selectSoloTaskById(
|
||||
taskId: string | null,
|
||||
): (s: SoloWorkspaceStore) => SoloTask | null {
|
||||
return (s) => {
|
||||
if (!taskId) return null
|
||||
return s.entities.tasksById[taskId] ?? null
|
||||
}
|
||||
}
|
||||
619
stores/solo-workspace/store.ts
Normal file
619
stores/solo-workspace/store.ts
Normal file
|
|
@ -0,0 +1,619 @@
|
|||
import { create } from 'zustand'
|
||||
import type {
|
||||
ClaudeJobEvent,
|
||||
JobState,
|
||||
RealtimeEvent,
|
||||
RealtimeStatus,
|
||||
ResyncReason,
|
||||
SoloColumnStatus,
|
||||
SoloTask,
|
||||
SoloTaskStatus,
|
||||
SoloUnassignedStory,
|
||||
SoloWorkspaceProduct,
|
||||
SoloWorkspaceSnapshot,
|
||||
SoloWorkspaceSprint,
|
||||
SoloVerifyRequired,
|
||||
} from './types'
|
||||
|
||||
interface ContextSlice {
|
||||
activeProduct: SoloWorkspaceProduct | null
|
||||
activeSprint: SoloWorkspaceSprint | null
|
||||
activeUserId: string | null
|
||||
}
|
||||
|
||||
interface EntitiesSlice {
|
||||
tasksById: Record<string, SoloTask>
|
||||
unassignedStoriesById: Record<string, SoloUnassignedStory>
|
||||
jobsByTaskId: Record<string, JobState>
|
||||
}
|
||||
|
||||
interface RelationsSlice {
|
||||
taskIdsByColumn: Record<SoloColumnStatus, string[]>
|
||||
unassignedStoryIds: string[]
|
||||
}
|
||||
|
||||
interface LoadingSlice {
|
||||
loadedProductId: string | null
|
||||
loadedSprintId: string | null
|
||||
loadingSprintId: string | null
|
||||
activeRequestId: string | null
|
||||
}
|
||||
|
||||
interface SyncSlice {
|
||||
realtimeStatus: RealtimeStatus
|
||||
showConnectingIndicator: boolean
|
||||
lastEventAt: number | null
|
||||
lastResyncAt: number | null
|
||||
resyncReason: ResyncReason | null
|
||||
}
|
||||
|
||||
interface State {
|
||||
context: ContextSlice
|
||||
entities: EntitiesSlice
|
||||
relations: RelationsSlice
|
||||
loading: LoadingSlice
|
||||
sync: SyncSlice
|
||||
pendingOps: Set<string>
|
||||
tasks: Record<string, SoloTask>
|
||||
unassignedStoriesById: Record<string, SoloUnassignedStory>
|
||||
claudeJobsByTaskId: Record<string, JobState>
|
||||
realtimeStatus: RealtimeStatus
|
||||
showConnectingIndicator: boolean
|
||||
connectedWorkers: number
|
||||
workerQuotaPct: number | null
|
||||
workerQuotaCheckAt: string | null
|
||||
}
|
||||
|
||||
interface Actions {
|
||||
hydrateSnapshot(snapshot: SoloWorkspaceSnapshot): void
|
||||
initTasks(tasks: SoloTask[]): void
|
||||
hydrateUnassignedStories(stories: SoloUnassignedStory[]): void
|
||||
removeUnassignedStory(storyId: string): void
|
||||
|
||||
optimisticMove(taskId: string, toStatus: SoloTaskStatus): SoloTaskStatus | null
|
||||
rollback(taskId: string, prevStatus: SoloTaskStatus): void
|
||||
updatePlan(taskId: string, plan: string | null): void
|
||||
updateVerifyOnly(taskId: string, value: boolean): void
|
||||
updateVerifyRequired(taskId: string, value: SoloVerifyRequired): void
|
||||
|
||||
markPending(taskId: string): void
|
||||
clearPending(taskId: string): void
|
||||
|
||||
setRealtimeStatus(status: RealtimeStatus, showConnectingIndicator: boolean): void
|
||||
|
||||
initJobs(jobs: JobState[]): void
|
||||
handleJobEvent(event: ClaudeJobEvent): void
|
||||
|
||||
setWorkers(count: number): void
|
||||
incrementWorkers(): void
|
||||
decrementWorkers(): void
|
||||
setWorkerQuota(pct: number, checkAt: string): void
|
||||
|
||||
handleRealtimeEvent(event: RealtimeEvent): void
|
||||
ensureWorkspaceLoaded(productId: string, sprintId?: string, requestId?: string): Promise<void>
|
||||
resyncActiveScopes(reason: ResyncReason): Promise<void>
|
||||
}
|
||||
|
||||
export type SoloWorkspaceStore = State & Actions
|
||||
|
||||
const EMPTY_COLUMNS: Record<SoloColumnStatus, string[]> = {
|
||||
TO_DO: [],
|
||||
IN_PROGRESS: [],
|
||||
DONE: [],
|
||||
}
|
||||
|
||||
const initialState: State = {
|
||||
context: {
|
||||
activeProduct: null,
|
||||
activeSprint: null,
|
||||
activeUserId: null,
|
||||
},
|
||||
entities: {
|
||||
tasksById: {},
|
||||
unassignedStoriesById: {},
|
||||
jobsByTaskId: {},
|
||||
},
|
||||
relations: {
|
||||
taskIdsByColumn: EMPTY_COLUMNS,
|
||||
unassignedStoryIds: [],
|
||||
},
|
||||
loading: {
|
||||
loadedProductId: null,
|
||||
loadedSprintId: null,
|
||||
loadingSprintId: null,
|
||||
activeRequestId: null,
|
||||
},
|
||||
sync: {
|
||||
realtimeStatus: 'connecting',
|
||||
showConnectingIndicator: false,
|
||||
lastEventAt: null,
|
||||
lastResyncAt: null,
|
||||
resyncReason: null,
|
||||
},
|
||||
pendingOps: new Set<string>(),
|
||||
tasks: {},
|
||||
unassignedStoriesById: {},
|
||||
claudeJobsByTaskId: {},
|
||||
realtimeStatus: 'connecting',
|
||||
showConnectingIndicator: false,
|
||||
connectedWorkers: 0,
|
||||
workerQuotaPct: null,
|
||||
workerQuotaCheckAt: null,
|
||||
}
|
||||
|
||||
function getColumnStatus(status: SoloTaskStatus): SoloColumnStatus {
|
||||
if (status === 'REVIEW') return 'IN_PROGRESS'
|
||||
return status
|
||||
}
|
||||
|
||||
function compareTask(a: SoloTask, b: SoloTask): number {
|
||||
if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
|
||||
if (a.priority !== b.priority) return a.priority - b.priority
|
||||
const aCode = a.task_code ?? ''
|
||||
const bCode = b.task_code ?? ''
|
||||
const codeCompare = aCode.localeCompare(bCode, 'nl', { numeric: true })
|
||||
if (codeCompare !== 0) return codeCompare
|
||||
return a.id.localeCompare(b.id)
|
||||
}
|
||||
|
||||
function compareUnassignedStory(a: SoloUnassignedStory, b: SoloUnassignedStory): number {
|
||||
const aCode = a.code ?? ''
|
||||
const bCode = b.code ?? ''
|
||||
const codeCompare = aCode.localeCompare(bCode, 'nl', { numeric: true })
|
||||
if (codeCompare !== 0) return codeCompare
|
||||
return a.title.localeCompare(b.title, 'nl', { numeric: true })
|
||||
}
|
||||
|
||||
function buildTaskRelations(tasksById: Record<string, SoloTask>): Record<SoloColumnStatus, string[]> {
|
||||
const next: Record<SoloColumnStatus, string[]> = {
|
||||
TO_DO: [],
|
||||
IN_PROGRESS: [],
|
||||
DONE: [],
|
||||
}
|
||||
const tasks = Object.values(tasksById).sort(compareTask)
|
||||
for (const task of tasks) {
|
||||
next[getColumnStatus(task.status)].push(task.id)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
function buildUnassignedRelations(storiesById: Record<string, SoloUnassignedStory>): string[] {
|
||||
return Object.values(storiesById)
|
||||
.sort(compareUnassignedStory)
|
||||
.map((story) => story.id)
|
||||
}
|
||||
|
||||
function normalizeTask(input: SoloTask): SoloTask {
|
||||
return {
|
||||
...input,
|
||||
status: normalizeTaskStatus(input.status),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTaskStatus(status: string): SoloTaskStatus {
|
||||
if (status === 'IN_PROGRESS' || status === 'REVIEW' || status === 'DONE') return status
|
||||
return 'TO_DO'
|
||||
}
|
||||
|
||||
function mapTasks(tasks: SoloTask[]): Record<string, SoloTask> {
|
||||
return Object.fromEntries(tasks.map((task) => [task.id, normalizeTask(task)]))
|
||||
}
|
||||
|
||||
function mapUnassignedStories(stories: SoloUnassignedStory[]): Record<string, SoloUnassignedStory> {
|
||||
return Object.fromEntries(stories.map((story) => [story.id, story]))
|
||||
}
|
||||
|
||||
function newRequestId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
function taskPatchFromEvent(event: RealtimeEvent): Partial<SoloTask> {
|
||||
const status = event.status ?? event.task_status
|
||||
return {
|
||||
...(status && { status: normalizeTaskStatus(status) }),
|
||||
...((event.sort_order ?? event.task_sort_order) !== undefined && {
|
||||
sort_order: event.sort_order ?? event.task_sort_order,
|
||||
}),
|
||||
...((event.title ?? event.task_title) !== undefined && {
|
||||
title: event.title ?? event.task_title,
|
||||
}),
|
||||
...(event.description !== undefined && { description: event.description }),
|
||||
...(event.priority !== undefined && { priority: event.priority }),
|
||||
...(event.story_id !== undefined && { story_id: event.story_id }),
|
||||
}
|
||||
}
|
||||
|
||||
function storyTitleFromEvent(event: RealtimeEvent): string | undefined {
|
||||
return event.title ?? event.story_title
|
||||
}
|
||||
|
||||
function storyCodeFromEvent(event: RealtimeEvent): string | null | undefined {
|
||||
return event.code ?? event.story_code
|
||||
}
|
||||
|
||||
export const useSoloWorkspaceStore = create<SoloWorkspaceStore>((set, get) => ({
|
||||
...initialState,
|
||||
|
||||
hydrateSnapshot(snapshot) {
|
||||
const tasksById = mapTasks(snapshot.tasks)
|
||||
const unassignedStoriesById = mapUnassignedStories(snapshot.unassignedStories)
|
||||
set((s) => ({
|
||||
context: {
|
||||
activeProduct: snapshot.product,
|
||||
activeSprint: snapshot.sprint,
|
||||
activeUserId: snapshot.activeUserId,
|
||||
},
|
||||
entities: {
|
||||
...s.entities,
|
||||
tasksById,
|
||||
unassignedStoriesById,
|
||||
},
|
||||
relations: {
|
||||
taskIdsByColumn: buildTaskRelations(tasksById),
|
||||
unassignedStoryIds: buildUnassignedRelations(unassignedStoriesById),
|
||||
},
|
||||
loading: {
|
||||
...s.loading,
|
||||
loadedProductId: snapshot.product.id,
|
||||
loadedSprintId: snapshot.sprint.id,
|
||||
loadingSprintId: null,
|
||||
},
|
||||
tasks: tasksById,
|
||||
unassignedStoriesById,
|
||||
}))
|
||||
},
|
||||
|
||||
initTasks(tasks) {
|
||||
const tasksById = mapTasks(tasks)
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: {
|
||||
...s.relations,
|
||||
taskIdsByColumn: buildTaskRelations(tasksById),
|
||||
},
|
||||
tasks: tasksById,
|
||||
}))
|
||||
},
|
||||
|
||||
hydrateUnassignedStories(stories) {
|
||||
const unassignedStoriesById = mapUnassignedStories(stories)
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, unassignedStoriesById },
|
||||
relations: {
|
||||
...s.relations,
|
||||
unassignedStoryIds: buildUnassignedRelations(unassignedStoriesById),
|
||||
},
|
||||
unassignedStoriesById,
|
||||
}))
|
||||
},
|
||||
|
||||
removeUnassignedStory(storyId) {
|
||||
set((s) => {
|
||||
if (!s.entities.unassignedStoriesById[storyId]) return s
|
||||
const unassignedStoriesById = { ...s.entities.unassignedStoriesById }
|
||||
delete unassignedStoriesById[storyId]
|
||||
return {
|
||||
entities: { ...s.entities, unassignedStoriesById },
|
||||
relations: {
|
||||
...s.relations,
|
||||
unassignedStoryIds: buildUnassignedRelations(unassignedStoriesById),
|
||||
},
|
||||
unassignedStoriesById,
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
optimisticMove(taskId, toStatus) {
|
||||
const prev = get().tasks[taskId]?.status ?? null
|
||||
if (!prev) return null
|
||||
const task = { ...get().tasks[taskId], status: toStatus }
|
||||
const tasksById = { ...get().tasks, [taskId]: task }
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: { ...s.relations, taskIdsByColumn: buildTaskRelations(tasksById) },
|
||||
tasks: tasksById,
|
||||
}))
|
||||
return prev
|
||||
},
|
||||
|
||||
rollback(taskId, prevStatus) {
|
||||
const existing = get().tasks[taskId]
|
||||
if (!existing) return
|
||||
const tasksById = { ...get().tasks, [taskId]: { ...existing, status: prevStatus } }
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: { ...s.relations, taskIdsByColumn: buildTaskRelations(tasksById) },
|
||||
tasks: tasksById,
|
||||
}))
|
||||
},
|
||||
|
||||
updatePlan(taskId, plan) {
|
||||
const existing = get().tasks[taskId]
|
||||
if (!existing) return
|
||||
const tasksById = { ...get().tasks, [taskId]: { ...existing, implementation_plan: plan } }
|
||||
set((s) => ({ entities: { ...s.entities, tasksById }, tasks: tasksById }))
|
||||
},
|
||||
|
||||
updateVerifyOnly(taskId, value) {
|
||||
const existing = get().tasks[taskId]
|
||||
if (!existing) return
|
||||
const tasksById = { ...get().tasks, [taskId]: { ...existing, verify_only: value } }
|
||||
set((s) => ({ entities: { ...s.entities, tasksById }, tasks: tasksById }))
|
||||
},
|
||||
|
||||
updateVerifyRequired(taskId, value) {
|
||||
const existing = get().tasks[taskId]
|
||||
if (!existing) return
|
||||
const tasksById = { ...get().tasks, [taskId]: { ...existing, verify_required: value } }
|
||||
set((s) => ({ entities: { ...s.entities, tasksById }, tasks: tasksById }))
|
||||
},
|
||||
|
||||
markPending(taskId) {
|
||||
set((s) => {
|
||||
if (s.pendingOps.has(taskId)) return s
|
||||
const pendingOps = new Set(s.pendingOps)
|
||||
pendingOps.add(taskId)
|
||||
return { pendingOps }
|
||||
})
|
||||
},
|
||||
|
||||
clearPending(taskId) {
|
||||
set((s) => {
|
||||
if (!s.pendingOps.has(taskId)) return s
|
||||
const pendingOps = new Set(s.pendingOps)
|
||||
pendingOps.delete(taskId)
|
||||
return { pendingOps }
|
||||
})
|
||||
},
|
||||
|
||||
setRealtimeStatus(status, showConnectingIndicator) {
|
||||
set((s) => {
|
||||
if (s.realtimeStatus === status && s.showConnectingIndicator === showConnectingIndicator) {
|
||||
return s
|
||||
}
|
||||
return {
|
||||
sync: { ...s.sync, realtimeStatus: status, showConnectingIndicator },
|
||||
realtimeStatus: status,
|
||||
showConnectingIndicator,
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
initJobs(jobs) {
|
||||
const jobsByTaskId = Object.fromEntries(jobs.map((job) => [job.task_id, job]))
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, jobsByTaskId },
|
||||
claudeJobsByTaskId: jobsByTaskId,
|
||||
}))
|
||||
},
|
||||
|
||||
handleJobEvent(event) {
|
||||
const { job_id, task_id } = event
|
||||
if (event.type === 'claude_job_enqueued') {
|
||||
set((s) => {
|
||||
const jobsByTaskId = {
|
||||
...s.claudeJobsByTaskId,
|
||||
[task_id]: { job_id, task_id, status: 'queued' as const },
|
||||
}
|
||||
return {
|
||||
entities: { ...s.entities, jobsByTaskId },
|
||||
claudeJobsByTaskId: jobsByTaskId,
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const { status, branch, pushed_at, pr_url, verify_result, summary, error } = event
|
||||
if (status === 'cancelled') {
|
||||
set((s) => {
|
||||
const jobsByTaskId = { ...s.claudeJobsByTaskId }
|
||||
delete jobsByTaskId[task_id]
|
||||
return {
|
||||
entities: { ...s.entities, jobsByTaskId },
|
||||
claudeJobsByTaskId: jobsByTaskId,
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
set((s) => {
|
||||
const jobsByTaskId = {
|
||||
...s.claudeJobsByTaskId,
|
||||
[task_id]: {
|
||||
job_id,
|
||||
task_id,
|
||||
status,
|
||||
branch,
|
||||
pushed_at,
|
||||
pr_url,
|
||||
verify_result,
|
||||
summary,
|
||||
error,
|
||||
},
|
||||
}
|
||||
return {
|
||||
entities: { ...s.entities, jobsByTaskId },
|
||||
claudeJobsByTaskId: jobsByTaskId,
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
setWorkers(count) {
|
||||
set({ connectedWorkers: Math.max(0, count) })
|
||||
},
|
||||
|
||||
incrementWorkers() {
|
||||
set((s) => ({ connectedWorkers: s.connectedWorkers + 1 }))
|
||||
},
|
||||
|
||||
decrementWorkers() {
|
||||
set((s) => ({
|
||||
connectedWorkers: Math.max(0, s.connectedWorkers - 1),
|
||||
workerQuotaPct: s.connectedWorkers - 1 <= 0 ? null : s.workerQuotaPct,
|
||||
workerQuotaCheckAt: s.connectedWorkers - 1 <= 0 ? null : s.workerQuotaCheckAt,
|
||||
}))
|
||||
},
|
||||
|
||||
setWorkerQuota(pct, checkAt) {
|
||||
set({ workerQuotaPct: pct, workerQuotaCheckAt: checkAt })
|
||||
},
|
||||
|
||||
handleRealtimeEvent(event) {
|
||||
set((s) => ({ sync: { ...s.sync, lastEventAt: Date.now() } }))
|
||||
|
||||
const ctx = get().context
|
||||
if (ctx.activeProduct?.id && event.product_id !== ctx.activeProduct.id) return
|
||||
|
||||
if (event.entity === 'task') {
|
||||
if (event.op === 'D') {
|
||||
const existing = get().tasks[event.id]
|
||||
if (!existing) return
|
||||
const tasksById = { ...get().tasks }
|
||||
delete tasksById[event.id]
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: { ...s.relations, taskIdsByColumn: buildTaskRelations(tasksById) },
|
||||
tasks: tasksById,
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
const existing = get().tasks[event.id]
|
||||
if (!existing) {
|
||||
if (
|
||||
event.assignee_id === ctx.activeUserId &&
|
||||
event.sprint_id === ctx.activeSprint?.id
|
||||
) {
|
||||
void get().resyncActiveScopes('unknown-event')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
event.assignee_id !== null &&
|
||||
ctx.activeUserId &&
|
||||
event.assignee_id !== ctx.activeUserId
|
||||
) {
|
||||
const tasksById = { ...get().tasks }
|
||||
delete tasksById[event.id]
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: { ...s.relations, taskIdsByColumn: buildTaskRelations(tasksById) },
|
||||
tasks: tasksById,
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
if (get().pendingOps.has(event.id)) return
|
||||
|
||||
const patch = taskPatchFromEvent(event)
|
||||
if (Object.keys(patch).length === 0) return
|
||||
const tasksById = {
|
||||
...get().tasks,
|
||||
[event.id]: { ...existing, ...patch },
|
||||
}
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: { ...s.relations, taskIdsByColumn: buildTaskRelations(tasksById) },
|
||||
tasks: tasksById,
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
if (event.op === 'D') {
|
||||
const tasksById = Object.fromEntries(
|
||||
Object.entries(get().tasks).filter(([, task]) => task.story_id !== event.id),
|
||||
)
|
||||
const unassignedStoriesById = { ...get().entities.unassignedStoriesById }
|
||||
delete unassignedStoriesById[event.id]
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById, unassignedStoriesById },
|
||||
relations: {
|
||||
taskIdsByColumn: buildTaskRelations(tasksById),
|
||||
unassignedStoryIds: buildUnassignedRelations(unassignedStoriesById),
|
||||
},
|
||||
tasks: tasksById,
|
||||
unassignedStoriesById,
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
const affectedIds = Object.entries(get().tasks)
|
||||
.filter(([, task]) => task.story_id === event.id)
|
||||
.map(([taskId]) => taskId)
|
||||
const newTitle = storyTitleFromEvent(event)
|
||||
const newCode = storyCodeFromEvent(event)
|
||||
|
||||
if (affectedIds.length > 0 && (newTitle !== undefined || newCode !== undefined)) {
|
||||
const tasksById = { ...get().tasks }
|
||||
for (const taskId of affectedIds) {
|
||||
const task = tasksById[taskId]
|
||||
tasksById[taskId] = {
|
||||
...task,
|
||||
...(newTitle !== undefined && { story_title: newTitle }),
|
||||
...(newCode !== undefined && { story_code: newCode }),
|
||||
}
|
||||
}
|
||||
set((s) => ({
|
||||
entities: { ...s.entities, tasksById },
|
||||
relations: { ...s.relations, taskIdsByColumn: buildTaskRelations(tasksById) },
|
||||
tasks: tasksById,
|
||||
}))
|
||||
}
|
||||
|
||||
if (
|
||||
event.sprint_id === ctx.activeSprint?.id &&
|
||||
(event.assignee_id === null || event.assignee_id === ctx.activeUserId)
|
||||
) {
|
||||
void get().resyncActiveScopes('unknown-event')
|
||||
}
|
||||
},
|
||||
|
||||
async ensureWorkspaceLoaded(productId, sprintId, requestId) {
|
||||
const activeRequestId = requestId ?? newRequestId()
|
||||
set((s) => ({
|
||||
loading: {
|
||||
...s.loading,
|
||||
loadingSprintId: sprintId ?? s.context.activeSprint?.id ?? null,
|
||||
activeRequestId,
|
||||
},
|
||||
}))
|
||||
try {
|
||||
const params = sprintId ? `?sprint_id=${encodeURIComponent(sprintId)}` : ''
|
||||
const snapshot = await fetchJson<SoloWorkspaceSnapshot | null>(
|
||||
`/api/products/${encodeURIComponent(productId)}/solo-workspace${params}`,
|
||||
)
|
||||
if (get().loading.activeRequestId !== activeRequestId) return
|
||||
if (!snapshot) return
|
||||
get().hydrateSnapshot(snapshot)
|
||||
} finally {
|
||||
set((s) => ({
|
||||
loading: {
|
||||
...s.loading,
|
||||
loadingSprintId:
|
||||
s.loading.activeRequestId === activeRequestId ? null : s.loading.loadingSprintId,
|
||||
},
|
||||
}))
|
||||
}
|
||||
},
|
||||
|
||||
async resyncActiveScopes(reason) {
|
||||
const ctx = get().context
|
||||
if (!ctx.activeProduct?.id) return
|
||||
set((s) => ({
|
||||
sync: { ...s.sync, lastResyncAt: Date.now(), resyncReason: reason },
|
||||
}))
|
||||
await get().ensureWorkspaceLoaded(ctx.activeProduct.id, ctx.activeSprint?.id)
|
||||
},
|
||||
}))
|
||||
123
stores/solo-workspace/types.ts
Normal file
123
stores/solo-workspace/types.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import type { ClaudeJobStatusApi } from '@/lib/job-status'
|
||||
|
||||
export type SoloTaskStatus = 'TO_DO' | 'IN_PROGRESS' | 'REVIEW' | 'DONE'
|
||||
export type SoloColumnStatus = 'TO_DO' | 'IN_PROGRESS' | 'DONE'
|
||||
export type SoloVerifyRequired = 'ALIGNED' | 'ALIGNED_OR_PARTIAL' | 'ANY'
|
||||
export type VerifyResultApi = 'aligned' | 'partial' | 'empty' | 'divergent'
|
||||
|
||||
export interface SoloTask {
|
||||
id: string
|
||||
title: string
|
||||
description: string | null
|
||||
implementation_plan: string | null
|
||||
priority: number
|
||||
sort_order: number
|
||||
status: SoloTaskStatus
|
||||
verify_only: boolean
|
||||
verify_required: SoloVerifyRequired
|
||||
story_id: string
|
||||
story_code: string | null
|
||||
story_title: string
|
||||
task_code: string | null
|
||||
pbi_code: string | null
|
||||
pbi_title: string | null
|
||||
pbi_description: string | null
|
||||
}
|
||||
|
||||
export interface SoloUnassignedStoryTask {
|
||||
id: string
|
||||
title: string
|
||||
description: string | null
|
||||
priority: number
|
||||
status: string
|
||||
}
|
||||
|
||||
export interface SoloUnassignedStory {
|
||||
id: string
|
||||
code: string | null
|
||||
title: string
|
||||
tasks: SoloUnassignedStoryTask[]
|
||||
}
|
||||
|
||||
export interface SoloWorkspaceProduct {
|
||||
id: string
|
||||
name: string
|
||||
repo_url?: string | null
|
||||
}
|
||||
|
||||
export interface SoloWorkspaceSprint {
|
||||
id: string
|
||||
sprint_goal: string
|
||||
}
|
||||
|
||||
export interface SoloWorkspaceSnapshot {
|
||||
product: SoloWorkspaceProduct
|
||||
sprint: SoloWorkspaceSprint
|
||||
activeUserId: string
|
||||
tasks: SoloTask[]
|
||||
unassignedStories: SoloUnassignedStory[]
|
||||
}
|
||||
|
||||
export interface JobState {
|
||||
job_id: string
|
||||
task_id: string
|
||||
status: ClaudeJobStatusApi
|
||||
branch?: string
|
||||
pushed_at?: string | null
|
||||
pr_url?: string | null
|
||||
verify_result?: VerifyResultApi | null
|
||||
summary?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type ClaudeJobEvent =
|
||||
| {
|
||||
type: 'claude_job_enqueued'
|
||||
job_id: string
|
||||
task_id: string
|
||||
user_id: string
|
||||
product_id: string
|
||||
status: 'queued'
|
||||
}
|
||||
| {
|
||||
type: 'claude_job_status'
|
||||
job_id: string
|
||||
task_id: string
|
||||
user_id: string
|
||||
product_id: string
|
||||
status: ClaudeJobStatusApi
|
||||
branch?: string
|
||||
pushed_at?: string
|
||||
pr_url?: string
|
||||
verify_result?: VerifyResultApi
|
||||
summary?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface RealtimeEvent {
|
||||
op: 'I' | 'U' | 'D'
|
||||
entity: 'task' | 'story'
|
||||
id: string
|
||||
story_id?: string
|
||||
product_id: string
|
||||
sprint_id: string | null
|
||||
assignee_id: string | null
|
||||
status?: SoloTaskStatus | 'OPEN' | 'IN_SPRINT' | 'DONE'
|
||||
sort_order?: number
|
||||
title?: string
|
||||
code?: string | null
|
||||
description?: string | null
|
||||
priority?: number
|
||||
task_status?: SoloTaskStatus
|
||||
task_sort_order?: number
|
||||
task_title?: string
|
||||
story_status?: 'OPEN' | 'IN_SPRINT' | 'DONE'
|
||||
story_sort_order?: number
|
||||
story_title?: string
|
||||
story_code?: string | null
|
||||
changed_fields?: string[]
|
||||
}
|
||||
|
||||
export type RealtimeStatus = 'connecting' | 'open' | 'disconnected'
|
||||
|
||||
export type ResyncReason = 'visible' | 'reconnect' | 'manual' | 'unknown-event'
|
||||
|
|
@ -21,6 +21,12 @@ import {
|
|||
writeStoryHint,
|
||||
writeTaskHint,
|
||||
} from './restore'
|
||||
import {
|
||||
normalizeSprintTask,
|
||||
normalizeSprintWorkspaceSnapshot,
|
||||
normalizeStoryStatusForStore,
|
||||
normalizeTaskStatusForStore,
|
||||
} from '@/stores/workspace-status-adapter'
|
||||
|
||||
interface ContextSlice {
|
||||
activeProduct: ActiveProductRef | null
|
||||
|
|
@ -180,7 +186,8 @@ export const useSprintWorkspaceStore = create<SprintWorkspaceStore>()(
|
|||
immer((set, get) => ({
|
||||
...initialState,
|
||||
|
||||
hydrateSnapshot(snapshot) {
|
||||
hydrateSnapshot(inputSnapshot) {
|
||||
const snapshot = normalizeSprintWorkspaceSnapshot(inputSnapshot)
|
||||
set((s) => {
|
||||
if (snapshot.product) s.context.activeProduct = snapshot.product
|
||||
|
||||
|
|
@ -387,8 +394,9 @@ export const useSprintWorkspaceStore = create<SprintWorkspaceStore>()(
|
|||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!Array.isArray(tasks)) return
|
||||
const normalizedTasks = tasks.map(normalizeSprintTask)
|
||||
set((s) => {
|
||||
for (const task of tasks) {
|
||||
for (const task of normalizedTasks) {
|
||||
const existing = s.entities.tasksById[task.id]
|
||||
if (existing && isDetail(existing)) {
|
||||
s.entities.tasksById[task.id] = { ...existing, ...task }
|
||||
|
|
@ -396,7 +404,7 @@ export const useSprintWorkspaceStore = create<SprintWorkspaceStore>()(
|
|||
s.entities.tasksById[task.id] = task
|
||||
}
|
||||
}
|
||||
s.relations.taskIdsByStory[storyId] = [...tasks]
|
||||
s.relations.taskIdsByStory[storyId] = [...normalizedTasks]
|
||||
.sort(compareTask)
|
||||
.map((t) => t.id)
|
||||
s.loading.loadedStoryIds[storyId] = true
|
||||
|
|
@ -409,8 +417,9 @@ export const useSprintWorkspaceStore = create<SprintWorkspaceStore>()(
|
|||
)
|
||||
if (requestId && get().loading.activeRequestId !== requestId) return
|
||||
if (!detail || typeof detail !== 'object') return
|
||||
const normalizedDetail = normalizeSprintTask(detail)
|
||||
set((s) => {
|
||||
s.entities.tasksById[taskId] = { ...detail, _detail: true }
|
||||
s.entities.tasksById[taskId] = { ...normalizedDetail, _detail: true }
|
||||
s.loading.loadedTaskIds[taskId] = true
|
||||
})
|
||||
},
|
||||
|
|
@ -839,16 +848,58 @@ function sanitizeSprintPayload(p: Record<string, unknown>): Partial<SprintWorksp
|
|||
}
|
||||
|
||||
function sanitizeStoryPayload(p: Record<string, unknown>): Partial<SprintWorkspaceStory> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
const {
|
||||
entity: _e,
|
||||
op: _o,
|
||||
story_status,
|
||||
story_sort_order,
|
||||
story_title,
|
||||
story_code,
|
||||
...rest
|
||||
} = p
|
||||
void _e
|
||||
void _o
|
||||
if (rest.status === undefined && typeof story_status === 'string') {
|
||||
rest.status = story_status
|
||||
}
|
||||
if (rest.sort_order === undefined && typeof story_sort_order === 'number') {
|
||||
rest.sort_order = story_sort_order
|
||||
}
|
||||
if (rest.title === undefined && typeof story_title === 'string') {
|
||||
rest.title = story_title
|
||||
}
|
||||
if (rest.code === undefined && (typeof story_code === 'string' || story_code === null)) {
|
||||
rest.code = story_code
|
||||
}
|
||||
if (typeof rest.status === 'string') {
|
||||
rest.status = normalizeStoryStatusForStore(rest.status)
|
||||
}
|
||||
return rest as Partial<SprintWorkspaceStory>
|
||||
}
|
||||
|
||||
function sanitizeTaskPayload(p: Record<string, unknown>): Partial<SprintWorkspaceTask> {
|
||||
const { entity: _e, op: _o, ...rest } = p
|
||||
const {
|
||||
entity: _e,
|
||||
op: _o,
|
||||
task_status,
|
||||
task_sort_order,
|
||||
task_title,
|
||||
...rest
|
||||
} = p
|
||||
void _e
|
||||
void _o
|
||||
if (rest.status === undefined && typeof task_status === 'string') {
|
||||
rest.status = task_status
|
||||
}
|
||||
if (rest.sort_order === undefined && typeof task_sort_order === 'number') {
|
||||
rest.sort_order = task_sort_order
|
||||
}
|
||||
if (rest.title === undefined && typeof task_title === 'string') {
|
||||
rest.title = task_title
|
||||
}
|
||||
if (typeof rest.status === 'string') {
|
||||
rest.status = normalizeTaskStatusForStore(rest.status)
|
||||
}
|
||||
return rest as Partial<SprintWorkspaceTask>
|
||||
}
|
||||
|
||||
|
|
@ -881,15 +932,19 @@ function coerceStoryPayload(
|
|||
id: string,
|
||||
p: Record<string, unknown>,
|
||||
): SprintWorkspaceStory {
|
||||
const status = p.status ?? p.story_status ?? 'OPEN'
|
||||
const sortOrder = p.sort_order ?? p.story_sort_order ?? 0
|
||||
const title = p.title ?? p.story_title ?? ''
|
||||
const code = p.code ?? p.story_code ?? null
|
||||
return {
|
||||
id,
|
||||
code: (p.code as string | null) ?? null,
|
||||
title: String(p.title ?? ''),
|
||||
code: (code as string | null) ?? null,
|
||||
title: String(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'),
|
||||
sort_order: Number(sortOrder),
|
||||
status: normalizeStoryStatusForStore(String(status)),
|
||||
pbi_id: String(p.pbi_id ?? ''),
|
||||
sprint_id: (p.sprint_id as string | null | undefined) ?? null,
|
||||
created_at:
|
||||
|
|
@ -900,14 +955,17 @@ function coerceStoryPayload(
|
|||
}
|
||||
|
||||
function coerceTaskPayload(id: string, p: Record<string, unknown>): SprintWorkspaceTask {
|
||||
const status = p.status ?? p.task_status ?? 'TO_DO'
|
||||
const sortOrder = p.sort_order ?? p.task_sort_order ?? 0
|
||||
const title = p.title ?? p.task_title ?? ''
|
||||
return {
|
||||
id,
|
||||
code: (p.code as string | null) ?? null,
|
||||
title: String(p.title ?? ''),
|
||||
title: String(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'),
|
||||
sort_order: Number(sortOrder),
|
||||
status: normalizeTaskStatusForStore(String(status)),
|
||||
story_id: String(p.story_id ?? ''),
|
||||
sprint_id: (p.sprint_id as string | null | undefined) ?? null,
|
||||
created_at:
|
||||
|
|
|
|||
88
stores/workspace-status-adapter.ts
Normal file
88
stores/workspace-status-adapter.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import {
|
||||
pbiStatusFromApi,
|
||||
pbiStatusToApi,
|
||||
storyStatusFromApi,
|
||||
taskStatusFromApi,
|
||||
} from '@/lib/task-status'
|
||||
import type {
|
||||
BacklogPbi,
|
||||
BacklogStory,
|
||||
BacklogTask,
|
||||
ProductBacklogSnapshot,
|
||||
TaskDetail,
|
||||
} from '@/stores/product-workspace/types'
|
||||
import type {
|
||||
SprintWorkspaceSnapshot,
|
||||
SprintWorkspaceStory,
|
||||
SprintWorkspaceTask,
|
||||
SprintWorkspaceTaskDetail,
|
||||
} from '@/stores/sprint-workspace/types'
|
||||
|
||||
export function normalizePbiStatusForStore(status: string): BacklogPbi['status'] {
|
||||
const dbStatus = pbiStatusFromApi(status)
|
||||
return dbStatus ? pbiStatusToApi(dbStatus) : (status as BacklogPbi['status'])
|
||||
}
|
||||
|
||||
export function normalizeStoryStatusForStore(status: string): string {
|
||||
return storyStatusFromApi(status) ?? status
|
||||
}
|
||||
|
||||
export function normalizeTaskStatusForStore(status: string): string {
|
||||
return taskStatusFromApi(status) ?? status
|
||||
}
|
||||
|
||||
export function normalizeBacklogPbi<T extends BacklogPbi>(pbi: T): T {
|
||||
const status = normalizePbiStatusForStore(pbi.status)
|
||||
return status === pbi.status ? pbi : { ...pbi, status }
|
||||
}
|
||||
|
||||
export function normalizeBacklogStory<T extends BacklogStory>(story: T): T {
|
||||
const status = normalizeStoryStatusForStore(story.status)
|
||||
return status === story.status ? story : { ...story, status }
|
||||
}
|
||||
|
||||
export function normalizeBacklogTask<T extends BacklogTask | TaskDetail>(task: T): T {
|
||||
const status = normalizeTaskStatusForStore(task.status)
|
||||
return status === task.status ? task : { ...task, status }
|
||||
}
|
||||
|
||||
export function normalizeSprintStory<T extends SprintWorkspaceStory>(story: T): T {
|
||||
const status = normalizeStoryStatusForStore(story.status)
|
||||
return status === story.status ? story : { ...story, status }
|
||||
}
|
||||
|
||||
export function normalizeSprintTask<T extends SprintWorkspaceTask | SprintWorkspaceTaskDetail>(
|
||||
task: T,
|
||||
): T {
|
||||
const status = normalizeTaskStatusForStore(task.status)
|
||||
return status === task.status ? task : { ...task, status }
|
||||
}
|
||||
|
||||
export function normalizeProductBacklogSnapshot(
|
||||
snapshot: ProductBacklogSnapshot,
|
||||
): ProductBacklogSnapshot {
|
||||
return {
|
||||
...snapshot,
|
||||
pbis: snapshot.pbis.map(normalizeBacklogPbi),
|
||||
storiesByPbi: mapRecordLists(snapshot.storiesByPbi, normalizeBacklogStory),
|
||||
tasksByStory: mapRecordLists(snapshot.tasksByStory, normalizeBacklogTask),
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeSprintWorkspaceSnapshot(
|
||||
snapshot: SprintWorkspaceSnapshot,
|
||||
): SprintWorkspaceSnapshot {
|
||||
return {
|
||||
...snapshot,
|
||||
stories: snapshot.stories.map(normalizeSprintStory),
|
||||
tasksByStory: mapRecordLists(snapshot.tasksByStory, normalizeSprintTask),
|
||||
}
|
||||
}
|
||||
|
||||
function mapRecordLists<T>(record: Record<string, T[]>, normalize: (item: T) => T): Record<string, T[]> {
|
||||
const next: Record<string, T[]> = {}
|
||||
for (const [id, list] of Object.entries(record)) {
|
||||
next[id] = list.map(normalize)
|
||||
}
|
||||
return next
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue