feat(odin): left sidebar + lazy conversation creation (claude.ai-style)

- Replace top tabs with a left sidebar (New chat + scrollable conversation
  list, per-row rename/delete menu, active highlight), chat on the right.
- Fix duplicate-empty-conversations bug: "Nová konverzace" now just opens an
  empty composer; a DB row is created only on the first successful message
  (and a failed AI call no longer leaves an orphan conversation). Repeated
  clicks never spawn empties, and nothing empty survives a refresh.
- Land on a fresh new chat on mount; deleting the open conversation returns
  to new chat.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
BOHA
2026-06-08 20:07:07 +02:00
parent f18e2e0f2c
commit 769767c33d
3 changed files with 334 additions and 280 deletions

View File

@@ -17,7 +17,7 @@ import type {
EditableField,
StagedFile,
} from "./types";
import OdinTabs from "./OdinTabs";
import OdinSidebar from "./OdinSidebar";
import OdinThread from "./OdinThread";
import InvoiceReviewCard from "./InvoiceReviewCard";
import OdinComposer from "./OdinComposer";
@@ -87,13 +87,10 @@ export default function OdinChat() {
const threadRef = useRef<HTMLDivElement>(null);
const seededId = useRef<number | null>(null);
// Select the first existing conversation once the list loads (lazy-create:
// a brand-new user has none until they send the first message or press "+").
useEffect(() => {
if (!convPending && activeId == null && conversations.length > 0) {
setActiveId(conversations[0].id);
}
}, [convPending, conversations, activeId]);
// No auto-select: like claude.ai, we land on a fresh "new chat" (activeId
// null) and the sidebar lists existing conversations to open. A conversation
// row in the DB is created lazily on the first message (see submit), so
// pressing "Nová konverzace" repeatedly never spawns empty conversations.
// Seed the thread from the active conversation's messages, once per id.
useEffect(() => {
@@ -185,13 +182,6 @@ export default function OdinChat() {
if (!text && files.length === 0) return;
setBusy(true);
const convId = await ensureActive();
if (convId == null) {
setBusy(false);
alert.error("Nepodařilo se vytvořit konverzaci");
return;
}
seededId.current = convId;
const prevTurns = turns;
const userContent = [
@@ -247,10 +237,13 @@ export default function OdinChat() {
setTurns((t) => [...t, { role: "assistant", content: note }]);
setInput("");
setAttachments([]);
persist(convId, [
{ role: "user", content: userContent },
{ role: "assistant", content: note },
]);
// Create the conversation now (first successful message) and persist.
const convId = await ensureActive();
if (convId != null)
persist(convId, [
{ role: "user", content: userContent },
{ role: "assistant", content: note },
]);
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
} else {
let ctx = optimistic.slice(-MODEL_CONTEXT);
@@ -265,10 +258,13 @@ export default function OdinChat() {
const reply: string = body.data.reply;
setTurns((t) => [...t, { role: "assistant", content: reply }]);
setInput("");
persist(convId, [
{ role: "user", content: userContent },
{ role: "assistant", content: reply },
]);
// Create the conversation now (first successful message) and persist.
const convId = await ensureActive();
if (convId != null)
persist(convId, [
{ role: "user", content: userContent },
{ role: "assistant", content: reply },
]);
qc.invalidateQueries({ queryKey: ["ai", "usage"] });
}
} catch (e) {
@@ -317,24 +313,16 @@ export default function OdinChat() {
}
};
const onNew = async () => {
// "Nová konverzace" just opens a fresh, empty composer — no DB row is created
// until the first message, so repeated clicks never spawn empty conversations.
const onNew = () => {
if (busy) return;
const res = await apiFetch("/api/admin/ai/conversations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const b = await res.json();
if (res.ok && b?.data?.conversation) {
const id = b.data.conversation.id as number;
seededId.current = id;
setActiveId(id);
setTurns([]);
setReview([]);
qc.invalidateQueries({ queryKey: ["ai", "conversations"] });
} else {
alert.error("Nepodařilo se vytvořit konverzaci");
}
setActiveId(null);
setTurns([]);
setReview([]);
setInput("");
setAttachments([]);
seededId.current = null;
};
const onRename = async (id: number, title: string) => {
@@ -356,8 +344,8 @@ export default function OdinChat() {
return;
}
if (id === activeId) {
const next = conversations.find((c) => c.id !== id)?.id ?? null;
setActiveId(next);
// Deleting the open conversation returns to a fresh new chat.
setActiveId(null);
setTurns([]);
setReview([]);
seededId.current = null;
@@ -370,55 +358,22 @@ export default function OdinChat() {
r.map((inv) => (inv.uid === uid ? { ...inv, [field]: value } : inv)),
);
const activeTitle =
conversations.find((c) => c.id === activeId)?.title ?? "Nová konverzace";
return (
<Box
sx={{
height: "calc(100dvh - 100px)",
display: "flex",
flexDirection: "column",
gap: 1.5,
border: 1,
borderColor: "divider",
borderRadius: 3,
bgcolor: "background.paper",
p: 2,
overflow: "hidden",
}}
>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
<Box
sx={{
px: 0.75,
py: 0.25,
borderRadius: 1,
fontSize: 11,
fontWeight: 700,
letterSpacing: 0.5,
color: "common.white",
bgcolor: "primary.main",
}}
>
AI
</Box>
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
Odin
</Typography>
</Box>
{usage && (
<Typography variant="caption" color="text.secondary">
Utraceno: ${usage.month_spend_usd.toFixed(2)} / $
{usage.budget_usd.toFixed(2)}
</Typography>
)}
</Box>
<OdinTabs
<OdinSidebar
conversations={conversations}
activeId={activeId}
busy={busy}
@@ -428,50 +383,89 @@ export default function OdinChat() {
onDelete={onDelete}
/>
<OdinThread
turns={turns}
busy={busy}
loading={messagesLoading}
threadRef={threadRef}
/>
{review.length > 0 && (
{/* Chat column */}
<Box
sx={{
flex: 1,
minWidth: 0,
display: "flex",
flexDirection: "column",
gap: 1.5,
p: 2,
}}
>
<Box
sx={{
maxHeight: "35vh",
overflowY: "auto",
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center",
gap: 1,
}}
>
{review.map((inv) => (
<InvoiceReviewCard
key={inv.uid}
inv={inv}
busy={busy}
canSave={canSave}
onChange={patch}
onSave={saveInvoice}
onDiscard={(uid) =>
setReview((r) => r.filter((x) => x.uid !== uid))
}
/>
))}
<Typography
variant="subtitle1"
noWrap
sx={{ fontWeight: 600, minWidth: 0 }}
>
{activeTitle}
</Typography>
{usage && (
<Typography
variant="caption"
color="text.secondary"
sx={{ flexShrink: 0 }}
>
Utraceno: ${usage.month_spend_usd.toFixed(2)} / $
{usage.budget_usd.toFixed(2)}
</Typography>
)}
</Box>
)}
<OdinComposer
input={input}
attachments={attachments}
busy={busy}
canSubmit={canSubmit}
fileRef={fileRef}
onInput={setInput}
onFiles={onFiles}
onRemoveAttachment={removeAttachment}
onSubmit={submit}
/>
<OdinThread
turns={turns}
busy={busy}
loading={messagesLoading}
threadRef={threadRef}
/>
{review.length > 0 && (
<Box
sx={{
maxHeight: "35vh",
overflowY: "auto",
display: "flex",
flexDirection: "column",
gap: 1,
}}
>
{review.map((inv) => (
<InvoiceReviewCard
key={inv.uid}
inv={inv}
busy={busy}
canSave={canSave}
onChange={patch}
onSave={saveInvoice}
onDiscard={(uid) =>
setReview((r) => r.filter((x) => x.uid !== uid))
}
/>
))}
</Box>
)}
<OdinComposer
input={input}
attachments={attachments}
busy={busy}
canSubmit={canSubmit}
fileRef={fileRef}
onInput={setInput}
onFiles={onFiles}
onRemoveAttachment={removeAttachment}
onSubmit={submit}
/>
</Box>
</Box>
);
}

View File

@@ -0,0 +1,224 @@
import { useState } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import IconButton from "@mui/material/IconButton";
import { Button, TextField, Modal, ConfirmDialog } from "../../ui";
interface OdinSidebarProps {
conversations: { id: number; title: string }[];
activeId: number | null;
busy: boolean;
onSelect: (id: number) => void;
onNew: () => void;
onRename: (id: number, title: string) => void;
onDelete: (id: number) => void;
}
export default function OdinSidebar({
conversations,
activeId,
busy,
onSelect,
onNew,
onRename,
onDelete,
}: OdinSidebarProps) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const [menuConv, setMenuConv] = useState<{
id: number;
title: string;
} | null>(null);
const [renameOpen, setRenameOpen] = useState(false);
const [renameDraft, setRenameDraft] = useState("");
const [deleteOpen, setDeleteOpen] = useState(false);
const openMenu = (
e: React.MouseEvent<HTMLElement>,
conv: { id: number; title: string },
) => {
e.stopPropagation();
setMenuConv(conv);
setAnchorEl(e.currentTarget);
};
const closeMenu = () => setAnchorEl(null);
const handleRenameOpen = () => {
closeMenu();
setRenameDraft(menuConv?.title ?? "");
setRenameOpen(true);
};
const handleRenameSubmit = () => {
if (menuConv) onRename(menuConv.id, renameDraft.trim() || menuConv.title);
setRenameOpen(false);
};
const handleDeleteOpen = () => {
closeMenu();
setDeleteOpen(true);
};
const handleDeleteConfirm = () => {
if (menuConv) onDelete(menuConv.id);
setDeleteOpen(false);
};
return (
<Box
sx={{
width: { xs: 184, sm: 232, md: 264 },
flexShrink: 0,
height: "100%",
display: "flex",
flexDirection: "column",
borderRight: 1,
borderColor: "divider",
bgcolor: "action.hover",
}}
>
{/* Brand + New chat */}
<Box sx={{ p: 1.5, display: "flex", flexDirection: "column", gap: 1 }}>
<Box sx={{ display: "flex", alignItems: "center", gap: 1, px: 0.5 }}>
<Box
sx={{
px: 0.75,
py: 0.25,
borderRadius: 1,
fontSize: 11,
fontWeight: 700,
letterSpacing: 0.5,
color: "common.white",
bgcolor: "primary.main",
}}
>
AI
</Box>
<Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
Odin
</Typography>
</Box>
<Button fullWidth disabled={busy} onClick={onNew}>
+ Nová konverzace
</Button>
</Box>
{/* Conversation list */}
<Box
sx={{
flex: 1,
minHeight: 0,
overflowY: "auto",
px: 1,
pb: 1,
display: "flex",
flexDirection: "column",
gap: 0.25,
}}
>
{conversations.length === 0 && (
<Typography
variant="caption"
color="text.secondary"
sx={{ px: 1, py: 1 }}
>
Zatím žádné konverzace.
</Typography>
)}
{conversations.map((conv) => {
const isActive = conv.id === activeId;
return (
<Box
key={conv.id}
onClick={() => !busy && onSelect(conv.id)}
sx={{
display: "flex",
alignItems: "center",
gap: 0.5,
px: 1,
py: 0.75,
borderRadius: 1.5,
cursor: busy ? "default" : "pointer",
bgcolor: isActive ? "action.selected" : "transparent",
"&:hover": {
bgcolor: isActive ? "action.selected" : "action.hover",
},
"&:hover .odin-conv-menu": { opacity: 1 },
}}
>
<Typography
variant="body2"
noWrap
title={conv.title}
sx={{
flex: 1,
minWidth: 0,
color: "text.primary",
fontWeight: isActive ? 600 : 400,
}}
>
{conv.title}
</Typography>
<IconButton
className="odin-conv-menu"
size="small"
disabled={busy}
onClick={(e) => openMenu(e, conv)}
aria-label="Možnosti konverzace"
title="Možnosti konverzace"
sx={{
flexShrink: 0,
opacity: { xs: 1, md: 0 },
transition: "opacity 0.15s",
}}
>
</IconButton>
</Box>
);
})}
</Box>
{/* Per-conversation menu */}
<Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={closeMenu}>
<MenuItem onClick={handleRenameOpen}>Přejmenovat</MenuItem>
<MenuItem onClick={handleDeleteOpen}>Smazat</MenuItem>
</Menu>
{/* Rename modal */}
<Modal
isOpen={renameOpen}
onClose={() => setRenameOpen(false)}
onSubmit={handleRenameSubmit}
title="Přejmenovat konverzaci"
submitText="Přejmenovat"
maxWidth="xs"
>
<Box sx={{ pt: 1 }}>
<TextField
label="Název"
fullWidth
value={renameDraft}
onChange={(e) => setRenameDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleRenameSubmit();
}
}}
autoFocus
/>
</Box>
</Modal>
{/* Delete confirm */}
<ConfirmDialog
isOpen={deleteOpen}
onClose={() => setDeleteOpen(false)}
onConfirm={handleDeleteConfirm}
title="Smazat konverzaci"
message={`Opravdu chcete smazat konverzaci „${menuConv?.title ?? ""}"? Tuto akci nelze vrátit.`}
confirmText="Smazat"
confirmVariant="danger"
/>
</Box>
);
}

View File

@@ -1,164 +0,0 @@
import { useState } from "react";
import Box from "@mui/material/Box";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import IconButton from "@mui/material/IconButton";
import { Button, TextField, Modal, ConfirmDialog } from "../../ui";
interface OdinTabsProps {
conversations: { id: number; title: string }[];
activeId: number | null;
busy: boolean;
onSelect: (id: number) => void;
onNew: () => void;
onRename: (id: number, title: string) => void;
onDelete: (id: number) => void;
}
export default function OdinTabs({
conversations,
activeId,
busy,
onSelect,
onNew,
onRename,
onDelete,
}: OdinTabsProps) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const [renameOpen, setRenameOpen] = useState(false);
const [renameDraft, setRenameDraft] = useState("");
const [deleteOpen, setDeleteOpen] = useState(false);
const activeConv = conversations.find((c) => c.id === activeId) ?? null;
const openMenu = (e: React.MouseEvent<HTMLElement>) => {
e.stopPropagation();
setAnchorEl(e.currentTarget);
};
const closeMenu = () => setAnchorEl(null);
const handleRenameOpen = () => {
closeMenu();
setRenameDraft(activeConv?.title ?? "");
setRenameOpen(true);
};
const handleRenameSubmit = () => {
if (activeId !== null) {
onRename(activeId, renameDraft.trim() || (activeConv?.title ?? ""));
}
setRenameOpen(false);
};
const handleDeleteOpen = () => {
closeMenu();
setDeleteOpen(true);
};
const handleDeleteConfirm = () => {
if (activeId !== null) {
onDelete(activeId);
}
setDeleteOpen(false);
};
return (
<>
<Box
sx={{
display: "flex",
gap: 0.5,
overflowX: "auto",
pb: 0.5,
alignItems: "center",
}}
>
{conversations.map((conv) => {
const isActive = conv.id === activeId;
return (
<Box
key={conv.id}
sx={{ display: "flex", alignItems: "center", flexShrink: 0 }}
>
<Button
size="small"
variant={isActive ? "contained" : "outlined"}
color={isActive ? "primary" : "inherit"}
disabled={busy}
onClick={() => onSelect(conv.id)}
>
{conv.title}
</Button>
{isActive && (
<IconButton
size="small"
disabled={busy}
onClick={openMenu}
aria-label="Možnosti konverzace"
title="Možnosti konverzace"
sx={{ ml: 0.25 }}
>
</IconButton>
)}
</Box>
);
})}
<Button
size="small"
variant="outlined"
color="inherit"
disabled={busy}
onClick={onNew}
sx={{ flexShrink: 0 }}
>
+
</Button>
</Box>
{/* Overflow menu */}
<Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={closeMenu}>
<MenuItem onClick={handleRenameOpen}>Přejmenovat</MenuItem>
<MenuItem onClick={handleDeleteOpen}>Smazat</MenuItem>
</Menu>
{/* Rename modal */}
<Modal
isOpen={renameOpen}
onClose={() => setRenameOpen(false)}
onSubmit={handleRenameSubmit}
title="Přejmenovat konverzaci"
submitText="Přejmenovat"
maxWidth="xs"
>
<Box sx={{ pt: 1 }}>
<TextField
label="Název"
fullWidth
value={renameDraft}
onChange={(e) => setRenameDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleRenameSubmit();
}
}}
autoFocus
/>
</Box>
</Modal>
{/* Delete confirm */}
<ConfirmDialog
isOpen={deleteOpen}
onClose={() => setDeleteOpen(false)}
onConfirm={handleDeleteConfirm}
title="Smazat konverzaci"
message={`Opravdu chcete smazat konverzaci „${activeConv?.title ?? ""}"? Tuto akci nelze vrátit.`}
confirmText="Smazat"
confirmVariant="danger"
/>
</>
);
}