Zum Inhalt

V2 Frontend — Screen Flow Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Implement the complete V2 screen flow: Screen 0 (Meine Werke) → Screen 1 (Narrativ-Detail) → Screen 2 (Analyse-Ergebnis) → Screen 3 (Wirkgefüge-Vorschlag) → Screen 4 (CausalModel-Detail).

Architecture: New entry point MeineWerke (Screen 0) replaces the old /narrative route. New NarrativeDetail (Screen 1) is a focused read-view for one narrative: scenes, actors, claims, Analysieren button. Existing Screen 2 and Screen 3 pages stay largely the same. Screen 4 (CausalModelEditor) gets URL-param-driven model loading and uses linked_narratives directly from the API. Navigation is flow-driven — no global nav bar needed.

Tech Stack: React 18, TypeScript, react-router-dom v6, Vite, Vitest + Testing Library, design tokens via CSS custom properties


File Map

File Change
frontend/src/lib/api.ts Update Claim interface (add label, status, wirkgefuege_ref); add getClaims; add updateSlot
frontend/src/pages/MeineWerke.tsx Create — Screen 0, narrative list + create + import
frontend/src/pages/MeineWerke.test.tsx Create — renders cards, navigates on click
frontend/src/pages/NarrativeDetail.tsx Create — Screen 1, single narrative with scenes/actors/claims + Analysieren
frontend/src/pages/NarrativeDetail.test.tsx Create — renders title, scenes, claims, Analysieren button
frontend/src/App.tsx Update routing: / → MeineWerke, /narrative/:id → NarrativeDetail, /causal-model/:id → CausalModelEditor
frontend/src/pages/NarrativeAnalyse.tsx Save confirmed actor to DB (POST /actors) when ✓ clicked
frontend/src/pages/WirkgefuegeVorschlag.tsx Navigate to /causal-model/${newModel.id} instead of /causal-model
frontend/src/pages/CausalModelEditor.tsx Read modelId from URL params; use selected.linked_narratives directly; navigate to /narrative/:id

Task 1: api.ts — Claim interface + getClaims + updateSlot

Files: - Modify: frontend/src/lib/api.ts

The backend now returns label, status, and wirkgefuege_ref on every ClaimResponse. The Claim interface in api.ts is missing these. Also GET /narratives/{id}/claims exists but has no client call. Also PUT /causal-models/{id}/slots/{slot_id} now accepts identifier.

  • [ ] Step 1: Read frontend/src/lib/api.ts

Note the current Claim interface (lines ~59–64) and find where to insert the new api calls.

  • [ ] Step 2: Update Claim interface

Replace the existing Claim interface with:

export interface Claim {
  id: string;
  label: string;
  text: string;
  typ: string;
  confidence: number;
  status: string;
  wirkgefuege_ref: string | null;
}
  • [ ] Step 3: Add getClaims to api.narratives

Inside the api.narratives object, add after getSceneClaims:

getClaims: (narrativeId: string) =>
  request<Claim[]>(`/narratives/${narrativeId}/claims`),
  • [ ] Step 4: Add updateSlot to api.causalModels

Inside the api.causalModels object, add after addRelation:

updateSlot: (
  causal_model_id: string,
  slot_id: string,
  epistemic_status: string,
  identifier?: string | null,
) =>
  request<Slot>(`/causal-models/${causal_model_id}/slots/${slot_id}`, {
    method: "PUT",
    body: JSON.stringify({ epistemic_status, identifier: identifier ?? null }),
  }),
  • [ ] Step 5: Verify TypeScript
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -30

Expected: no errors. Fix any type errors before continuing.

  • [ ] Step 6: Commit
cd /Users/thormar/klartext/frontend && git add src/lib/api.ts
git commit -m "feat: update Claim interface, add getClaims and updateSlot API calls"

Task 2: MeineWerke.test.tsx (failing test first)

Files: - Create: frontend/src/pages/MeineWerke.test.tsx

Write the test BEFORE creating the component. This ensures the test drives the implementation.

  • [ ] Step 1: Create the failing test

Create frontend/src/pages/MeineWerke.test.tsx:

import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { MemoryRouter } from "react-router-dom";
import MeineWerke from "./MeineWerke";

const mockNavigate = vi.fn();
vi.mock("react-router-dom", async () => {
  const actual = await vi.importActual("react-router-dom");
  return { ...actual, useNavigate: () => mockNavigate };
});

vi.mock("../lib/api", () => ({
  api: {
    narratives: {
      list: vi.fn().mockResolvedValue([
        {
          id: "n1",
          title: "Mein Narrativ",
          causal_model_id: null,
          scene_count: 3,
          actor_count: 2,
          claim_count: 5,
        },
      ]),
      create: vi.fn().mockResolvedValue({ id: "n2", title: "Neues Narrativ", causal_model_id: null }),
      importFromPath: vi.fn().mockResolvedValue({ id: "n3", title: "Importiert", causal_model_id: null }),
    },
  },
}));

function renderPage() {
  return render(
    <MemoryRouter>
      <MeineWerke />
    </MemoryRouter>
  );
}

