Repository Public
1"use client";2import Link from "next/link";3import { useMemo, useState } from "react";4import { useLocale } from "@/i18n/client";5import { dict, fill, KIND_LABEL, LEVEL_LABEL } from "@/i18n/dict";6import { api, idempotencyKey } from "@/lib/client-api";7import { FORMATS, KINDS, LEVELS, THEMES, type Locale } from "@/schema";8import type { Brief, Outline } from "@/ai/prompts";9import type { OutlineOutput, GenerateOutput } from "@/ai/pipeline";10import type { JobView } from "@/server/jobs";11import type { AssetView } from "@/server/assets";12import { JobProgress, useJob } from "./job";13import { errorText, money, Notice, PageHeader, useApi } from "./ui";1415const T = dict({16 title: ["Nouvelle fiche", "New sheet"], lead: ["Décrivez la fiche. Claude propose d’abord un plan, que vous corrigez avant de lancer la rédaction complète.", "Describe the sheet. Claude first proposes a plan, which you correct before launching the full draft."],17 prompt: ["Votre demande", "Your request"], promptPh: ["Crée une fiche sur l’architecture Mixture of Experts, explique le top-k routing, ajoute une équation et une simulation interactive.", "Create a sheet on the Mixture of Experts architecture, explain top-k routing, add an equation and an interactive simulation."],18 language: ["Langue de la fiche", "Language of the sheet"], level: ["Niveau", "Level"], kind: ["Type de fiche", "Kind of sheet"], length: ["Longueur", "Length"], format: ["Format", "Format"], theme: ["Style", "Style"],19 audience: ["Public visé", "Audience"], audiencePh: ["Étudiants de maîtrise en finance", "Graduate students in finance"], constraints: ["Contraintes", "Constraints"],20 constraintsPh: ["Notation à respecter, points à couvrir ou à éviter…", "Notation to follow, points to cover or avoid…"],21 short: ["Courte (8–12 blocs)", "Short (8–12 blocks)"], standard: ["Standard (14–20 blocs)", "Standard (14–20 blocks)"], long: ["Longue (22–30 blocs)", "Long (22–30 blocks)"],22 sources: ["Documents à lire", "Material to read"], sourcesHelp: ["PDF, texte, CSV, JSON ou image. Claude les lit comme des données ; il ne suit pas les instructions qu’ils contiennent.", "PDF, text, CSV, JSON or image. Claude reads them as data; it does not follow instructions found inside them."],23 upload: ["Ajouter un fichier", "Add a file"], links: ["Liens à lire (https)", "Links to read (https)"], linksHelp: ["Un lien par ligne, 5 au plus. Le serveur récupère la page ; sans lien ni document, Claude travaille de mémoire et ses références sont marquées « non vérifiées ».",24 "One link per line, 5 at most. The server fetches the page; without links or documents Claude works from memory and its references are marked “unverified”."],25 plan: ["Proposer un plan", "Propose a plan"], direct: ["Générer sans plan", "Generate without a plan"], more: ["Options", "Options"],26 planTitle: ["Plan proposé", "Proposed plan"], planLead: ["Corrigez ce qui doit l’être : la rédaction suivra ce plan.", "Correct whatever needs it: the draft will follow this plan."],27 sheetTitle: ["Titre", "Title"], summary: ["Résumé", "Summary"], objectives: ["Objectifs pédagogiques (un par ligne)", "Learning objectives (one per line)"], sections: ["Sections", "Sections"],28 visual: ["Plan visuel", "Visual plan"], planned: ["Références envisagées", "References considered"], fromMaterial: ["dans vos documents", "in your material"], fromMemory: ["de mémoire — à vérifier", "from memory — to be checked"],29 questions: ["Questions ouvertes", "Open questions"], generate: ["Générer la fiche", "Generate the sheet"], redo: ["Refaire le plan", "Redo the plan"], back: ["Modifier la demande", "Edit the request"],30 estimate: ["Estimation pour la rédaction : environ {usd} ({blocks} blocs, modèle {model}). Le coût réel s’affiche pendant la génération.", "Estimate for the draft: about {usd} ({blocks} blocks, model {model}). The actual cost is shown while it runs."],31 spent: ["Coût du plan : {usd}.", "Cost of the plan: {usd}."], notConfigured: ["La génération par Claude n’est pas configurée sur ce serveur (clé API absente). Vous pouvez créer une fiche vide ou partir d’un modèle.", "Generation by Claude is not configured on this server (no API key). You can create an empty sheet or start from a template."],32 other: ["Autres points de départ", "Other starting points"], empty: ["Fiche vide", "Empty sheet"], template: ["Partir d’un modèle", "Start from a template"], remove: ["Retirer", "Remove"], removeSection: ["Retirer la section", "Remove section"],33 warnings: ["À noter", "Note"], opening: ["Ouverture de l’éditeur…", "Opening the editor…"], cancelled: ["Génération annulée. Rien n’a été créé.", "Generation cancelled. Nothing was created."],34});35const THEME_LABEL: Record<(typeof THEMES)[number], [string, string]> = { "scientific-light": ["Scientifique clair", "Scientific light"], "scientific-dark": ["Scientifique sombre", "Scientific dark"], editorial: ["Éditorial", "Editorial"], blueprint: ["Plan technique", "Blueprint"], finance: ["Finance", "Finance"] };36const FORMAT_LABEL: Record<(typeof FORMATS)[number], [string, string]> = { article: ["Article responsive", "Responsive article"], a4: ["A4", "A4"], "slide-16-9": ["Présentation 16:9", "Slide 16:9"], square: ["Carré (réseaux sociaux)", "Square (social)"], "portrait-4-5": ["Vertical 4:5", "Portrait 4:5"] };3738interface SettingsInfo { settings: { aiModel: string }; environment: { anthropicKeySet: boolean; defaultModel: string }; models: { id: string; price: { input: number; output: number } }[] }3940export function NewSheet() {41 const locale = useLocale(), fr = locale === "fr", t = T(locale);42 const info = useApi<SettingsInfo>("/api/admin/settings");43 const [brief, setBrief] = useState<Brief>({ prompt: "", locale, audience: "", level: "intermediate", kind: "explainer", length: "standard", format: "article", theme: "scientific-light", constraints: "", attachments: [], urls: [] });44 const [files, setFiles] = useState<AssetView[]>([]), [links, setLinks] = useState(""), [uploading, setUploading] = useState(false);45 const [step, setStep] = useState<"brief" | "outline">("brief");46 const [outline, setOutline] = useState<Outline | null>(null), [planMeta, setPlanMeta] = useState<OutlineOutput | null>(null);47 const [jobId, setJobId] = useState<string | null>(null), [error, setError] = useState<string | null>(null), [note, setNote] = useState<string | null>(null);4849 const model = info.data ? info.data.settings.aiModel || info.data.environment.defaultModel : "";50 const price = info.data?.models.find((m) => m.id === model)?.price;51 const set = <K extends keyof Brief>(k: K, v: Brief[K]) => setBrief((b) => ({ ...b, [k]: v }));52 const fullBrief = useMemo<Brief>(() => ({ ...brief, attachments: files.map((f) => f.id), urls: links.split(/\s+/).map((s) => s.trim()).filter(Boolean).slice(0, 5) }), [brief, files, links]);5354 const job = useJob(jobId, (j: JobView) => {55 if (j.status === "succeeded" && j.kind === "outline") { const o = j.output as OutlineOutput; setOutline(o.outline); setPlanMeta(o); setStep("outline"); setJobId(null); }56 else if (j.status === "succeeded" && j.kind === "generate") { setNote(t.opening); window.location.assign(`/admin/sheets/${(j.output as GenerateOutput).sheetId}/edit`); }57 else if (j.status === "cancelled") { setJobId(null); setNote(t.cancelled); }58 });59 const running = !!job && (job.status === "queued" || job.status === "running");6061 const start = async (kind: "outline" | "generate", withOutline: Outline | null) => {62 setError(null); setNote(null);63 try { const j = await api<JobView>("/api/admin/generations", { body: { kind, brief: fullBrief, ...(kind === "generate" ? { outline: withOutline } : {}), idempotencyKey: idempotencyKey() } }); setJobId(j.id); }64 catch (e) { setError(errorText(e, fr)); }65 };66 const upload = async (list: FileList | null) => {67 if (!list?.length) return;68 setUploading(true); setError(null);69 for (const file of Array.from(list).slice(0, 8 - files.length)) {70 const form = new FormData(); form.set("file", file);71 try { const a = await api<AssetView>("/api/admin/assets", { form }); setFiles((f) => [...f, a]); } catch (e) { setError(`${file.name} : ${errorText(e, fr)}`); }72 }73 setUploading(false);74 };75 const createEmpty = async () => { try { const r = await api<{ id: string }>("/api/admin/sheets", { body: { locale: brief.locale } }); window.location.assign(`/admin/sheets/${r.id}/edit`); } catch (e) { setError(errorText(e, fr)); } };7677 const estimate = planMeta && price ? ((planMeta.usage.inputTokens + 16000) * price.input + planMeta.estimate.outputTokens * 1.6 * price.output) / 1e6 : null;78 const label = "grid gap-1.5 text-sm font-medium", sel = "field";79 const configured = info.data?.environment.anthropicKeySet !== false;8081 return (82 <div className="mx-auto max-w-3xl">83 <PageHeader title={t.title} lead={t.lead} />84 {!configured && <div className="mb-5"><Notice tone="warn">{t.notConfigured}</Notice></div>}8586 {step === "brief" && (87 <form className="grid gap-5" onSubmit={(e) => { e.preventDefault(); void start("outline", null); }}>88 <label className={label} htmlFor="prompt">{t.prompt}89 <textarea id="prompt" className="field min-h-36 leading-relaxed" value={brief.prompt} onChange={(e) => set("prompt", e.target.value)} placeholder={t.promptPh} required minLength={8} maxLength={6000} autoFocus /></label>90 <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">91 <label className={label}>{t.language}<select className={sel} value={brief.locale} onChange={(e) => set("locale", e.target.value as Locale)}><option value="fr">Français</option><option value="en">English</option></select></label>92 <label className={label}>{t.level}<select className={sel} value={brief.level} onChange={(e) => set("level", e.target.value as Brief["level"])}>{LEVELS.map((x) => <option key={x} value={x}>{LEVEL_LABEL(locale)[x]}</option>)}</select></label>93 <label className={label}>{t.kind}<select className={sel} value={brief.kind} onChange={(e) => set("kind", e.target.value as Brief["kind"])}>{KINDS.map((x) => <option key={x} value={x}>{KIND_LABEL(locale)[x]}</option>)}</select></label>94 <label className={label}>{t.length}<select className={sel} value={brief.length} onChange={(e) => set("length", e.target.value as Brief["length"])}><option value="short">{t.short}</option><option value="standard">{t.standard}</option><option value="long">{t.long}</option></select></label>95 <label className={label}>{t.format}<select className={sel} value={brief.format} onChange={(e) => set("format", e.target.value as Brief["format"])}>{FORMATS.map((x) => <option key={x} value={x}>{FORMAT_LABEL[x][fr ? 0 : 1]}</option>)}</select></label>96 <label className={label}>{t.theme}<select className={sel} value={brief.theme} onChange={(e) => set("theme", e.target.value as Brief["theme"])}>{THEMES.map((x) => <option key={x} value={x}>{THEME_LABEL[x][fr ? 0 : 1]}</option>)}</select></label>97 </div>98 <details className="card px-4">99 <summary className="flex min-h-12 cursor-pointer items-center font-semibold">{t.more}</summary>100 <div className="grid gap-4 pb-4">101 <label className={label}>{t.audience}<input className="field" value={brief.audience} onChange={(e) => set("audience", e.target.value)} placeholder={t.audiencePh} maxLength={200} /></label>102 <label className={label}>{t.constraints}<textarea className="field min-h-20" value={brief.constraints} onChange={(e) => set("constraints", e.target.value)} placeholder={t.constraintsPh} maxLength={2000} /></label>103 <fieldset className="grid gap-2">104 <legend className="text-sm font-medium">{t.sources}</legend>105 <p className="text-sm text-faint">{t.sourcesHelp}</p>106 {files.length > 0 && <ul className="grid gap-2">{files.map((f) => <li key={f.id} className="flex items-center justify-between gap-3 rounded-lg border border-line px-3 py-2 text-sm"><span className="min-w-0 truncate">{f.filename} <span className="text-faint">· {f.kind} · {Math.ceil(f.bytes / 1024)} ko</span></span><button type="button" className="btn btn-ghost btn-sm" onClick={() => setFiles((x) => x.filter((y) => y.id !== f.id))}>{t.remove}</button></li>)}</ul>}107 <label className="btn w-fit cursor-pointer">{uploading ? "…" : t.upload}<input type="file" multiple className="sr-only" accept=".pdf,.txt,.md,.csv,.json,.png,.jpg,.jpeg,.webp,application/pdf,text/*,image/*" onChange={(e) => { void upload(e.target.files); e.target.value = ""; }} disabled={uploading || files.length >= 8} /></label>108 </fieldset>109 <label className={label}>{t.links}<textarea className="field min-h-20 font-mono text-sm" value={links} onChange={(e) => setLinks(e.target.value)} placeholder="https://arxiv.org/abs/1706.03762" inputMode="url" autoCapitalize="none" spellCheck={false} /><span className="font-normal text-faint">{t.linksHelp}</span></label>110 </div>111 </details>112 {error && <Notice tone="bad">{error}</Notice>}113 {note && <Notice>{note}</Notice>}114 {job && <JobProgress job={job} />}115 <div className="flex flex-wrap gap-3">116 <button className="btn btn-primary" disabled={running || !configured || brief.prompt.trim().length < 8}>{t.plan}</button>117 <button type="button" className="btn" disabled={running || !configured || brief.prompt.trim().length < 8} onClick={() => void start("generate", null)}>{t.direct}</button>118 </div>119 <div className="mt-4 border-t border-line pt-5">120 <p className="eyebrow mb-3">{t.other}</p>121 <div className="flex flex-wrap gap-3"><Link className="btn" href="/admin/templates">{t.template}</Link><button type="button" className="btn" onClick={createEmpty}>{t.empty}</button></div>122 </div>123 </form>124 )}125126 {step === "outline" && outline && (127 <div className="grid gap-5">128 <div><h2 className="font-display text-2xl font-semibold">{t.planTitle}</h2><p className="mt-1 text-muted">{t.planLead}</p></div>129 {planMeta && planMeta.warnings.length > 0 && <Notice tone="warn"><strong>{t.warnings} :</strong><ul className="mt-1 list-disc pl-5">{planMeta.warnings.map((w, i) => <li key={i}>{w}</li>)}</ul></Notice>}130 <label className={label}>{t.sheetTitle}<input className="field" value={outline.title} maxLength={160} onChange={(e) => setOutline({ ...outline, title: e.target.value })} /></label>131 <label className={label}>{t.summary}<textarea className="field min-h-20" value={outline.summary} maxLength={400} onChange={(e) => setOutline({ ...outline, summary: e.target.value })} /></label>132 <label className={label}>{t.objectives}<textarea className="field min-h-24" value={outline.objectives.join("\n")} onChange={(e) => setOutline({ ...outline, objectives: e.target.value.split("\n").map((s) => s.slice(0, 300)).filter((s, i, a) => s.trim() || i === a.length - 1).slice(0, 6) })} /></label>133 <fieldset className="grid gap-3">134 <legend className="mb-1 text-sm font-medium">{t.sections}</legend>135 {outline.sections.map((s, i) => (136 <div key={i} className="card grid gap-2 p-3">137 <div className="flex gap-2">138 <input className="field font-semibold" aria-label={`${t.sections} ${i + 1}`} value={s.heading} maxLength={160} onChange={(e) => setOutline({ ...outline, sections: outline.sections.map((x, k) => (k === i ? { ...x, heading: e.target.value } : x)) })} />139 <button type="button" className="btn btn-ghost !px-3" aria-label={t.removeSection} disabled={outline.sections.length <= 1} onClick={() => setOutline({ ...outline, sections: outline.sections.filter((_, k) => k !== i) })}>✕</button>140 </div>141 <textarea className="field min-h-16 text-sm" aria-label={`${t.sections} ${i + 1} — purpose`} value={s.purpose} maxLength={400} onChange={(e) => setOutline({ ...outline, sections: outline.sections.map((x, k) => (k === i ? { ...x, purpose: e.target.value } : x)) })} />142 <ul className="flex flex-wrap gap-1.5 text-xs text-muted">{s.blocks.map((b, k) => <li key={k} className="rounded-md border border-line px-2 py-1" title={b.intent}><span className="font-mono">{b.type}</span> — {b.intent.slice(0, 70)}</li>)}</ul>143 </div>144 ))}145 </fieldset>146 <label className={label}>{t.visual}<textarea className="field min-h-24" value={outline.visualPlan} maxLength={1200} onChange={(e) => setOutline({ ...outline, visualPlan: e.target.value })} /></label>147 {outline.sourcesPlanned.length > 0 && <div><p className="text-sm font-medium">{t.planned}</p><ul className="mt-2 grid gap-1.5 text-sm">{outline.sourcesPlanned.map((s, i) => <li key={i} className="rounded-lg border border-line px-3 py-2">{s.title} <span className={s.fromMaterial ? "text-ok" : "text-warn"}>· {s.fromMaterial ? t.fromMaterial : t.fromMemory}</span></li>)}</ul></div>}148 {outline.openQuestions.length > 0 && <Notice><strong>{t.questions}</strong><ul className="mt-1 list-disc pl-5">{outline.openQuestions.map((q, i) => <li key={i}>{q}</li>)}</ul></Notice>}149 <p className="text-sm text-faint">150 {planMeta && fill(t.spent, { usd: money(planMeta.usage.costUsd) })}{" "}151 {estimate !== null && planMeta && fill(t.estimate, { usd: money(estimate), blocks: planMeta.estimate.blocks, model })}152 </p>153 {error && <Notice tone="bad">{error}</Notice>}154 {note && <Notice>{note}</Notice>}155 {job && <JobProgress job={job} />}156 <div className="flex flex-wrap gap-3">157 <button type="button" className="btn btn-primary" disabled={running || !outline.title.trim()} onClick={() => void start("generate", { ...outline, objectives: outline.objectives.filter((o) => o.trim()) })}>{t.generate}</button>158 <button type="button" className="btn" disabled={running} onClick={() => void start("outline", null)}>{t.redo}</button>159 <button type="button" className="btn btn-ghost" disabled={running} onClick={() => setStep("brief")}>{t.back}</button>160 </div>161 </div>162 )}163 </div>164 );165}166