feat(writing): auto-title suggestion in the briefing

The plan's open question on title-handling — "Topic = initialer Titel,
beim ersten Generate Auto-Title-Vorschlag anbieten" — answered with a
small -button next to the title input.

- prompt-builder: buildTitleSuggestionPrompt(input) returns a system+
  user pair that asks for a single 4–8-word title in the briefing's
  language. System prompt is strict: no quotes, no period, no "Titel:"
  prefix, no Markdown — so the result drops cleanly into the input
  field. cleanSuggestedTitle() strips wrapping quotes (straight + curly,
  single + double + German „"), a "Titel:" prefix, and a trailing
  period as a defense-in-depth pass.
- BriefingForm: -button next to the title input, disabled until the
  topic field has content (the suggestion needs context). On click it
  calls callWritingGeneration with the title prompt + temperature 0.6
  + maxTokens 60. In edit mode it pulls an excerpt of the current
  version (up to 800 chars) so the title hugs the actual prose, not
  just the briefing.
- The button shows a "…" while running and an error inline if the
  call fails — non-blocking, the user can still type their own title
  and save.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Till JS 2026-04-25 12:16:45 +02:00
parent 636138b2d4
commit a80e8f57a0
2 changed files with 176 additions and 2 deletions

View file

@ -7,6 +7,9 @@
<script lang="ts">
import { KIND_LABELS, TONE_PRESETS, LENGTH_PRESETS, DEFAULT_LANGUAGE } from '../constants';
import { draftsStore } from '../stores/drafts.svelte';
import { callWritingGeneration } from '../api';
import { buildTitleSuggestionPrompt, cleanSuggestedTitle } from '../utils/prompt-builder';
import { useCurrentVersionForDraft } from '../queries';
import StylePicker from './StylePicker.svelte';
import ReferencePicker from './ReferencePicker.svelte';
import type { Draft, DraftKind, DraftBriefing, DraftReference } from '../types';
@ -68,6 +71,57 @@
let saving = $state(false);
let error = $state<string | null>(null);
let suggestingTitle = $state(false);
// In edit mode we can hand the model an excerpt of the current
// version so the title hugs the actual prose, not just the briefing.
// In create mode there's nothing to excerpt yet.
/* svelte-ignore state_referenced_locally */
const currentVersion$ = draft ? useCurrentVersionForDraft(draft.id) : null;
const currentExcerpt = $derived.by<string | undefined>(() => {
const content = currentVersion$?.value?.content;
if (!content) return undefined;
return content.length > 800 ? content.slice(0, 800) + '…' : content;
});
async function suggestTitle() {
if (suggestingTitle) return;
const trimmedTopic = topic.trim();
if (!trimmedTopic) {
error = 'Bitte erst ein Thema eingeben — der Vorschlag braucht Kontext.';
return;
}
suggestingTitle = true;
error = null;
try {
const prompt = buildTitleSuggestionPrompt({
kind,
briefing: {
topic: trimmedTopic,
audience: audience.trim() || null,
tone: tone.trim() || null,
language,
extraInstructions: extraInstructions.trim() || null,
},
excerpt: currentExcerpt,
});
const result = await callWritingGeneration({
systemPrompt: prompt.system,
userPrompt: prompt.user,
kind: 'title-suggestion',
temperature: 0.6,
// Titles are 48 words; 60 tokens is enough headroom even
// for a chatty model that adds whitespace.
maxTokens: 60,
});
const cleaned = cleanSuggestedTitle(result.output);
if (cleaned) title = cleaned;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally {
suggestingTitle = false;
}
}
// When the user switches kind while creating a new draft, nudge the
// target length to that kind's preset so they don't have to touch it.
@ -128,8 +182,25 @@
<div class="row">
<label>
<span>Titel</span>
<!-- svelte-ignore a11y_autofocus -->
<input type="text" bind:value={title} placeholder="Mein Blogpost über …" required autofocus />
<div class="title-row">
<!-- svelte-ignore a11y_autofocus -->
<input
type="text"
bind:value={title}
placeholder="Mein Blogpost über …"
required
autofocus
/>
<button
type="button"
class="suggest-btn"
onclick={suggestTitle}
disabled={suggestingTitle || !topic.trim()}
title={topic.trim() ? 'Titel aus Briefing + Inhalt vorschlagen' : 'Erst Thema ausfüllen'}
>
{suggestingTitle ? '…' : '✨'}
</button>
</div>
</label>
<label class="kind-select">
<span>Textart</span>
@ -258,6 +329,34 @@
.field-label {
color: var(--color-text-muted, rgba(0, 0, 0, 0.55));
}
.title-row {
display: flex;
gap: 0.4rem;
align-items: stretch;
}
.title-row input {
flex: 1;
min-width: 0;
}
.suggest-btn {
flex-shrink: 0;
padding: 0 0.7rem;
border-radius: 0.5rem;
border: 1px solid var(--color-border, rgba(0, 0, 0, 0.1));
background: transparent;
cursor: pointer;
font: inherit;
font-size: 1rem;
color: inherit;
}
.suggest-btn:hover:not(:disabled) {
border-color: #0ea5e9;
color: #0ea5e9;
}
.suggest-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
small {
font-weight: normal;
opacity: 0.7;

View file

@ -285,3 +285,78 @@ export function buildTranslatePrompt(ctx: SelectionContext, params: TranslatePar
].join('\n'),
};
}
// ─── Title suggestion (Auto-Title) ───────────────────────
export interface TitleSuggestionInput {
kind: DraftKind;
briefing: DraftBriefing;
/** Optional excerpt of the current draft body (already trimmed). */
excerpt?: string;
}
/**
* Build a system+user pair that asks the LLM for a single 48-word
* title. We keep the system prompt strict: just the bare title, no
* quotes / periods / prefixes so the result drops cleanly into the
* title input without post-processing on the client.
*/
export function buildTitleSuggestionPrompt(input: TitleSuggestionInput): PromptPair {
const { kind, briefing, excerpt } = input;
const lang = languageLabel(briefing.language);
const kindLbl = kindLabel(kind);
const system = [
`Du schlägst einen pointierten Titel auf ${lang} für einen ${kindLbl} vor.`,
'Gib ausschließlich den Titel zurück: 4 bis 8 Wörter, keine Anführungszeichen, kein Schlusspunkt, keine Aufzählung, kein "Titel:"-Präfix. Kein Markdown.',
].join('\n\n');
const userLines: string[] = [];
userLines.push(`Thema: ${briefing.topic}`);
if (briefing.audience) userLines.push(`Zielgruppe: ${briefing.audience}`);
if (briefing.tone) userLines.push(`Ton: ${briefing.tone}`);
if (briefing.extraInstructions) {
userLines.push(`Hinweise: ${briefing.extraInstructions}`);
}
if (excerpt) {
userLines.push('');
userLines.push('Aktueller Textauszug:');
userLines.push('---');
userLines.push(excerpt);
userLines.push('---');
}
userLines.push('');
userLines.push('Schlage genau einen Titel vor.');
return { system, user: userLines.join('\n') };
}
/**
* Strip common LLM-output artefacts (wrapping quotes, trailing period,
* trailing newline) from a single suggested title. Keeps the result
* usable as a one-shot drop-in.
*/
export function cleanSuggestedTitle(raw: string): string {
let out = raw.trim();
// Strip wrapping quotes — straight or curly, single or double.
const QUOTE_PAIRS: Array<[string, string]> = [
['"', '"'],
["'", "'"],
['„', '“'],
['«', '»'],
['', ''],
];
for (const [open, close] of QUOTE_PAIRS) {
if (out.startsWith(open) && out.endsWith(close) && out.length >= open.length + close.length) {
out = out.slice(open.length, out.length - close.length).trim();
break;
}
}
// Drop a "Titel:" / "Title:" prefix if the model adds one despite the
// instruction.
out = out.replace(/^(?:Titel|Title)\s*:\s*/i, '').trim();
// Strip terminal full stop only — keep "?" / "!" because they may be
// intentional for blog/social titles.
if (out.endsWith('.') && !out.endsWith('..')) out = out.slice(0, -1).trim();
return out;
}