The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
feat(history): add per-task version history (#37)
steve wue3bea77fbe4e
diff --git a/docs/pr-assets/history-versions/empty-state-en.png b/docs/pr-assets/history-versions/empty-state-en.pngnew file mode 100644index 00000000..a79d0901Binary files /dev/null and b/docs/pr-assets/history-versions/empty-state-en.png differdiff --git a/docs/pr-assets/history-versions/empty-state-zh-cn.png b/docs/pr-assets/history-versions/empty-state-zh-cn.pngnew file mode 100644index 00000000..e20fe91dBinary files /dev/null and b/docs/pr-assets/history-versions/empty-state-zh-cn.png differdiff --git a/docs/pr-assets/history-versions/large-html-visual-compare.png b/docs/pr-assets/history-versions/large-html-visual-compare.pngnew file mode 100644index 00000000..fb8ed368Binary files /dev/null and b/docs/pr-assets/history-versions/large-html-visual-compare.png differdiff --git a/docs/pr-assets/history-versions/v1-v2-visual-compare.png b/docs/pr-assets/history-versions/v1-v2-visual-compare.pngnew file mode 100644index 00000000..48fb37d1Binary files /dev/null and b/docs/pr-assets/history-versions/v1-v2-visual-compare.png differdiff --git a/next/package.json b/next/package.jsonindex 47a8755a..c982e131 100644--- a/next/package.json+++ b/next/package.json@@ -13,8 +13,10 @@},"dependencies": {"clsx": "^2.1.1",+ "diff": "^9.0.0","dompurify": "^3.4.2","highlight.js": "^11.11.1",+ "idb": "^8.0.3","jszip": "^3.10.1","juice": "^11.1.1","lucide-react": "^1.14.0",@@ -35,6 +37,7 @@"@types/papaparse": "^5.5.2","@types/react": "^19","@types/react-dom": "^19",+ "fake-indexeddb": "^6.2.5","happy-dom": "^20.9.0","tailwindcss": "^4","typescript": "^5",diff --git a/next/src/app/page.tsx b/next/src/app/page.tsxindex 169760e8..50ff012b 100644--- a/next/src/app/page.tsx+++ b/next/src/app/page.tsx@@ -5,6 +5,7 @@ import { Toolbar } from "@/components/toolbar";import { EditorPane } from "@/components/editor-pane";import { PreviewPane } from "@/components/preview-pane";import { TasksSidebar } from "@/components/tasks-sidebar";+import { HistoryPane } from "@/components/history-pane";import { WelcomeModal } from "@/components/welcome-modal";import { SettingsModal, type SectionId } from "@/components/settings-modal";import { ConvertChip } from "@/components/convert-chip";@@ -82,6 +83,7 @@ export default function Home() {style={{ borderTop: "1px solid var(--line-faint)" }}><TasksSidebar />+ <HistoryPane /><div className="relative flex flex-1 min-w-0">{layoutMode !== "preview" && (<sectiondiff --git a/next/src/components/history-pane.tsx b/next/src/components/history-pane.tsxnew file mode 100644index 00000000..2ba66ea8--- /dev/null+++ b/next/src/components/history-pane.tsx@@ -0,0 +1,493 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { diffLines, type ChangeObject } from "diff";+import { selectActiveTask, useStore } from "@/lib/store";+import {+ deleteRun,+ listRuns,+ MAX_VERSIONS_PER_TASK,+ type RunRecord,+} from "@/lib/history/db";+import { isCurrentRun } from "@/lib/history/is-current";+import { previewHtml } from "@/lib/extract-html";+import { relativeTime, useMounted } from "@/lib/use-autosave";+import { useT } from "@/lib/i18n";++type Mode = "list" | "diff";++/**+ * Per-task version timeline. Reads from IndexedDB so the full HTML payloads+ * for past runs don't bloat localStorage. Lets the user inspect, restore,+ * or side-by-side compare any of the last `MAX_VERSIONS_PER_TASK` versions.+ */+export function HistoryPane() {+ const open = useStore((s) => s.historyPaneOpen);+ const setOpen = useStore((s) => s.setHistoryPaneOpen);+ const activeTaskId = useStore((s) => s.activeTaskId);+ const activeTask = useStore(selectActiveTask);+ const setHtmlFor = useStore((s) => s.setHtmlFor);+ const setContent = useStore((s) => s.setContent);+ const commitBase = useStore((s) => s.commitBaseFor);+ const setStatusFor = useStore((s) => s.setStatusFor);+ const t = useT();+ const mounted = useMounted();++ const [runs, setRuns] = useState<RunRecord[]>([]);+ const [loading, setLoading] = useState(false);+ const [mode, setMode] = useState<Mode>("list");+ // Versions selected for the diff view. Left = older, right = newer (by default).+ const [leftId, setLeftId] = useState<string | null>(null);+ const [rightId, setRightId] = useState<string | null>(null);+ const [showSourceDiff, setShowSourceDiff] = useState(false);++ // The persist middleware writes synchronously on every action, so we+ // refresh the list whenever the active task's html changes — that's our+ // signal that a new version was just committed.+ const activeHtml = activeTask?.html ?? "";+ const refresh = useCallback(() => {+ if (!activeTaskId) {+ setRuns([]);+ return;+ }+ setLoading(true);+ listRuns(activeTaskId)+ .then((rows) => setRuns(rows))+ .finally(() => setLoading(false));+ }, [activeTaskId]);++ useEffect(() => {+ if (!open) return;+ refresh();+ }, [open, refresh, activeHtml]);++ // Whenever the task changes, drop back to list mode so we don't render+ // diff against a stale version pair.+ useEffect(() => {+ setMode("list");+ setLeftId(null);+ setRightId(null);+ setShowSourceDiff(false);+ }, [activeTaskId]);++ if (!open) return null;++ const onOpenDiff = (record: RunRecord) => {+ // Compare the picked version against the latest run if there is one,+ // otherwise against itself (degenerate but doesn't crash).+ const latest = runs[0];+ const pickRight = latest && latest.id !== record.id ? latest.id : record.id;+ setLeftId(record.id);+ setRightId(pickRight);+ setMode("diff");+ };++ const onRestore = (record: RunRecord) => {+ if (!activeTaskId) return;+ if (!confirm(t("history.restoreConfirm", { v: record.version }))) return;+ setHtmlFor(activeTaskId, record.html);+ setContent(record.content);+ setStatusFor(activeTaskId, "done");+ // Snapshot the restored state as a new version so the user can roll+ // forward again later; commitBaseFor also resets the diff-edit baseline.+ commitBase(activeTaskId);+ refresh();+ };++ const onDelete = async (record: RunRecord) => {+ if (!activeTaskId) return;+ if (!confirm(t("history.deleteConfirm", { v: record.version }))) return;+ await deleteRun(activeTaskId, record.version);+ refresh();+ };++ return (+ <aside+ className="flex flex-col"+ style={{+ width: 280,+ background: "var(--paper)",+ borderRight: "1px solid var(--line-faint)",+ }}+ >+ <div+ className="flex items-center justify-between gap-2 px-4 py-3"+ style={{ borderBottom: "1px solid var(--line-faint)" }}+ >+ <div className="flex min-w-0 items-center gap-2">+ <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-[var(--ink-faint)]">+ {t("history.heading")}+ </span>+ <span+ className="rounded-full px-1.5 text-[10px] font-mono tabular-nums"+ style={{ background: "var(--surface)", color: "var(--ink-mute)", border: "1px solid var(--line-faint)" }}+ title={t("history.versionCap", { n: MAX_VERSIONS_PER_TASK })}+ >+ {runs.length}+ </span>+ </div>+ <div className="flex items-center gap-1">+ {mode === "diff" && (+ <button+ onClick={() => setMode("list")}+ className="rounded px-1.5 py-0.5 text-[11px] text-[var(--ink-mute)] hover:text-[var(--ink)]"+ title={t("history.backToList")}+ >+ ‹ {t("history.backToList")}+ </button>+ )}+ <button+ onClick={() => setOpen(false)}+ className="text-[14px] text-[var(--ink-faint)] hover:text-[var(--ink)] transition-colors px-1"+ title={t("history.close")}+ aria-label={t("history.close")}+ >+ ✕+ </button>+ </div>+ </div>++ {!activeTaskId ? (+ <div className="px-4 py-6 text-center text-[12px] text-[var(--ink-mute)]">+ {t("history.empty.noTask")}+ </div>+ ) : mode === "list" ? (+ <HistoryList+ runs={runs}+ loading={loading}+ mounted={mounted}+ activeHtml={activeHtml}+ onCompare={onOpenDiff}+ onRestore={onRestore}+ onDelete={onDelete}+ />+ ) : (+ <DiffView+ runs={runs}+ leftId={leftId}+ rightId={rightId}+ onPickLeft={setLeftId}+ onPickRight={setRightId}+ showSource={showSourceDiff}+ onToggleSource={() => setShowSourceDiff((v) => !v)}+ />+ )}+ </aside>+ );+}++function HistoryList({+ runs,+ loading,+ mounted,+ activeHtml,+ onCompare,+ onRestore,+ onDelete,+}: {+ runs: RunRecord[];+ loading: boolean;+ mounted: boolean;+ activeHtml: string;+ onCompare: (r: RunRecord) => void;+ onRestore: (r: RunRecord) => void;+ onDelete: (r: RunRecord) => void;+}) {+ const t = useT();++ if (loading && runs.length === 0) {+ return (+ <div className="px-4 py-6 text-center text-[12px] text-[var(--ink-mute)]">+ {t("history.loading")}+ </div>+ );+ }+ if (runs.length === 0) {+ return (+ <div className="px-4 py-6 text-center text-[12px] text-[var(--ink-mute)]">+ {t("history.empty.noVersions")}+ </div>+ );+ }+ return (+ <div className="flex-1 overflow-y-auto p-2 pt-2.5">+ {runs.map((r) => (+ <HistoryCard+ key={r.id}+ run={r}+ isCurrent={isCurrentRun(r, runs, activeHtml)}+ mounted={mounted}+ onCompare={() => onCompare(r)}+ onRestore={() => onRestore(r)}+ onDelete={() => onDelete(r)}+ />+ ))}+ </div>+ );+}++function HistoryCard({+ run,+ isCurrent,+ mounted,+ onCompare,+ onRestore,+ onDelete,+}: {+ run: RunRecord;+ isCurrent: boolean;+ mounted: boolean;+ onCompare: () => void;+ onRestore: () => void;+ onDelete: () => void;+}) {+ const t = useT();+ const sizeKB = (run.html.length / 1024).toFixed(1);+ return (+ <div+ className="group relative mb-1.5 rounded-xl px-3 py-2.5 transition-colors hover:bg-[var(--surface)]"+ style={{+ border: isCurrent ? "1px solid var(--line-soft)" : "1px solid transparent",+ background: isCurrent ? "var(--surface)" : "transparent",+ }}+ >+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-2 min-w-0">+ <span+ className="font-mono text-[11px] tabular-nums"+ style={{ color: isCurrent ? "var(--coral)" : "var(--ink-mute)" }}+ >+ v{run.version}+ </span>+ {isCurrent && (+ <span+ className="rounded px-1.5 py-0.5 text-[9px] uppercase tracking-wide"+ style={{ background: "var(--coral-soft)", color: "var(--coral)" }}+ >+ {t("history.current")}+ </span>+ )}+ </div>+ <span className="font-mono text-[10px] tabular-nums text-[var(--ink-faint)]">+ {sizeKB} KB+ </span>+ </div>+ <div className="mt-0.5 text-[10.5px] text-[var(--ink-faint)]" suppressHydrationWarning>+ {mounted ? relativeTime(run.ts) : ""}+ </div>+ <div className="mt-1.5 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">+ <button+ onClick={onCompare}+ className="rounded border px-1.5 py-0.5 text-[10.5px] text-[var(--ink-mute)] hover:border-[var(--ink)]/30 hover:text-[var(--ink)]"+ style={{ borderColor: "var(--line-faint)" }}+ >+ {t("history.compare")}+ </button>+ <button+ onClick={onRestore}+ disabled={isCurrent}+ className="rounded border px-1.5 py-0.5 text-[10.5px] text-[var(--ink-mute)] hover:border-[var(--ink)]/30 hover:text-[var(--ink)] disabled:cursor-not-allowed disabled:opacity-40"+ style={{ borderColor: "var(--line-faint)" }}+ >+ {t("history.restore")}+ </button>+ <button+ onClick={onDelete}+ className="ml-auto rounded px-1.5 py-0.5 text-[10.5px] text-[var(--ink-faint)] hover:text-[var(--red)]"+ title={t("history.delete")}+ >+ ✕+ </button>+ </div>+ </div>+ );+}++function DiffView({+ runs,+ leftId,+ rightId,+ onPickLeft,+ onPickRight,+ showSource,+ onToggleSource,+}: {+ runs: RunRecord[];+ leftId: string | null;+ rightId: string | null;+ onPickLeft: (id: string) => void;+ onPickRight: (id: string) => void;+ showSource: boolean;+ onToggleSource: () => void;+}) {+ const t = useT();+ const left = useMemo(() => runs.find((r) => r.id === leftId) ?? null, [runs, leftId]);+ const right = useMemo(() => runs.find((r) => r.id === rightId) ?? null, [runs, rightId]);+ const changes = useMemo<ChangeObject<string>[]>(() => {+ if (!showSource || !left || !right) return [];+ // Line-level diff over the raw HTML source. This is line-level not+ // visual; we explicitly punted on visual diff in the design.+ return diffLines(left.html, right.html);+ }, [showSource, left, right]);++ return (+ <div className="flex flex-1 min-h-0 flex-col">+ <div+ className="grid grid-cols-2 gap-1.5 px-3 py-2 text-[11px]"+ style={{ borderBottom: "1px solid var(--line-faint)" }}+ >+ <VersionPicker+ runs={runs}+ value={leftId}+ onChange={onPickLeft}+ label={t("history.diff.leftLabel")}+ />+ <VersionPicker+ runs={runs}+ value={rightId}+ onChange={onPickRight}+ label={t("history.diff.rightLabel")}+ />+ </div>+ <div+ className="flex items-center justify-between gap-2 px-3 py-2"+ style={{ borderBottom: "1px solid var(--line-faint)" }}+ >+ <label className="flex items-center gap-1.5 text-[11px] text-[var(--ink-mute)] cursor-pointer">+ <input+ type="checkbox"+ checked={showSource}+ onChange={onToggleSource}+ />+ {t("history.diff.showSource")}+ </label>+ {left && right && (+ <span className="font-mono text-[10px] text-[var(--ink-faint)] tabular-nums">+ v{left.version} → v{right.version}+ </span>+ )}+ </div>+ <div className="flex-1 min-h-0 overflow-hidden">+ {!left || !right ? (+ <div className="px-4 py-6 text-center text-[12px] text-[var(--ink-mute)]">+ {t("history.diff.pickPair")}+ </div>+ ) : showSource ? (+ <SourceDiff changes={changes} />+ ) : (+ <VisualDiff left={left} right={right} />+ )}+ </div>+ </div>+ );+}++function VersionPicker({+ runs,+ value,+ onChange,+ label,+}: {+ runs: RunRecord[];+ value: string | null;+ onChange: (id: string) => void;+ label: string;+}) {+ return (+ <label className="flex flex-col gap-1">+ <span className="text-[10px] uppercase tracking-[0.16em] text-[var(--ink-faint)]">+ {label}+ </span>+ <select+ value={value ?? ""}+ onChange={(e) => onChange(e.target.value)}+ className="w-full rounded-md bg-[var(--surface)] px-1.5 py-1 text-[11px] text-[var(--ink)] outline-none"+ style={{ border: "1px solid var(--line-faint)" }}+ >+ {runs.map((r) => (+ <option key={r.id} value={r.id}>+ v{r.version} · {(r.html.length / 1024).toFixed(1)} KB+ </option>+ ))}+ </select>+ </label>+ );+}++function VisualDiff({ left, right }: { left: RunRecord; right: RunRecord }) {+ // Two iframes rendering each version's HTML stacked vertically (the pane+ // is narrow at 280px so horizontal split would shrink each render below+ // any useful resolution). srcdoc is intentional: it sandboxes scripts and+ // keeps history previews from contaminating the real preview pane.+ const t = useT();+ return (+ <div className="flex h-full flex-col">+ <DiffIframe label={`v${left.version}`} html={left.html} caption={t("history.diff.before")} />+ <div className="h-px shrink-0" style={{ background: "var(--line-faint)" }} />+ <DiffIframe label={`v${right.version}`} html={right.html} caption={t("history.diff.after")} />+ </div>+ );+}++function DiffIframe({ html, label, caption }: { html: string; label: string; caption: string }) {+ const srcDoc = useMemo(() => previewHtml(html), [html]);+ return (+ <div className="relative flex-1 min-h-0">+ <div+ className="absolute left-1.5 top-1.5 z-10 rounded px-1.5 py-0.5 text-[9px] font-mono"+ style={{ background: "rgba(0,0,0,0.6)", color: "#fff" }}+ title={caption}+ >+ {label}+ </div>+ <iframe+ srcDoc={srcDoc}+ sandbox="allow-same-origin"+ className="h-full w-full"+ style={{ background: "#fff", border: 0 }}+ title={caption}+ />+ </div>+ );+}++function SourceDiff({ changes }: { changes: ChangeObject<string>[] }) {+ // Line diff rendered as plain monospaced text with added / removed lines+ // tinted green / red. We deliberately don't escape — DOMPurify isn't+ // needed because we render text content into a <pre>, not innerHTML.+ return (+ <div className="h-full overflow-auto bg-[var(--paper)] font-mono text-[10.5px] leading-snug">+ {changes.map((c, i) => {+ const lines = c.value.split("\n");+ // diffLines often leaves an empty trailing element after the last \n —+ // drop it so we don't render a blank ghost row per chunk.+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();+ const color = c.added+ ? "var(--green, #2f7d3a)"+ : c.removed+ ? "var(--red, #c0392b)"+ : "var(--ink-mute)";+ const bg = c.added+ ? "rgba(47, 125, 58, 0.08)"+ : c.removed+ ? "rgba(192, 57, 43, 0.08)"+ : "transparent";+ const prefix = c.added ? "+ " : c.removed ? "- " : " ";+ return (+ <div key={i} style={{ background: bg }}>+ {lines.map((line, j) => (+ <div+ key={j}+ className="whitespace-pre px-2"+ style={{ color }}+ >+ {prefix}+ {line}+ </div>+ ))}+ </div>+ );+ })}+ </div>+ );+}diff --git a/next/src/components/toolbar.tsx b/next/src/components/toolbar.tsxindex d7282f54..ba941ebc 100644--- a/next/src/components/toolbar.tsx+++ b/next/src/components/toolbar.tsx@@ -75,6 +75,7 @@ export function Toolbar({<div className="flex items-center gap-2"><LayoutModeToggle /><div className="hidden h-6 w-px sm:block" style={{ background: "var(--line)" }} />+ <HistoryToggle /><buttononClick={onOpenSettings}className="grid h-9 w-9 place-items-center rounded-full border text-[var(--ink-soft)] transition-all hover:border-[var(--ink)]/30 hover:text-[var(--ink)]"@@ -97,6 +98,32 @@ export function Toolbar({);}+function HistoryToggle() {+ const open = useStore((s) => s.historyPaneOpen);+ const setOpen = useStore((s) => s.setHistoryPaneOpen);+ const t = useT();+ return (+ <button+ onClick={() => setOpen(!open)}+ className="grid h-9 w-9 place-items-center rounded-full border text-[var(--ink-soft)] transition-all hover:border-[var(--ink)]/30 hover:text-[var(--ink)]"+ style={{+ background: open ? "var(--coral-soft)" : "var(--surface)",+ borderColor: open ? "var(--coral)" : "var(--line)",+ color: open ? "var(--coral)" : undefined,+ }}+ title={t("history.toggle")}+ aria-label={t("history.toggle")}+ aria-pressed={open}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">+ <path d="M3 12a9 9 0 1 0 3-6.7" />+ <polyline points="3 4 3 9 8 9" />+ <polyline points="12 7 12 12 15 14" />+ </svg>+ </button>+ );+}+function CommunityLinks() {const t = useT();const linkCls =diff --git a/next/src/lib/history/db.test.ts b/next/src/lib/history/db.test.tsnew file mode 100644index 00000000..e6780cfb--- /dev/null+++ b/next/src/lib/history/db.test.ts@@ -0,0 +1,138 @@+import * as FDB from "fake-indexeddb";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { PutRunInput } from "./db";++function installIndexedDB() {+ vi.stubGlobal("indexedDB", new FDB.IDBFactory());+ vi.stubGlobal("IDBKeyRange", FDB.IDBKeyRange);+ vi.stubGlobal("IDBCursor", FDB.IDBCursor);+ vi.stubGlobal("IDBCursorWithValue", FDB.IDBCursorWithValue);+ vi.stubGlobal("IDBDatabase", FDB.IDBDatabase);+ vi.stubGlobal("IDBIndex", FDB.IDBIndex);+ vi.stubGlobal("IDBObjectStore", FDB.IDBObjectStore);+ vi.stubGlobal("IDBOpenDBRequest", FDB.IDBOpenDBRequest);+ vi.stubGlobal("IDBRequest", FDB.IDBRequest);+ vi.stubGlobal("IDBTransaction", FDB.IDBTransaction);+ vi.stubGlobal("IDBVersionChangeEvent", FDB.IDBVersionChangeEvent);+}++async function loadHistoryDb() {+ vi.resetModules();+ return import("./db");+}++function runInput(taskId: string, versionHint: number): PutRunInput {+ return {+ taskId,+ html: `<main>version ${versionHint}</main>`,+ content: `content ${versionHint}`,+ ts: 1_700_000_000_000 + versionHint,+ stats: {+ outputBytes: versionHint,+ deltaCount: versionHint,+ },+ templateId: "article-magazine",+ };+}++describe("history IndexedDB store", () => {+ beforeEach(() => {+ installIndexedDB();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("increments versions per task and lists newest first", async () => {+ const { getRun, listRuns, putRun } = await loadHistoryDb();++ const first = await putRun(runInput("task-a", 1));+ const second = await putRun(runInput("task-a", 2));++ expect(first?.version).toBe(1);+ expect(first?.id).toBe("task-a__000001");+ expect(second?.version).toBe(2);+ expect(second?.id).toBe("task-a__000002");++ const rows = await listRuns("task-a");+ expect(rows.map((row) => row.version)).toEqual([2, 1]);+ expect(rows.map((row) => row.html)).toEqual([+ "<main>version 2</main>",+ "<main>version 1</main>",+ ]);++ await expect(getRun("task-a", 1)).resolves.toMatchObject({+ version: 1,+ content: "content 1",+ templateId: "article-magazine",+ });+ });++ it("keeps only the newest versions for a noisy task", async () => {+ const { MAX_VERSIONS_PER_TASK, listRuns, putRun } = await loadHistoryDb();++ for (let versionHint = 1; versionHint <= MAX_VERSIONS_PER_TASK + 1; versionHint++) {+ await putRun(runInput("task-noisy", versionHint));+ }++ const rows = await listRuns("task-noisy");+ expect(rows).toHaveLength(MAX_VERSIONS_PER_TASK);+ expect(rows.map((row) => row.version)).toEqual(+ Array.from({ length: MAX_VERSIONS_PER_TASK }, (_, index) => MAX_VERSIONS_PER_TASK + 1 - index),+ );+ expect(rows.at(-1)?.version).toBe(2);+ });++ it("isolates task histories and deletes only the selected task", async () => {+ const { deleteTaskRuns, listRuns, putRun } = await loadHistoryDb();++ await putRun(runInput("task-a", 1));+ await putRun(runInput("task-a", 2));+ await putRun(runInput("task-a", 3));+ await putRun(runInput("task-b", 1));++ await expect(listRuns("task-a")).resolves.toHaveLength(3);+ await expect(listRuns("task-b")).resolves.toHaveLength(1);++ await deleteTaskRuns("task-a");++ await expect(listRuns("task-a")).resolves.toEqual([]);+ await expect(listRuns("task-b")).resolves.toMatchObject([+ {+ taskId: "task-b",+ version: 1,+ },+ ]);+ });++ it("deletes individual runs without disturbing newer versions", async () => {+ const { deleteRun, getRun, listRuns, putRun } = await loadHistoryDb();++ await putRun(runInput("task-a", 1));+ await putRun(runInput("task-a", 2));+ await putRun(runInput("task-a", 3));++ await deleteRun("task-a", 2);++ await expect(getRun("task-a", 2)).resolves.toBeUndefined();+ await expect(listRuns("task-a")).resolves.toMatchObject([+ { version: 3 },+ { version: 1 },+ ]);+ });++ it("treats unavailable IndexedDB as a soft failure", async () => {+ vi.stubGlobal("indexedDB", undefined);+ vi.stubGlobal("IDBKeyRange", undefined);++ const { clearAll, deleteRun, deleteTaskRuns, getRun, listRuns, putRun } = await loadHistoryDb();++ await expect(putRun(runInput("task-a", 1))).resolves.toBeNull();+ await expect(listRuns("task-a")).resolves.toEqual([]);+ await expect(getRun("task-a", 1)).resolves.toBeUndefined();+ await expect(deleteRun("task-a", 1)).resolves.toBeUndefined();+ await expect(deleteTaskRuns("task-a")).resolves.toBeUndefined();+ await expect(clearAll()).resolves.toBeUndefined();+ });+});diff --git a/next/src/lib/history/db.ts b/next/src/lib/history/db.tsnew file mode 100644index 00000000..22688ae7--- /dev/null+++ b/next/src/lib/history/db.ts@@ -0,0 +1,196 @@+"use client";++/**+ * IndexedDB-backed history store for per-task HTML versions.+ *+ * Why IDB and not the existing zustand-persist (localStorage)? localStorage+ * caps around 5 MB origin-wide and our HTML payloads are routinely 30-100 KB+ * each. A handful of converted tasks with a dozen versions would push us past+ * the quota; the store would then silently drop writes. IndexedDB has gigabyte+ * budgets in every modern browser and stores binary-friendly Blobs without the+ * UTF-16 doubling tax localStorage pays.+ *+ * Versions live exclusively here — the zustand store keeps only the "current"+ * + "previous baseline" pair it needs for diff-edit mode.+ */++import { openDB, type DBSchema, type IDBPDatabase } from "idb";+import type { RunStats } from "@/lib/store";++const DB_NAME = "html-anything-history";+const DB_VERSION = 1;+const STORE = "runs";++/** Cap per task. Anything older rolls off so a single noisy task can't blow+ * through the user's IDB quota on its own. */+export const MAX_VERSIONS_PER_TASK = 20;++export type RunRecord = {+ /** `${taskId}__${version}` — monotonic, sortable, single primary key. */+ id: string;+ taskId: string;+ /** 1-based, increments on every commit for the same task. */+ version: number;+ html: string;+ content: string;+ /** Wall-clock time the run finished. */+ ts: number;+ /** Snapshot of the convert pipeline stats at commit time. */+ stats: RunStats;+ /** Template id at commit time — lets the history pane label entries even+ * if the user has since switched templates on the task. */+ templateId?: string;+};++interface HistoryDB extends DBSchema {+ [STORE]: {+ key: string;+ value: RunRecord;+ indexes: {+ "by-task": string;+ "by-task-version": [string, number];+ };+ };+}++let dbPromise: Promise<IDBPDatabase<HistoryDB>> | null = null;++function getDB(): Promise<IDBPDatabase<HistoryDB>> {+ if (typeof indexedDB === "undefined") {+ return Promise.reject(new Error("IndexedDB is not available in this environment"));+ }+ if (!dbPromise) {+ dbPromise = openDB<HistoryDB>(DB_NAME, DB_VERSION, {+ upgrade(db) {+ if (!db.objectStoreNames.contains(STORE)) {+ const store = db.createObjectStore(STORE, { keyPath: "id" });+ store.createIndex("by-task", "taskId");+ store.createIndex("by-task-version", ["taskId", "version"]);+ }+ },+ });+ }+ return dbPromise;+}++function makeId(taskId: string, version: number): string {+ return `${taskId}__${version.toString(36).padStart(6, "0")}`;+}++export type PutRunInput = Omit<RunRecord, "id" | "version">;++/**+ * Append a new version for the task. Returns the saved record (or null if+ * IDB is unavailable — caller treats that as a soft failure, history is a+ * nice-to-have, not load-bearing for the convert pipeline).+ */+export async function putRun(input: PutRunInput): Promise<RunRecord | null> {+ let db: IDBPDatabase<HistoryDB>;+ try {+ db = await getDB();+ } catch {+ return null;+ }+ const tx = db.transaction(STORE, "readwrite");+ const idx = tx.store.index("by-task-version");+ // Find the highest version for this task by walking the composite index+ // in reverse — single seek, no scan over other tasks.+ const cursor = await idx.openKeyCursor(+ IDBKeyRange.bound([input.taskId, -Infinity], [input.taskId, Infinity]),+ "prev",+ );+ const nextVersion = cursor ? (cursor.key as [string, number])[1] + 1 : 1;+ const record: RunRecord = {+ ...input,+ id: makeId(input.taskId, nextVersion),+ version: nextVersion,+ };+ await tx.store.put(record);+ await tx.done;+ // GC after commit so reads in the same tick don't see a half-pruned list.+ await pruneTask(input.taskId);+ return record;+}++/** Versions for a task, newest first. */+export async function listRuns(taskId: string): Promise<RunRecord[]> {+ let db: IDBPDatabase<HistoryDB>;+ try {+ db = await getDB();+ } catch {+ return [];+ }+ const rows = await db.getAllFromIndex(STORE, "by-task", taskId);+ rows.sort((a, b) => b.version - a.version);+ return rows;+}++export async function getRun(taskId: string, version: number): Promise<RunRecord | undefined> {+ let db: IDBPDatabase<HistoryDB>;+ try {+ db = await getDB();+ } catch {+ return undefined;+ }+ return db.get(STORE, makeId(taskId, version));+}++/** Drop every version belonging to a task (used by deleteTask). */+export async function deleteTaskRuns(taskId: string): Promise<void> {+ let db: IDBPDatabase<HistoryDB>;+ try {+ db = await getDB();+ } catch {+ return;+ }+ const tx = db.transaction(STORE, "readwrite");+ const idx = tx.store.index("by-task");+ for await (const cursor of idx.iterate(taskId)) {+ await cursor.delete();+ }+ await tx.done;+}++export async function deleteRun(taskId: string, version: number): Promise<void> {+ let db: IDBPDatabase<HistoryDB>;+ try {+ db = await getDB();+ } catch {+ return;+ }+ await db.delete(STORE, makeId(taskId, version));+}++/**+ * Keep the latest `MAX_VERSIONS_PER_TASK` versions per task — anything older+ * gets pruned. We iterate the composite index in descending order, skip the+ * first N keepers, and delete the tail.+ */+async function pruneTask(taskId: string): Promise<void> {+ const db = await getDB();+ const tx = db.transaction(STORE, "readwrite");+ const idx = tx.store.index("by-task-version");+ let kept = 0;+ for await (const cursor of idx.iterate(+ IDBKeyRange.bound([taskId, -Infinity], [taskId, Infinity]),+ "prev",+ )) {+ if (kept < MAX_VERSIONS_PER_TASK) {+ kept++;+ continue;+ }+ await cursor.delete();+ }+ await tx.done;+}++/** Test / dev helper — clears every run record. Not wired into the UI. */+export async function clearAll(): Promise<void> {+ let db: IDBPDatabase<HistoryDB>;+ try {+ db = await getDB();+ } catch {+ return;+ }+ await db.clear(STORE);+}diff --git a/next/src/lib/history/is-current.test.ts b/next/src/lib/history/is-current.test.tsnew file mode 100644index 00000000..6fba0149--- /dev/null+++ b/next/src/lib/history/is-current.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";+import type { RunRecord } from "./db";+import { isCurrentRun } from "./is-current";++function record(version: number, html: string): RunRecord {+ return {+ id: `task-a__${String(version).padStart(6, "0")}`,+ taskId: "task-a",+ version,+ html,+ content: `content ${version}`,+ ts: 1_700_000_000_000 + version,+ stats: { outputBytes: html.length, deltaCount: 0 },+ templateId: "article-magazine",+ };+}++describe("isCurrentRun", () => {+ it("flags the newest run when its html matches the editor", () => {+ const v2 = record(2, "<main>v2</main>");+ const v1 = record(1, "<main>v1</main>");+ const runs = [v2, v1];++ expect(isCurrentRun(v2, runs, v2.html)).toBe(true);+ expect(isCurrentRun(v1, runs, v2.html)).toBe(false);+ });++ it("does not flag an older byte-identical run as current after restore", () => {+ // After restoring v1, commitBase appends a fresh v3 whose html equals v1's html.+ // The old isCurrent (pure content equality) wrongly flagged BOTH v3 and v1+ // as current and disabled Restore on the genuinely-historical v1.+ const sharedHtml = "<main>v1</main>";+ const v3 = record(3, sharedHtml);+ const v2 = record(2, "<main>v2</main>");+ const v1 = record(1, sharedHtml);+ const runs = [v3, v2, v1];++ expect(isCurrentRun(v3, runs, sharedHtml)).toBe(true);+ expect(isCurrentRun(v1, runs, sharedHtml)).toBe(false);+ expect(isCurrentRun(v2, runs, sharedHtml)).toBe(false);+ });++ it("drops the current flag when the editor html drifts from the newest run", () => {+ const v2 = record(2, "<main>v2</main>");+ const v1 = record(1, "<main>v1</main>");+ const runs = [v2, v1];++ // User edited the editor after the last commit — no row is live anymore.+ expect(isCurrentRun(v2, runs, "<main>v2 edited</main>")).toBe(false);+ expect(isCurrentRun(v1, runs, "<main>v2 edited</main>")).toBe(false);+ });++ it("returns false against an empty runs list", () => {+ const orphan = record(1, "<main>v1</main>");+ expect(isCurrentRun(orphan, [], orphan.html)).toBe(false);+ });+});diff --git a/next/src/lib/history/is-current.ts b/next/src/lib/history/is-current.tsnew file mode 100644index 00000000..e4fb21c9--- /dev/null+++ b/next/src/lib/history/is-current.ts@@ -0,0 +1,19 @@+import type { RunRecord } from "./db";++/**+ * A run is "current" only when it is the newest row *and* its html still+ * matches the editor. Anchoring on the newest id (not just html equality)+ * is what makes restore correct: `commitBase` appends a new row whose html+ * equals the restored row's html, so a pure content check would flag both+ * as current and disable Restore on the older identical version.+ *+ * `runs` must be the listRuns ordering (newest first); `runs[0]` is the+ * live version.+ */+export function isCurrentRun(+ run: RunRecord,+ runs: RunRecord[],+ activeHtml: string,+): boolean {+ return run.id === runs[0]?.id && run.html === activeHtml;+}diff --git a/next/src/lib/i18n.ts b/next/src/lib/i18n.tsindex cfd894a7..70ba0b9d 100644--- a/next/src/lib/i18n.ts+++ b/next/src/lib/i18n.ts@@ -225,6 +225,28 @@ export interface Dict {"tasks.defaultName": string;"tasks.matchTooltip": string;+ // History pane+ "history.toggle": string;+ "history.heading": string;+ "history.close": string;+ "history.versionCap": string;+ "history.current": string;+ "history.compare": string;+ "history.restore": string;+ "history.delete": string;+ "history.loading": string;+ "history.empty.noTask": string;+ "history.empty.noVersions": string;+ "history.restoreConfirm": string;+ "history.deleteConfirm": string;+ "history.backToList": string;+ "history.diff.leftLabel": string;+ "history.diff.rightLabel": string;+ "history.diff.showSource": string;+ "history.diff.pickPair": string;+ "history.diff.before": string;+ "history.diff.after": string;+// Community / upstream link entry points"community.starOnGitHub": string;"community.joinDiscord": string;@@ -551,6 +573,27 @@ const en: Dict = {"tasks.defaultName": "Task {n}","tasks.matchTooltip": "{a} / {b} match",+ "history.toggle": "Version history",+ "history.heading": "history",+ "history.close": "Close history",+ "history.versionCap": "Up to {n} versions per task",+ "history.current": "current",+ "history.compare": "Compare",+ "history.restore": "Restore",+ "history.delete": "Delete version",+ "history.loading": "Loading versions…",+ "history.empty.noTask": "No active task.",+ "history.empty.noVersions": "No versions yet. Run Convert to start the history.",+ "history.restoreConfirm": "Restore version v{v}? The current preview will be replaced.",+ "history.deleteConfirm": "Delete version v{v}? This cannot be undone.",+ "history.backToList": "Back",+ "history.diff.leftLabel": "Before",+ "history.diff.rightLabel": "After",+ "history.diff.showSource": "Show DOM diff",+ "history.diff.pickPair": "Pick two versions to compare.",+ "history.diff.before": "Before",+ "history.diff.after": "After",+"community.starOnGitHub": "Star on GitHub","community.joinDiscord": "Join Discord","community.upstreamHint": "The upstream design system this is built on",@@ -870,6 +913,27 @@ const zhCN: Dict = {"tasks.defaultName": "任务 {n}","tasks.matchTooltip": "{a} / {b} 匹配",+ "history.toggle": "版本历史",+ "history.heading": "历史",+ "history.close": "关闭历史",+ "history.versionCap": "每个任务最多保留 {n} 个版本",+ "history.current": "当前",+ "history.compare": "对比",+ "history.restore": "恢复",+ "history.delete": "删除版本",+ "history.loading": "正在加载版本…",+ "history.empty.noTask": "暂无活动任务。",+ "history.empty.noVersions": "还没有版本。运行一次 Convert 即可生成历史。",+ "history.restoreConfirm": "恢复到版本 v{v}? 当前预览将被替换。",+ "history.deleteConfirm": "删除版本 v{v}? 该操作不可撤销。",+ "history.backToList": "返回",+ "history.diff.leftLabel": "旧",+ "history.diff.rightLabel": "新",+ "history.diff.showSource": "显示 DOM 差异",+ "history.diff.pickPair": "请选择两个要对比的版本。",+ "history.diff.before": "旧版本",+ "history.diff.after": "新版本",+"community.starOnGitHub": "在 GitHub 上 Star","community.joinDiscord": "加入 Discord","community.upstreamHint": "本项目所基于的上游设计系统",diff --git a/next/src/lib/store.ts b/next/src/lib/store.tsindex 37a9874b..162ab443 100644--- a/next/src/lib/store.ts+++ b/next/src/lib/store.ts@@ -3,6 +3,7 @@import { useEffect, useState } from "react";import { create } from "zustand";import { persist } from "zustand/middleware";+import { deleteTaskRuns, putRun } from "@/lib/history/db";export type ModelOption = { id: string; label: string };@@ -175,6 +176,8 @@ type Persisted = {agentBinOverrides: Record<string, string>;welcomeAck: boolean;sidebarCollapsed: boolean;+ /** Whether the per-task version history pane is open next to the tasks sidebar. */+ historyPaneOpen: boolean;locale: Locale;layoutMode: LayoutMode;};@@ -193,6 +196,7 @@ type State = {agentBinOverrides: Record<string, string>;welcomeAck: boolean;sidebarCollapsed: boolean;+ historyPaneOpen: boolean;locale: Locale;layoutMode: LayoutMode;@@ -257,6 +261,7 @@ type State = {setAgentBinOverride: (agentId: string, path: string) => void;setWelcomeAck: (v: boolean) => void;setSidebarCollapsed: (v: boolean) => void;+ setHistoryPaneOpen: (v: boolean) => void;setLocale: (l: Locale) => void;setLayoutMode: (m: LayoutMode) => void;};@@ -285,6 +290,7 @@ export const useStore = create<State>()(agentBinOverrides: {},welcomeAck: false,sidebarCollapsed: false,+ historyPaneOpen: false,locale: "en",layoutMode: "split",@@ -301,12 +307,14 @@ export const useStore = create<State>()(// never leave 0 tasks — replace with a fresh empty oneconst fresh = makeTask({ name: "任务 1" });set({ tasks: [fresh], activeTaskId: fresh.id });+ void deleteTaskRuns(id).catch(() => {});return;}const next = tasks.filter((t) => t.id !== id);const nextActive =activeTaskId === id ? next[Math.max(0, tasks.findIndex((t) => t.id === id) - 1)]?.id ?? next[0].id : activeTaskId;set({ tasks: next, activeTaskId: nextActive });+ void deleteTaskRuns(id).catch(() => {});},setActiveTask: (id) => {if (get().tasks.some((t) => t.id === id)) set({ activeTaskId: id });@@ -410,13 +418,38 @@ export const useStore = create<State>()(set((st) => ({tasks: patchTask(st.tasks, taskId, (t) => ({ stats: { ...t.stats, ...patch } })),})),- commitBaseFor: (taskId) =>+ commitBaseFor: (taskId) => {+ // Snapshot the freshly converted (content, html) as the next diff-edit+ // baseline, then archive it to IndexedDB so the history pane has a+ // version to render. IDB write is fire-and-forget — history is a+ // nice-to-have and must not block the convert pipeline.+ type Snap = { content: string; html: string; stats: RunStats; templateId: string };+ let snapshot: Snap | null = null;set((st) => ({- tasks: patchTask(st.tasks, taskId, (t) => ({- baseContent: t.content,- baseHtml: t.html,- })),- })),+ tasks: patchTask(st.tasks, taskId, (t) => {+ snapshot = {+ content: t.content,+ html: t.html,+ stats: t.stats,+ templateId: t.templateId,+ };+ return { baseContent: t.content, baseHtml: t.html };+ }),+ }));+ const snap = snapshot as Snap | null;+ if (snap && snap.html) {+ void putRun({+ taskId,+ html: snap.html,+ content: snap.content,+ stats: snap.stats,+ templateId: snap.templateId,+ ts: Date.now(),+ }).catch(() => {+ // history is best-effort; ignore quota / private-mode failures+ });+ }+ },pushDeploymentFor: (taskId, deployment) =>set((st) => ({tasks: patchTask(st.tasks, taskId, (t) => {@@ -449,6 +482,7 @@ export const useStore = create<State>()(}),setWelcomeAck: (v) => set({ welcomeAck: v }),setSidebarCollapsed: (v) => set({ sidebarCollapsed: v }),+ setHistoryPaneOpen: (v) => set({ historyPaneOpen: v }),setLocale: (l) => set({ locale: l }),setLayoutMode: (m) => set({ layoutMode: m }),}),@@ -469,6 +503,7 @@ export const useStore = create<State>()(agentBinOverrides: s.agentBinOverrides,welcomeAck: s.welcomeAck,sidebarCollapsed: s.sidebarCollapsed,+ historyPaneOpen: s.historyPaneOpen,locale: s.locale,layoutMode: s.layoutMode,}),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d37a468d..fb23ee34 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -35,12 +35,18 @@ importers:clsx:specifier: ^2.1.1version: 2.1.1+ diff:+ specifier: ^9.0.0+ version: 9.0.0dompurify:specifier: ^3.4.2version: 3.4.2highlight.js:specifier: ^11.11.1version: 11.11.1+ idb:+ specifier: ^8.0.3+ version: 8.0.3jszip:specifier: ^3.10.1version: 3.10.1@@ -96,6 +102,9 @@ importers:'@types/react-dom':specifier: ^19version: 19.2.3(@types/[email protected])+ fake-indexeddb:+ specifier: ^6.2.5+ version: 6.2.5happy-dom:specifier: ^20.9.0version: 20.9.0@@ -863,6 +872,10 @@ packages:resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}engines: {node: '>=8'}+ resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}+ engines: {node: '>=0.3.1'}+resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}@@ -917,6 +930,10 @@ packages:resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}engines: {node: '>=12.0.0'}+ resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}engines: {node: '>=12.0.0'}@@ -961,6 +978,9 @@ packages:resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==}+resolution: {integrity: sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==}engines: {node: '>=16.x'}@@ -1981,6 +2001,8 @@ snapshots:+ [email protected]: {}+dependencies:domelementtype: 2.3.0@@ -2058,6 +2080,8 @@ snapshots:+ [email protected]: {}+optionalDependencies:picomatch: 4.0.4@@ -2099,6 +2123,8 @@ snapshots:dependencies:safer-buffer: 2.1.2+ [email protected]: {}+dependencies:queue: 6.0.2