describe("MeineWerke", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockNavigate.mockReset();
  });

  it("renders narrative cards with title and counts", async () => {
    renderPage();
    expect(await screen.findByText("Mein Narrativ")).toBeInTheDocument();
    expect(screen.getByText("3 Szenen")).toBeInTheDocument();
    expect(screen.getByText("2 Akteure")).toBeInTheDocument();
    expect(screen.getByText("5 Claims")).toBeInTheDocument();
  });

  it("navigates to narrative detail on card click", async () => {
    renderPage();
    const card = await screen.findByText("Mein Narrativ");
    fireEvent.click(card);
    expect(mockNavigate).toHaveBeenCalledWith("/narrative/n1");
  });

  it("creates narrative and navigates to it", async () => {
    renderPage();
    await screen.findByText("Mein Narrativ"); // wait for load

    const input = screen.getByPlaceholderText("Titel");
    fireEvent.change(input, { target: { value: "Neues Werk" } });

    const btn = screen.getByRole("button", { name: /Anlegen/i });
    fireEvent.click(btn);

    await waitFor(() => {
      expect(mockNavigate).toHaveBeenCalledWith("/narrative/n2");
    });
  });
});
  • [ ] Step 2: Run test to confirm FAIL
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/MeineWerke.test.tsx 2>&1 | head -20

Expected: FAIL — Cannot find module './MeineWerke'


Task 3: MeineWerke.tsx — Screen 0

Files: - Create: frontend/src/pages/MeineWerke.tsx

  • [ ] Step 1: Create the component

Create frontend/src/pages/MeineWerke.tsx:

import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { api, NarrativeSummary } from "../lib/api";

// ---------------------------------------------------------------------------
// MeineWerke — Screen 0 — entry point, lists all narratives
// ---------------------------------------------------------------------------

