Scrum4Me/components/ideas/idea-timeline.tsx
Janpeter Visser d84cdf664f
feat(PBI-67): IDEA_REVIEW_PLAN — iterative multi-model plan review (#199)
* feat(ideas): upload-plan knop — short-circuit van Make-Plan AI-flow

Voegt een 'Upload plan' knop toe in idea-row-actions (verschijnt in zowel
list als idea-detail). Klik → file picker → kies .md → server-side parse +
opslaan; idea-status springt naar PLAN_READY. Vandaaruit de bestaande
'Maak PBI' knop voor materialize.

Server (uploadPlanMdAction):
- Toegestaan vanuit DRAFT, GRILLED, PLAN_FAILED, PLAN_READY
- DRAFT → skip-grill: status gaat direct naar PLAN_READY
- PLAN_READY overschrijft het bestaande plan (consistent met
  updatePlanMdAction, geen confirmation)
- Geblokkeerd in GRILLING/PLANNING (job loopt), PLANNED (al gematerialiseerd)
- Parse-failure → 422 + details (NIET opslaan, zodat een onparseerbaar plan
  nooit in de DB belandt)
- Empty / >100k chars → 422
- Schrijft IdeaLog NOTE met from_status + length
- Rate-limit + demo-guard + ownership-check via loadOwnedIdea (zelfde
  patroon als updatePlanMdAction)

UI (idea-row-actions.tsx):
- Hidden <input type=file accept=".md,.markdown,text/markdown,text/plain">
- FileReader → text → action
- Toast bij success + router.refresh()
- Blocked-tooltip in andere statussen

Tests: 10 nieuwe in __tests__/actions/ideas-crud.test.ts dekkend voor:
happy paths (DRAFT/GRILLED/PLAN_READY-overwrite/PLAN_FAILED), blocks
(PLANNED/GRILLING), validation (empty/oversized/parse-fail), 404.
Full suite groen: 849/849.

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

* Add reviews for Bootstrap-wizard plans v3.2 to v3.4

- Review v3.2: Addressed executor model, fire-and-forget issues, and PAT handling.
- Review v3.3: Improved transaction handling, stale recovery, and ID generation.
- Review v3.4: Finalized GitHub permissions, catalog versioning, and E2E verification queries.
- Updated recommendations for each version to enhance implementation readiness.

* docs(plans): M8 bootstrap-wizard upload-variant v1.4 — backtick-paden

Upload-variant van het volledige technische plan (docs/plans/M8-bootstrap-wizard.md),
bedoeld voor de "Upload plan"-functie. Genereert 1 PBI + 4 Stories + 22 Tasks
via materializeIdeaPlanAction.

v1.4-aanpassingen tov eerdere generatie-iteratie:
- Alle bestandspaden in implementation_plan in backticks (path-extractor matchen)
- Expliciete "Bestanden:" blok per task vóór de stappen
- Alle tasks op verify_required: ALIGNED_OR_PARTIAL (was deels ALIGNED — te strict
  voor ADR-stubs en multi-file edits)

Fixt forward-only: T-963 cancelled_by_self door DIVERGENT verifier-verdict.
Re-upload van dit bestand produceert tasks die door verify_task_against_plan
als ALIGNED of PARTIAL geclassificeerd kunnen worden.

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

* PBI-67: Add review-plan support to Idea model and job config

- Add plan_review_log and reviewed_at fields to Idea model
- Add REVIEWING_PLAN, PLAN_REVIEW_FAILED, PLAN_REVIEWED to IdeaStatus enum
- Add IDEA_REVIEW_PLAN to ClaudeJobKind enum
- Add IDEA_REVIEW_PLAN config to job-config.ts with model=opus, thinking_budget=6000
- Create migration record for schema changes (applied via db push)

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* PBI-67 Phase 2: Add update-idea-plan-reviewed MCP tool

- Create src/tools/update-idea-plan-reviewed.ts: saves review-log and transitions idea status to PLAN_REVIEWED
- Add PLAN_REVIEW_RESULT to IdeaLogType enum (both repos)
- Register tool in src/index.ts
- Update Prisma schemas (both repos): add plan_review_log and reviewed_at fields to Idea model
- Add REVIEWING_PLAN, PLAN_REVIEW_FAILED, PLAN_REVIEWED to IdeaStatus enum (MCP schema)
- Add IDEA_REVIEW_PLAN to ClaudeJobKind enum (MCP schema)
- Tool includes transaction safety and convergence metrics logging

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* feat(PBI-67): IDEA_REVIEW_PLAN Phases 3-6 — server actions, UI components, prompt & tests

- Phase 3: startReviewPlanJobAction, cancelIdeaJobAction, status transitions
  (REVIEWING_PLAN / PLAN_REVIEWED / PLAN_REVIEW_FAILED), status colors,
  job-card/jobs-column filters, idea-list status tabs
- Phase 4: review-plan-job.md prompt (multi-model orchestration with codex
  injection + active plan revision via update_idea_plan_md after each round),
  runbook, 13 unit tests
- Phase 5: ReviewLogViewer component (rounds, convergence, approval, issues),
  idea-detail integration, proper ReviewLog TypeScript types exported from component
- Phase 6.1: wait-for-job discriminator wired (IDEA_REVIEW_PLAN), plan-revision
  step made mandatory in prompt (was previously optional/missing)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 03:35:02 +02:00

347 lines
12 KiB
TypeScript

'use client'
// IdeaTimeline — chronologische merge van IdeaLog + ClaudeQuestion + UserQuestion entries.
// Server-component zou ook kunnen, maar we mounten dit binnen de client-side
// detail-layout dus client is simpler (geen rsc-boundary doorbreken).
//
// Iconen + kleur per log-type voor snelle herkenning.
// Open ClaudeQuestions krijgen een inline answer-form (M11).
// PBI-33: UserQuestions tonen vraag + (indien beantwoord) Claude's antwoord.
// Onderaan: UserChatInput om nieuwe vraag te stellen (alleen als plan_md aanwezig is).
import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import {
CheckCircle2,
ClipboardList,
FileText,
HelpCircle,
Lightbulb,
MessageCircle,
RefreshCw,
StickyNote,
Wrench,
} from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { debugProps } from '@/lib/debug'
import { answerQuestion } from '@/actions/questions'
import { UserChatInput } from '@/components/ideas/user-chat-input'
import type { IdeaLogType } from '@prisma/client'
export interface TimelineLog {
id: string
type: string
content: string
metadata: unknown
created_at: string
}
export interface TimelineQuestion {
id: string
question: string
options: string[] | null
status: 'open' | 'answered' | 'cancelled' | 'expired'
answer: string | null
created_at: string
expires_at: string
}
export interface TimelineUserQuestion {
id: string
question: string
answer: string | null
status: 'pending' | 'answered'
created_at: string
}
interface Props {
logs: TimelineLog[]
questions: TimelineQuestion[]
userQuestions: TimelineUserQuestion[]
planMd: string | null
ideaId: string
isDemo?: boolean
}
const LOG_ICON: Record<IdeaLogType, React.ReactNode> = {
DECISION: <Lightbulb className="size-4" />,
NOTE: <StickyNote className="size-4" />,
GRILL_RESULT: <FileText className="size-4" />,
PLAN_RESULT: <ClipboardList className="size-4" />,
PLAN_REVIEW_RESULT: <CheckCircle2 className="size-4" />,
STATUS_CHANGE: <RefreshCw className="size-4" />,
JOB_EVENT: <Wrench className="size-4" />,
}
const LOG_LABEL: Record<IdeaLogType, string> = {
DECISION: 'Beslissing',
NOTE: 'Notitie',
GRILL_RESULT: 'Grill-resultaat',
PLAN_RESULT: 'Plan-resultaat',
PLAN_REVIEW_RESULT: 'Plan-beoordeeling',
STATUS_CHANGE: 'Status',
JOB_EVENT: 'Job-event',
}
const QUESTION_STATUS_LABEL: Record<TimelineQuestion['status'], string> = {
open: 'Open',
answered: 'Beantwoord',
cancelled: 'Geannuleerd',
expired: 'Verlopen',
}
const USER_QUESTION_STATUS_LABEL: Record<TimelineUserQuestion['status'], string> = {
pending: 'In behandeling',
answered: 'Beantwoord',
}
export function IdeaTimeline({
logs,
questions,
userQuestions,
planMd,
ideaId,
isDemo = false,
}: Props) {
const merged = [
...logs.map((l) => ({
kind: 'log' as const,
created_at: l.created_at,
data: l,
})),
...questions.map((q) => ({
kind: 'question' as const,
created_at: q.created_at,
data: q,
})),
...userQuestions.map((uq) => ({
kind: 'user_question' as const,
created_at: uq.created_at,
data: uq,
})),
].sort((a, b) => (a.created_at < b.created_at ? 1 : -1))
const showChatInput = planMd !== null
return (
<div className="space-y-4" {...debugProps('idea-timeline', 'IdeaTimeline', 'components/ideas/idea-timeline.tsx')}>
{merged.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center italic">
Nog geen activiteit op dit idee.
</p>
) : (
<ol className="border-l-2 border-input pl-4 space-y-3 ml-2" data-debug-id="idea-timeline__items">
{merged.map((entry, i) => {
// Expliciete locale + format om SSR/CSR hydration-mismatch te voorkomen
// (server-locale verschilde van browser-locale).
const time = new Date(entry.created_at).toLocaleString('nl-NL', {
dateStyle: 'short',
timeStyle: 'short',
})
if (entry.kind === 'log') {
const type = entry.data.type as IdeaLogType
return (
<li key={`l-${entry.data.id}`} className="relative">
<span className="absolute -left-[26px] top-1 flex size-5 items-center justify-center rounded-full bg-surface-container text-muted-foreground">
{LOG_ICON[type] ?? <StickyNote className="size-4" />}
</span>
<div className="rounded-md border border-input bg-surface-container p-3 space-y-1">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium uppercase tracking-wide">
{LOG_LABEL[type] ?? type}
</span>
<span>·</span>
<time>{time}</time>
</div>
<p className="text-sm whitespace-pre-wrap">{entry.data.content}</p>
{entry.data.metadata != null &&
typeof entry.data.metadata === 'object' &&
Object.keys(entry.data.metadata as object).length > 0 ? (
<details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">metadata</summary>
<pre className="mt-1 whitespace-pre-wrap font-mono text-[10px]">
{JSON.stringify(entry.data.metadata, null, 2)}
</pre>
</details>
) : null}
</div>
</li>
)
}
if (entry.kind === 'question') {
const q = entry.data
return (
<li key={`q-${q.id}-${i}`} className="relative">
<span className="absolute -left-[26px] top-1 flex size-5 items-center justify-center rounded-full bg-surface-container text-status-review">
<HelpCircle className="size-4" />
</span>
<div className="rounded-md border border-input bg-surface-container p-3 space-y-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium uppercase tracking-wide">Vraag</span>
<span>·</span>
<span>{QUESTION_STATUS_LABEL[q.status]}</span>
<span>·</span>
<time>{time}</time>
</div>
<p className="text-sm">{q.question}</p>
{q.status === 'open' ? (
<AnswerForm questionId={q.id} options={q.options} />
) : (
<>
{q.options && q.options.length > 0 ? (
<ul className="text-xs text-muted-foreground list-disc list-inside">
{q.options.map((o, ii) => (
<li key={ii}>{o}</li>
))}
</ul>
) : null}
{q.answer ? (
<p className="text-sm border-l-2 border-primary pl-2 text-foreground">
<span className="text-xs font-medium uppercase tracking-wide text-primary mr-2">
Antwoord
</span>
{q.answer}
</p>
) : null}
</>
)}
</div>
</li>
)
}
// user_question — gebruiker stelt vraag aan Claude (PBI-33 PLAN_CHAT)
const uq = entry.data
return (
<li key={`uq-${uq.id}`} className="relative">
<span className="absolute -left-[26px] top-1 flex size-5 items-center justify-center rounded-full bg-surface-container text-primary">
<MessageCircle className="size-4" />
</span>
<div className="rounded-md border border-input bg-surface-container p-3 space-y-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="font-medium uppercase tracking-wide">Jouw vraag</span>
<span>·</span>
<span>{USER_QUESTION_STATUS_LABEL[uq.status]}</span>
<span>·</span>
<time>{time}</time>
</div>
<p className="text-sm whitespace-pre-wrap">{uq.question}</p>
{uq.status === 'pending' ? (
<p className="text-xs text-muted-foreground italic">
Claude denkt na
</p>
) : uq.answer ? (
<div className="border-l-2 border-primary pl-2">
<span className="text-xs font-medium uppercase tracking-wide text-primary">
Antwoord van Claude
</span>
<p className="text-sm whitespace-pre-wrap text-foreground mt-1">
{uq.answer}
</p>
</div>
) : null}
</div>
</li>
)
})}
</ol>
)}
{showChatInput && <UserChatInput ideaId={ideaId} isDemo={isDemo} />}
</div>
)
}
// ---------------------------------------------------------------------------
// AnswerForm — inline antwoord op een open Claude-vraag.
// Voor multi-choice (options): knoppen die direct submitten met de gekozen
// optie. Anders: textarea + Submit knop.
function AnswerForm({
questionId,
options,
}: {
questionId: string
options: string[] | null
}) {
const router = useRouter()
const [text, setText] = useState('')
const [pending, startTransition] = useTransition()
function submit(answer: string) {
const trimmed = answer.trim()
if (!trimmed) {
toast.error('Antwoord mag niet leeg zijn')
return
}
startTransition(async () => {
const r = await answerQuestion(questionId, trimmed)
if (!r.ok) {
toast.error(r.error)
return
}
toast.success('Antwoord verzonden — agent gaat door.')
setText('')
router.refresh()
})
}
if (options && options.length > 0) {
return (
<div className="flex flex-col gap-1.5 pt-1">
{options.map((opt, i) => (
<Button
key={i}
size="sm"
variant="outline"
className="justify-start text-left h-auto py-2 whitespace-normal"
disabled={pending}
onClick={() => submit(opt)}
>
{opt}
</Button>
))}
<details className="text-xs text-muted-foreground pt-1">
<summary className="cursor-pointer">Of typ een eigen antwoord</summary>
<div className="space-y-2 pt-2">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
rows={3}
placeholder="Eigen antwoord…"
disabled={pending}
/>
<div className="flex justify-end">
<Button size="sm" disabled={pending || !text.trim()} onClick={() => submit(text)}>
Verzend
</Button>
</div>
</div>
</details>
</div>
)
}
return (
<div className="space-y-2 pt-1">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
rows={3}
placeholder="Antwoord…"
disabled={pending}
/>
<div className="flex justify-end">
<Button size="sm" disabled={pending || !text.trim()} onClick={() => submit(text)}>
Verzend
</Button>
</div>
</div>
)
}