export default function MeineWerke() {
  const [summaries, setSummaries] = useState<NarrativeSummary[]>([]);
  const [newTitle, setNewTitle] = useState("");
  const [importPath, setImportPath] = useState("");
  const [creating, setCreating] = useState(false);
  const [importing, setImporting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    api.narratives.list()
      .then(setSummaries)
      .catch(() => setError("API nicht erreichbar"));
  }, []);

  async function createNarrative() {
    if (!newTitle.trim()) return;
    setCreating(true);
    setError(null);
    try {
      const narrative = await api.narratives.create(newTitle.trim());
      setNewTitle("");
      navigate(`/narrative/${narrative.id}`);
    } catch {
      setError("Narrativ konnte nicht erstellt werden.");
    } finally {
      setCreating(false);
    }
  }

  async function importNarrative() {
    if (!importPath.trim()) return;
    setImporting(true);
    setError(null);
    try {
      const narrative = await api.narratives.importFromPath(importPath.trim());
      setImportPath("");
      navigate(`/narrative/${narrative.id}`);
    } catch {
      setError("Import fehlgeschlagen. Pfad prüfen.");
    } finally {
      setImporting(false);
    }
  }

  return (
    <div style={{ maxWidth: "900px", margin: "0 auto", padding: "40px 24px" }}>
      <h1 style={{ fontSize: "24px", fontWeight: "700", marginTop: "0", marginBottom: "8px", color: "var(--color-text-primary)" }}>
        Meine Werke
      </h1>
      <p style={{ fontSize: "14px", color: "var(--color-text-secondary)", margin: "0 0 32px" }}>
        {summaries.length === 0 ? "Noch keine Werke vorhanden." : `${summaries.length} Narrative`}
      </p>

      {error && (
        <p style={{ color: "var(--color-red-text)", fontSize: "13px", marginBottom: "16px" }}>{error}</p>
      )}

      {/* Narrative grid */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))",
          gap: "12px",
          marginBottom: "40px",
        }}
      >
        {summaries.map((n) => (
          <button
            key={n.id}
            onClick={() => navigate(`/narrative/${n.id}`)}
            style={{
              border: "1px solid var(--color-border)",
              borderRadius: "8px",
              padding: "16px 20px",
              cursor: "pointer",
              background: "var(--color-bg)",
              textAlign: "left",
              display: "block",
              width: "100%",
              transition: "border-color 0.1s",
            }}
          >
            <h3
              style={{
                margin: "0 0 10px",
                fontSize: "15px",
                fontWeight: "600",
                color: "var(--color-text-primary)",
              }}
            >
              {n.title}
            </h3>
            <div style={{ display: "flex", gap: "6px", flexWrap: "wrap" }}>
              <Chip>{n.scene_count} Szenen</Chip>
              <Chip>{n.actor_count} Akteure</Chip>
              <Chip>{n.claim_count} Claims</Chip>
              {n.causal_model_id && (
                <Chip variant="teal">🔗 Wirkgefüge</Chip>
              )}
            </div>
          </button>
        ))}
      </div>

      {/* Create + Import side by side */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
        {/* Create */}
        <div
          style={{
            border: "1px solid var(--color-border)",
            borderRadius: "8px",
            padding: "20px",
            background: "var(--color-bg-subtle)",
          }}
        >
          <h3
            style={{
              margin: "0 0 12px",
              fontSize: "11px",
              fontWeight: "600",
              color: "var(--color-text-tertiary)",
              textTransform: "uppercase",
              letterSpacing: "0.06em",
            }}
          >
            Neues Narrativ
          </h3>
          <input
            value={newTitle}
            onChange={(e) => setNewTitle(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && createNarrative()}
            placeholder="Titel"
            style={inputStyle}
          />
          <button
            onClick={createNarrative}
            disabled={creating || !newTitle.trim()}
            style={primaryButtonStyle(creating || !newTitle.trim())}
          >
            {creating ? "Erstelle…" : "Anlegen"}
          </button>
        </div>

        {/* Import */}
        <div
          style={{
            border: "1px solid var(--color-border)",
            borderRadius: "8px",
            padding: "20px",
            background: "var(--color-bg-subtle)",
          }}
        >
          <h3
            style={{
              margin: "0 0 12px",
              fontSize: "11px",
              fontWeight: "600",
              color: "var(--color-text-tertiary)",
              textTransform: "uppercase",
              letterSpacing: "0.06em",
            }}
          >
            Aus Datei importieren
          </h3>
          <input
            value={importPath}
            onChange={(e) => setImportPath(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && importNarrative()}
            placeholder="Pfad zur .docx oder .md"
            style={inputStyle}
          />
          <button
            onClick={importNarrative}
            disabled={importing || !importPath.trim()}
            style={primaryButtonStyle(importing || !importPath.trim())}
          >
            {importing ? "Importiere…" : "Importieren"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Sub-components and style helpers
// ---------------------------------------------------------------------------

function Chip({ children, variant = "default" }: { children: React.ReactNode; variant?: "default" | "teal" }) {
  const styles = {
    default: { bg: "var(--color-bg-subtle)", text: "var(--color-text-secondary)" },
    teal:    { bg: "var(--color-teal-bg)",   text: "var(--color-teal-text)" },
  } as const;
  const c = styles[variant];
  return (
    <span
      style={{
        fontSize: "11px",
        padding: "2px 8px",
        borderRadius: "10px",
        background: c.bg,
        color: c.text,
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </span>
  );
}

const inputStyle: React.CSSProperties = {
  width: "100%",
  padding: "8px 10px",
  marginBottom: "8px",
  boxSizing: "border-box",
  fontSize: "13px",
  border: "1px solid var(--color-border)",
  borderRadius: "6px",
  fontFamily: "var(--font-sans)",
  outline: "none",
  background: "var(--color-bg)",
  color: "var(--color-text-primary)",
};

function primaryButtonStyle(disabled: boolean): React.CSSProperties {
  return {
    width: "100%",
    padding: "8px 16px",
    fontSize: "13px",
    fontWeight: "500",
    border: "none",
    borderRadius: "6px",
    cursor: disabled ? "not-allowed" : "pointer",
    background: disabled ? "var(--color-bg)" : "var(--color-text-primary)",
    color: disabled ? "var(--color-text-tertiary)" : "var(--color-text-inverse)",
    outline: disabled ? "1px solid var(--color-border)" : "none",
  };
}
  • [ ] Step 2: Run the test
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/MeineWerke.test.tsx 2>&1 | tail -10

Expected: all 3 tests PASS.

  • [ ] Step 3: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20

Expected: no errors.

  • [ ] Step 4: Commit
git add frontend/src/pages/MeineWerke.tsx frontend/src/pages/MeineWerke.test.tsx
git commit -m "feat: MeineWerke — Screen 0 — narrative list, create and import"

Task 4: NarrativeDetail.test.tsx (failing test first)

Files: - Create: frontend/src/pages/NarrativeDetail.test.tsx

  • [ ] Step 1: Create the failing test

Create frontend/src/pages/NarrativeDetail.test.tsx:

import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import NarrativeDetail from "./NarrativeDetail";

const mockNavigate = vi.fn();
vi.mock("react-router-dom", async () => {
  const actual = await vi.importActual("react-router-dom");
  return { ...actual, useNavigate: () => mockNavigate };
});

vi.mock("../lib/api", () => ({
  api: {
    narratives: {
      get: vi.fn().mockResolvedValue({
        id: "n1",
        title: "Test Narrativ",
        causal_model_id: null,
        scenes: [
          { id: "s1", title: "Szene 1", text: "Szenentext.", position: 1 },
        ],
        actors: [
          { id: "a1", label: "Max Mustermann", actor_type: "individual", notes: null, entity_ref: null },
        ],
      }),
      getClaims: vi.fn().mockResolvedValue([
        {
          id: "c1",
          label: "Geldmenge treibt Inflation",
          text: "Die Geldmenge hat Einfluss auf die Inflation.",
          typ: "causal",
          confidence: 0.9,
          status: "draft",
          wirkgefuege_ref: null,
        },
      ]),
      analyse: vi.fn().mockResolvedValue({ actors: [], claims: [] }),
    },
  },
}));

function renderPage() {
  return render(
    <MemoryRouter initialEntries={["/narrative/n1"]}>
      <Routes>
        <Route path="/narrative/:narrativeId" element={<NarrativeDetail />} />
      </Routes>
    </MemoryRouter>
  );
}

describe("NarrativeDetail", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockNavigate.mockReset();
  });

  it("renders narrative title and scene", async () => {
    renderPage();
    expect(await screen.findByText("Test Narrativ")).toBeInTheDocument();
    expect(screen.getByText("Szene 1")).toBeInTheDocument();
  });

  it("renders actor", async () => {
    renderPage();
    expect(await screen.findByText(/Max Mustermann/)).toBeInTheDocument();
  });

  it("renders claim with label and status", async () => {
    renderPage();
    expect(await screen.findByText("Geldmenge treibt Inflation")).toBeInTheDocument();
    expect(screen.getByText("Entwurf")).toBeInTheDocument();
  });

  it("shows Analysieren button and navigates after click", async () => {
    renderPage();
    await screen.findByText("Test Narrativ"); // wait for load

    const btn = screen.getByRole("button", { name: /Analysieren/i });
    fireEvent.click(btn);

    await waitFor(() => {
      expect(mockNavigate).toHaveBeenCalledWith(
        "/narrative/n1/analyse",
        expect.objectContaining({ state: expect.objectContaining({ narrative: { id: "n1", title: "Test Narrativ" } }) })
      );
    });
  });
});
  • [ ] Step 2: Run to confirm FAIL
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/NarrativeDetail.test.tsx 2>&1 | head -20

Expected: FAIL — Cannot find module './NarrativeDetail'


Task 5: NarrativeDetail.tsx — Screen 1

Files: - Create: frontend/src/pages/NarrativeDetail.tsx

  • [ ] Step 1: Create the component

Create frontend/src/pages/NarrativeDetail.tsx:

import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { api, Claim, Narrative } from "../lib/api";

// ---------------------------------------------------------------------------
// Label maps — German user-facing strings
// ---------------------------------------------------------------------------

const STATUS_LABELS: Record<string, string> = {
  draft: "Entwurf",
  confirmed: "Bestätigt",
  linked: "Verknüpft",
  rejected: "Verworfen",
};

const STATUS_COLORS: Record<string, { bg: string; text: string }> = {
  draft:     { bg: "var(--color-amber-bg)",  text: "var(--color-amber-text)" },
  confirmed: { bg: "var(--color-green-bg)",  text: "var(--color-green-text)" },
  linked:    { bg: "var(--color-teal-bg)",   text: "var(--color-teal-text)" },
  rejected:  { bg: "var(--color-red-bg)",    text: "var(--color-red-text)" },
};

const ACTOR_TYPE_LABELS: Record<string, string> = {
  individual:     "Figur",
  organisation:   "Organisation",
  group:          "Gruppe",
  institution:    "Institution",
  abstract_entity:"Abstrakte Entität",
};

const CLAIM_TYPE_LABELS: Record<string, string> = {
  empirical:      "Empirisch",
  causal:         "Kausal",
  definitional:   "Definitorisch",
  normative:      "Normativ",
  prognostic:     "Prognostisch",
  counterfactual: "Kontrafaktisch",
  methodological: "Methodisch",
  uncertainty:    "Unsicherheit",
};

// ---------------------------------------------------------------------------
// NarrativeDetail — Screen 1
//
// Loads narrative + its claims, shows scenes (expandable), actors, claims,
// and the primary "Analysieren" button.
// ---------------------------------------------------------------------------

export default function NarrativeDetail() {
  const { narrativeId } = useParams<{ narrativeId: string }>();
  const navigate = useNavigate();

  const [narrative, setNarrative] = useState<Narrative | null>(null);
  const [claims, setClaims] = useState<Claim[]>([]);
  const [expandedSceneId, setExpandedSceneId] = useState<string | null>(null);
  const [analysing, setAnalysing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!narrativeId) return;
    Promise.all([
      api.narratives.get(narrativeId),
      api.narratives.getClaims(narrativeId),
    ])
      .then(([narr, cls]) => {
        setNarrative(narr);
        setClaims(cls);
      })
      .catch(() => setError("Narrativ konnte nicht geladen werden."));
  }, [narrativeId]);

  async function analyseNarrative() {
    if (!narrativeId || !narrative) return;
    setAnalysing(true);
    setError(null);
    try {
      const analysis = await api.narratives.analyse(narrativeId);
      navigate(`/narrative/${narrativeId}/analyse`, {
        state: { analysis, narrative: { id: narrativeId, title: narrative.title } },
      });
    } catch {
      setError("Analyse fehlgeschlagen. Bitte erneut versuchen.");
    } finally {
      setAnalysing(false);
    }
  }

  if (error && !narrative) {
    return <p style={{ color: "var(--color-red-text)", padding: "32px 24px" }}>{error}</p>;
  }
  if (!narrative) {
    return <p style={{ color: "var(--color-text-tertiary)", padding: "32px 24px" }}>Lade…</p>;
  }

  return (
    <div style={{ maxWidth: "760px", margin: "0 auto", padding: "32px 24px" }}>
      {/* Back */}
      <button
        onClick={() => navigate("/")}
        style={{
          background: "none", border: "none", cursor: "pointer",
          color: "var(--color-text-secondary)", marginBottom: "20px",
          padding: "0", fontSize: "13px",
        }}
      >
        ← Meine Werke
      </button>

      {/* Header */}
      <h1
        style={{
          fontSize: "24px", fontWeight: "700", marginTop: "0",
          marginBottom: "4px", color: "var(--color-text-primary)",
        }}
      >
        {narrative.title}
      </h1>
      <p style={{ fontSize: "13px", color: "var(--color-text-secondary)", margin: "0 0 32px" }}>
        {narrative.scenes.length} Szenen · {narrative.actors.length} Akteure · {claims.length} Claims
        {narrative.causal_model_id && " · 🔗 Wirkgefüge verknüpft"}
      </p>

      {/* ------------------------------------------------------------------ */}
      {/* Scenes                                                              */}
      {/* ------------------------------------------------------------------ */}
      <SectionHeader label={`Szenen (${narrative.scenes.length})`} />
      {narrative.scenes.length === 0 ? (
        <EmptyHint>Keine Szenen vorhanden.</EmptyHint>
      ) : (
        <ul style={{ listStyle: "none", padding: 0, margin: "0 0 28px" }}>
          {narrative.scenes.map((scene) => (
            <li key={scene.id} style={{ marginBottom: "6px" }}>
              <button
                onClick={() =>
                  setExpandedSceneId(expandedSceneId === scene.id ? null : scene.id)
                }
                style={{
                  width: "100%", background: "none",
                  border: "1px solid var(--color-border)", borderRadius: "6px",
                  padding: "10px 14px", cursor: "pointer", textAlign: "left",
                  fontSize: "13px", color: "var(--color-text-primary)",
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                }}
              >
                <span>
                  <span style={{ color: "var(--color-text-tertiary)", marginRight: "8px" }}>
                    {scene.position}.
                  </span>
                  {scene.title}
                </span>
                <span style={{ color: "var(--color-text-tertiary)", fontSize: "11px" }}>
                  {expandedSceneId === scene.id ? "▲" : "▼"}
                </span>
              </button>
              {expandedSceneId === scene.id && (
                <div
                  style={{
                    padding: "12px 14px",
                    borderLeft: "3px solid var(--color-blue-text)",
                    background: "var(--color-bg-subtle)",
                    borderRadius: "0 0 6px 6px",
                    fontSize: "13px",
                    lineHeight: "1.7",
                    color: "var(--color-text-secondary)",
                    whiteSpace: "pre-wrap",
                  }}
                >
                  {scene.text}
                </div>
              )}
            </li>
          ))}
        </ul>
      )}

      {/* ------------------------------------------------------------------ */}
      {/* Actors                                                              */}
      {/* ------------------------------------------------------------------ */}
      <SectionHeader label={`Akteure (${narrative.actors.length})`} />
      {narrative.actors.length === 0 ? (
        <EmptyHint style={{ marginBottom: "28px" }}>Noch keine Akteure bestätigt.</EmptyHint>
      ) : (
        <ul style={{ listStyle: "none", padding: 0, margin: "0 0 28px" }}>
          {narrative.actors.map((actor) => (
            <li
              key={actor.id}
              style={{
                display: "flex", alignItems: "center", gap: "8px",
                padding: "8px 0",
                borderBottom: "1px solid var(--color-border-subtle)",
              }}
            >
              <span style={{ fontSize: "13px", color: "var(--color-text-primary)", flex: 1 }}>
                👤 {actor.label}
              </span>
              <span
                style={{
                  fontSize: "11px", padding: "2px 8px", borderRadius: "10px",
                  background: "var(--color-bg-subtle)", color: "var(--color-text-secondary)",
                }}
              >
                {ACTOR_TYPE_LABELS[actor.actor_type] ?? actor.actor_type}
              </span>
            </li>
          ))}
        </ul>
      )}

      {/* ------------------------------------------------------------------ */}
      {/* Claims                                                              */}
      {/* ------------------------------------------------------------------ */}
      <SectionHeader label={`Claims (${claims.length})`} />
      {claims.length === 0 ? (
        <EmptyHint style={{ marginBottom: "28px" }}>
          Noch keine Claims. Erst "Analysieren" klicken.
        </EmptyHint>
      ) : (
        <ul style={{ listStyle: "none", padding: 0, margin: "0 0 28px" }}>
          {claims.map((claim) => {
            const statusColor =
              STATUS_COLORS[claim.status] ?? STATUS_COLORS["draft"];
            return (
              <li
                key={claim.id}
                style={{
                  padding: "10px 0",
                  borderBottom: "1px solid var(--color-border-subtle)",
                }}
              >
                <div
                  style={{
                    display: "flex", alignItems: "center",
                    gap: "8px", marginBottom: "4px",
                  }}
                >
                  <span
                    style={{
                      fontSize: "13px", fontWeight: "500",
                      color: "var(--color-text-primary)", flex: 1,
                    }}
                  >
                    {claim.label}
                  </span>
                  <span
                    style={{
                      fontSize: "11px", padding: "2px 8px", borderRadius: "10px",
                      background: statusColor.bg, color: statusColor.text,
                      whiteSpace: "nowrap",
                    }}
                  >
                    {STATUS_LABELS[claim.status] ?? claim.status}
                  </span>
                  <span
                    style={{
                      fontSize: "11px", padding: "2px 8px", borderRadius: "10px",
                      background: "var(--color-bg-subtle)",
                      color: "var(--color-text-secondary)",
                    }}
                  >
                    {CLAIM_TYPE_LABELS[claim.typ] ?? claim.typ}
                  </span>
                </div>
                <p
                  style={{
                    margin: 0, fontSize: "12px",
                    color: "var(--color-text-secondary)", fontStyle: "italic",
                  }}
                >
                  "{claim.text}"
                </p>
              </li>
            );
          })}
        </ul>
      )}

      {/* ------------------------------------------------------------------ */}
      {/* Analysieren button                                                  */}
      {/* ------------------------------------------------------------------ */}
      <div
        style={{
          borderTop: "1px solid var(--color-border)",
          paddingTop: "24px",
          marginTop: "8px",
        }}
      >
        <button
          onClick={analyseNarrative}
          disabled={analysing}
          style={{
            width: "100%", padding: "12px 16px", fontSize: "14px",
            fontWeight: "500", border: "none", borderRadius: "8px",
            cursor: analysing ? "not-allowed" : "pointer",
            background: analysing ? "var(--color-bg-subtle)" : "var(--color-text-primary)",
            color: analysing ? "var(--color-text-tertiary)" : "var(--color-text-inverse)",
          }}
        >
          {analysing ? "⏳ Analyse läuft…" : "Analysieren →"}
        </button>
        {error && (
          <p style={{ color: "var(--color-red-text)", fontSize: "13px", marginTop: "8px" }}>
            {error}
          </p>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------

function SectionHeader({ label }: { label: string }) {
  return (
    <h3
      style={{
        fontSize: "11px", fontWeight: "600", textTransform: "uppercase",
        letterSpacing: "0.06em", color: "var(--color-text-tertiary)",
        margin: "0 0 10px", padding: "16px 0 8px",
        borderTop: "1px solid var(--color-border)",
      }}
    >
      {label}
    </h3>
  );
}

function EmptyHint({ children, style }: { children: React.ReactNode; style?: React.CSSProperties }) {
  return (
    <p style={{ color: "var(--color-text-tertiary)", fontSize: "13px", margin: "0 0 28px", ...style }}>
      {children}
    </p>
  );
}
  • [ ] Step 2: Run the tests
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/NarrativeDetail.test.tsx 2>&1 | tail -10

Expected: all 4 tests PASS.

  • [ ] Step 3: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20

Expected: no errors.

  • [ ] Step 4: Commit
git add frontend/src/pages/NarrativeDetail.tsx frontend/src/pages/NarrativeDetail.test.tsx
git commit -m "feat: NarrativeDetail — Screen 1 — scenes, actors, claims, Analysieren"

Task 6: App.tsx — routing and nav update

Files: - Modify: frontend/src/App.tsx

  • [ ] Step 1: Read current App.tsx

Read the file to understand the current routes and nav.

  • [ ] Step 2: Update App.tsx

Replace the entire file with:

import { BrowserRouter, Routes, Route } from "react-router-dom";
import MeineWerke from "./pages/MeineWerke";
import NarrativeDetail from "./pages/NarrativeDetail";
import NarrativeAnalyse from "./pages/NarrativeAnalyse";
import WirkgefuegeVorschlag from "./pages/WirkgefuegeVorschlag";
import CausalModelEditor from "./pages/CausalModelEditor";
import Login from "./pages/Login";

// ---------------------------------------------------------------------------
// App — V2 routing
//
// Screen 0: /              → MeineWerke
// Screen 1: /narrative/:id → NarrativeDetail
// Screen 2: /narrative/:id/analyse → NarrativeAnalyse
// Screen 3: /narrative/:id/wirkgefuege-vorschlag → WirkgefuegeVorschlag
// Screen 4: /causal-model/:id → CausalModelEditor
// ---------------------------------------------------------------------------

export default function App() {
  return (
    <BrowserRouter>
      <div style={{ minHeight: "100vh", background: "var(--color-bg)" }}>
        <Routes>
          <Route path="/" element={<MeineWerke />} />
          <Route path="/narrative/:narrativeId" element={<NarrativeDetail />} />
          <Route path="/narrative/:narrativeId/analyse" element={<NarrativeAnalyse />} />
          <Route
            path="/narrative/:narrativeId/wirkgefuege-vorschlag"
            element={<WirkgefuegeVorschlag />}
          />
          <Route path="/causal-model/:modelId" element={<CausalModelEditor />} />
          <Route path="/login" element={<Login />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

Note: The old /causal-model (without id param) and /narrative (without id) are removed. Only the new id-based routes remain.

  • [ ] Step 3: Update existing App.test.tsx if present

Read frontend/src/App.test.tsx. If it tests specific routes that no longer exist, update it to test / renders something.

Current App.test.tsx likely just renders the App with a smoke test. Update the mock if it imports NarrativeEditor which is no longer routed:

import { render } from "@testing-library/react";
import { describe, it } from "vitest";
import App from "./App";

describe("App", () => {
  it("renders without crashing", () => {
    render(<App />);
  });
});
  • [ ] Step 4: Run all tests
cd /Users/thormar/klartext/frontend && npx vitest run 2>&1 | tail -15

All tests must pass. If NarrativeEditor.test.tsx fails (because it expects the old route), update it — NarrativeEditor is now a standalone component, not a page in the routing. The test can still test it directly:

// in NarrativeEditor.test.tsx — the component still exists, just not routed
// The test tests the component in isolation, so no route change needed.
// But the api.narratives.list mock may need `scene_count/actor_count/claim_count`.
// Update the mock:
vi.mock("../lib/api", () => ({
  api: {
    narratives: {
      list: vi.fn().mockResolvedValue([
        {
          id: "n1", title: "Test Narrativ", causal_model_id: null,
          scene_count: 0, actor_count: 0, claim_count: 0,
        },
      ]),
      get: vi.fn().mockResolvedValue({ ... }),
      analyse: vi.fn().mockResolvedValue({ actors: [], claims: [] }),
    },
    causalModels: { list: vi.fn().mockResolvedValue([]) },
  },
}));
  • [ ] Step 5: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20
  • [ ] Step 6: Commit
git add frontend/src/App.tsx frontend/src/App.test.tsx frontend/src/pages/NarrativeEditor.test.tsx
git commit -m "feat: V2 routing — / → MeineWerke, /narrative/:id → NarrativeDetail, /causal-model/:id → CausalModelEditor"

Task 7: NarrativeAnalyse.tsx — save confirmed actors to DB

Files: - Modify: frontend/src/pages/NarrativeAnalyse.tsx

Currently, clicking ✓ on an actor only updates local UI state. Per the V2 spec, confirmed actors should be saved to the DB so they appear on Screen 1 after the workflow.

  • [ ] Step 1: Read frontend/src/pages/NarrativeAnalyse.tsx

Find how setActorStates is called on accept.

  • [ ] Step 2: Extract acceptActor function

In NarrativeAnalyse, replace the inline onAccept callback for actors with a proper acceptActor function that both updates UI state AND saves to the API:

Find the section with:

onAccept={() =>
  setActorStates((prev) => prev.map((s, j) => (j === i ? "accepted" : s)))
}

Replace with a call to an acceptActor(i) function. Define that function in the component:

async function acceptActor(index: number) {
  setActorStates((prev) => prev.map((s, j) => (j === index ? "accepted" : s)));
  const actor = analysis.actors[index];
  try {
    await api.narratives.addActor(
      narrativeId!,
      actor.label,
      actor.actor_type,
      null,                     // notes
      actor.entity_suggestion,  // entity_ref — maps to actor.entity_ref
    );
  } catch {
    // Non-critical: UI already shows accepted state
    console.warn("Akteur konnte nicht gespeichert werden:", actor.label);
  }
}

Update the ActorCard usage:

onAccept={() => acceptActor(i)}

  • [ ] Step 3: Run existing NarrativeAnalyse tests
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/NarrativeAnalyse.test.tsx 2>&1 | tail -10

All tests must pass. If the test mocks api.narratives.addActor, it should already be present. If not, add it to the mock:

addActor: vi.fn().mockResolvedValue({ id: "a1", label: "Test", actor_type: "individual", notes: null, entity_ref: null }),

  • [ ] Step 4: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20
  • [ ] Step 5: Commit
git add frontend/src/pages/NarrativeAnalyse.tsx
git commit -m "feat: NarrativeAnalyse — confirmed actors saved to DB via POST /actors"

Task 8: WirkgefuegeVorschlag.tsx — navigate to /causal-model/:id

Files: - Modify: frontend/src/pages/WirkgefuegeVorschlag.tsx

Currently navigates to /causal-model with state. Screen 4 now uses URL params, so navigate to /causal-model/${newModel.id}.

  • [ ] Step 1: Read frontend/src/pages/WirkgefuegeVorschlag.tsx

Find the navigate("/causal-model", ...) call.

  • [ ] Step 2: Update the navigate call

Find:

navigate("/causal-model", { state: { selectedModelId: newModel.id } });

Replace with:

navigate(`/causal-model/${newModel.id}`);

  • [ ] Step 3: Run existing WirkgefuegeVorschlag tests
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/WirkgefuegeVorschlag.test.tsx 2>&1 | tail -10

All tests must pass. Update the test mock's navigate assertion if it checks the old path:

// Old:
expect(mockNavigate).toHaveBeenCalledWith("/causal-model", expect.anything());
// New:
expect(mockNavigate).toHaveBeenCalledWith(`/causal-model/${newModelId}`);

  • [ ] Step 4: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20
  • [ ] Step 5: Commit
git add frontend/src/pages/WirkgefuegeVorschlag.tsx frontend/src/pages/WirkgefuegeVorschlag.test.tsx
git commit -m "feat: WirkgefuegeVorschlag navigates to /causal-model/:id after save"

Task 9: CausalModelEditor.tsx — URL params + linked_narratives

Files: - Modify: frontend/src/pages/CausalModelEditor.tsx

Two changes: 1. Read modelId from URL params (useParams) and load that model on mount 2. Use selected.linked_narratives directly (instead of filtering narratives by causal_model_id) and navigate to /narrative/:id instead of /narrative

  • [ ] Step 1: Read frontend/src/pages/CausalModelEditor.tsx

Find: how loadModel is called, where locationState?.selectedModelId is used, and where linkedNarratives is computed and rendered.

  • [ ] Step 2: Add useParams and auto-load from URL

Import useParams (it's already imported via useLocation):

import { useLocation, useNavigate, useParams } from "react-router-dom";

Add inside the component (near the top of function body, after existing state declarations):

const { modelId } = useParams<{ modelId: string }>();

Update the useEffect to use modelId from URL params instead of (or in addition to) locationState:

Find the existing useEffect:

useEffect(() => {
  Promise.all([api.causalModels.list(), api.narratives.list()])
    .then(([cms, narrs]) => {
      setModels(cms);
      setNarratives(narrs);
      const targetId = locationState?.selectedModelId;
      if (targetId) {
        const match = cms.find((m) => m.id === targetId);
        if (match) {
          loadModel(targetId);
        }
      }
    })
    .catch(() => setError("API nicht erreichbar"));
}, []);

Replace with:

useEffect(() => {
  const targetId = modelId ?? locationState?.selectedModelId;
  Promise.all([api.causalModels.list(), targetId ? api.causalModels.get(targetId) : Promise.resolve(null)])
    .then(([cms, model]) => {
      setModels(cms);
      if (model) setSelected(model);
    })
    .catch(() => setError("API nicht erreichbar"));
}, [modelId]);

Note: This removes the api.narratives.list() call since linkedNarratives will come directly from selected.linked_narratives.

  • [ ] Step 3: Remove narratives state and update linkedNarratives

Remove the narratives state:

// Remove:
const [narratives, setNarratives] = useState<NarrativeSummary[]>([]);

Remove the NarrativeSummary import from api if it's only used for that.

Update the linkedNarratives computation. Find:

const linkedNarratives = narratives.filter((n) => n.causal_model_id === selected?.id);

Replace with:

const linkedNarratives = selected?.linked_narratives ?? [];

  • [ ] Step 4: Update navigate in linked narratives

Find the navigate call in the linked narratives section:

onClick={() => navigate("/narrative")}

Replace with:

onClick={() => navigate(`/narrative/${n.id}`)}

  • [ ] Step 5: Run CausalModelEditor tests
cd /Users/thormar/klartext/frontend && npx vitest run src/pages/CausalModelEditor.test.tsx 2>&1 | tail -10

Read the test file first. The mocks may need updating: - api.causalModels.get mock should return a model WITH linked_narratives: [] - api.narratives.list may no longer be called — update the mock accordingly

The test uses MemoryRouter — update it to use MemoryRouter initialEntries={["/causal-model/m1"]} and render within a Route path="/causal-model/:modelId" if the test expects auto-loading.

  • [ ] Step 6: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20

Fix any errors.

  • [ ] Step 7: Commit
git add frontend/src/pages/CausalModelEditor.tsx frontend/src/pages/CausalModelEditor.test.tsx
git commit -m "feat: CausalModelEditor uses URL params, linked_narratives from model API"

Task 10: Full regression

Files: none

  • [ ] Step 1: Run full Vitest suite
cd /Users/thormar/klartext/frontend && npx vitest run 2>&1 | tail -15

Expected: all tests pass, 0 failures.

  • [ ] Step 2: TypeScript check
cd /Users/thormar/klartext/frontend && npx tsc --noEmit 2>&1 | head -20

Expected: no errors.

  • [ ] Step 3: Final commit if any loose ends

If any files were modified but not committed, commit now.


Self-Review

Spec coverage

Screen Requirement Task
Screen 0 Übersichtsliste aller Narrative mit Titel, Szenenanzahl, Actor-, Claimanzahl, Wirkgefüge-Indikator Task 3
Screen 0 Neues Narrativ anlegen Task 3
Screen 0 Datei importieren → direkt zu Screen 1 Task 3
Screen 1 Titel + Szenenliste (lesbar) Task 5
Screen 1 Akteure und Claims nach Analyse sichtbar Task 5
Screen 1 "Analysieren" Button → Screen 2 Task 5
Screen 2 Actor/Claim-Karten mit Bestätigen/Verwerfen unchanged
Screen 2 "Alle bestätigen" Button unchanged
Screen 2 Bestätigte Actors werden in DB gespeichert Task 7
Screen 2 "Wirkgefüge-Vorschläge generieren" nur aktiv wenn ≥1 Claim unchanged
Screen 3 Slots + Relationen bearbeitbar unchanged
Screen 3 Slot-Identifier umbenennbar unchanged (local state, persisted on save)
Screen 3 Speichern → CausalModel + Slots + Relationen anlegen + Narrativ verknüpfen unchanged
Screen 3 Speichern → zu Screen 4 navigieren Task 8
Screen 4 Slots, Relationen, Axiome anzeigen unchanged
Screen 4 Verknüpfte Narrative anzeigen Task 9
Screen 4 Verknüpftes Narrativ → zu Screen 1 navigieren Task 9

Placeholder scan

No TBD, TODO, or vague steps in this plan. All steps include complete code.

Type consistency

  • Claim interface updated in Task 1 — claim.label, claim.status, claim.typ used in NarrativeDetail Task 5 ✅
  • api.narratives.getClaims defined in Task 1, called in NarrativeDetail Task 5 ✅
  • LinkedNarrative in CausalModel — n.id, n.title used in CausalModelEditor Task 9 ✅
  • NarrativeSummary.scene_count / actor_count / claim_count used in MeineWerke Task 3 ✅
  • Routes: /narrative/${id} defined in App Task 6, navigated to in Tasks 3, 9 ✅
  • Routes: /causal-model/${id} defined in App Task 6, navigated to in Task 8 ✅