diff --git a/README.md b/README.md index 8b4fd44..1c3f1eb 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ bun run build Open [http://localhost:5173](http://localhost:5173) in your browser. -> **Proxy Note**: Vite server and the production Bun server proxy `/api/*` and WebSocket connections to `BACKEND_ORIGIN` (default: `http://127.0.0.1:7656`, the co-located backend's loopback port), preserving HttpOnly session cookies across same-origin calls. Point it elsewhere with `BACKEND_ORIGIN=… bun run dev`, or with `BACKEND_ORIGIN` in `hezarfen_frontend.env` for the compose stack (see "Run in a container" below). +> **Proxy Note**: Vite proxies `/api/*` and WebSocket connections to `BACKEND_ORIGIN`, preserving HttpOnly session cookies across same-origin calls. Local development defaults to `https://hezarfen-backend.dizey.sh`, so `bun run dev` works without a backend process on the laptop; use `BACKEND_ORIGIN=http://127.0.0.1:7656 bun run dev` to target one locally. The production Bun server gets its co-located loopback default from the image and can be overridden through `hezarfen_frontend.env` (see "Run in a container" below). --- @@ -106,6 +106,7 @@ It needs three repository secrets — `SSH_PRIVATE_KEY`, `SSH_HOST`, `SSH_USER`, | `/guide` | Authenticated | Redesigned product guide featuring role scope matrix, 6 core feature cards, and pro tips. | | `/profile` | Authenticated | User profile management (display name, email, phone, birth date). | | `/notes` | Student+ | Personal notebook with paper-style cards, Note Import Assistant (PDF/TXT), reader drawer, file attachments, and `.hzdraw` live canvas. | +| `/ai` | Authenticated | AI hub: the note studio (course-note AI outputs plus narrated podcast audio with live job progress, cancellation and playback), the ZEKA analysis board, and the Çelebi entry point. `/sound-studio` redirects to its note-studio tab. | | `/questions`, `/questions/:id` | Student+ | Community Question Bank with solution authoring and teacher verification. | | `/courses`, `/courses/:id` | Student+ | Course catalog, student enrollment, curriculum subjects, homework assignments, and lesson session roll call. | | `/exams`, `/exams/:id` | Student+ | Exam list and details, subject-tagged questions, draft/publish controls, and grading statistics. | diff --git a/docs/ui/figma-migration-coverage.md b/docs/ui/figma-migration-coverage.md index 4c4d7df..67831d9 100644 --- a/docs/ui/figma-migration-coverage.md +++ b/docs/ui/figma-migration-coverage.md @@ -140,7 +140,9 @@ false actions: - AI recommendation approval queue, evidence history, and rule management. - AI question generation and institution-level competency analytics. -- Ses Atölyesi audio generation, player, quality gate, and listening analytics. +- Ses Atölyesi quality gate and listening analytics. Course-note audio generation, + job progress/cancellation, and the player are implemented on the `/ai` hub's + note-studio tab (the old `/sound-studio` route redirects there). - Student/parent teacher-approved study plans and mastery time series. - Institution selection and multi-institution session context. - Password reset, remember-me session policy, and SSO. diff --git a/src/components/ai/celebi-launcher.tsx b/src/components/ai/celebi-launcher.tsx new file mode 100644 index 0000000..e5a0990 --- /dev/null +++ b/src/components/ai/celebi-launcher.tsx @@ -0,0 +1,38 @@ +import { For } from "solid-js"; +import { Button } from "@/components/ui/button"; +import { IconSparkles } from "@/components/ui/icons"; +import { openCelebiPanel } from "@/stores/celebi-panel"; +import { useT } from "@/stores/preferences-context"; + +// Çelebi itself is a shell panel — it follows the viewer across every route, +// so the hub tab opens that one panel instead of mounting a second chat. +export function CelebiLauncher() { + const t = useT(); + const examples = () => [t("aiHub.celebiExample1"), t("aiHub.celebiExample2"), t("aiHub.celebiExample3")]; + + return ( +
+
+ +
+
+

{t("ai.title")}

+

{t("ai.empty")}

+
+ + +

{t("aiHub.celebiHint")}

+
+ ); +} diff --git a/src/components/ai/insights-board.tsx b/src/components/ai/insights-board.tsx new file mode 100644 index 0000000..1014a11 --- /dev/null +++ b/src/components/ai/insights-board.tsx @@ -0,0 +1,291 @@ +import { Show, Suspense, createMemo, createSignal } from "solid-js"; +import { createResource } from "@/lib/create-resource"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { + getInsightByUserId, + getInsightRuns, + getMyInsight, + postInsightComputeByUserId, + postInsightsRefresh, +} from "@/api/insights"; +import { getMyStudents } from "@/api/parents"; +import { getUserSearch } from "@/api/users"; +import { formatApiError, type PersonRef, type Role } from "@/api/client"; +import { InsightDetail } from "@/components/insights/insight-detail"; +import { InsightRunsTable } from "@/components/insights/insight-runs-table"; +import { RosterPersonCell } from "@/components/users/roster-person-cell"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconEye, IconRefresh, IconSparkles } from "@/components/ui/icons"; +import { SidePanel } from "@/components/ui/side-panel"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { createFlash } from "@/lib/flash"; +import { matchesSearch } from "@/lib/search-text"; +import { personLabel } from "@/lib/person"; +import { hasMinRole } from "@/lib/roles"; +import { useAuth } from "@/stores/auth-context"; +import { usePreferences } from "@/stores/preferences-context"; + +const PAGE_SIZE = 10; + +/** Every insight surface in one board: the viewer's own analysis, the student + * list they may browse, and the school-wide run log for managers. */ +export function InsightsBoard() { + const auth = useAuth(); + const prefs = usePreferences(); + const tx = (key: string, vars?: Record) => prefs.t(key as never, vars); + const role = () => auth.user()?.role; + const canBrowseStudents = () => role() === "parent" || hasMinRole(role(), "teacher"); + const canManageRuns = () => hasMinRole(role(), "manager"); + const [selectedStudent, setSelectedStudent] = createSignal(null); + const [pageError, setPageError] = createSignal(""); + const [panelError, setPanelError] = createSignal(""); + const [refreshingAll, setRefreshingAll] = createSignal(false); + const [computingStudent, setComputingStudent] = createSignal(false); + const [, flash] = createFlash(); + + const [selfInsight, { refetch: refetchSelfInsight }] = createResource( + () => auth.user()?.id ?? null, + async () => getMyInsight(), + ); + const [students, { refetch: refetchStudents }] = createResource( + () => (canBrowseStudents() ? role() : null), + async (viewerRole: Role) => + viewerRole === "parent" + ? (await getMyStudents({ limit: 200 })).items + : (await getUserSearch("", undefined, "student", { limit: 200 })).items, + ); + const [runs, { refetch: refetchRuns }] = createResource( + () => (canManageRuns() ? true : null), + async () => getInsightRuns({ limit: 100 }), + ); + const [insight, { mutate: mutateInsight, refetch: refetchInsight }] = createResource( + () => selectedStudent()?.id ?? null, + async (userId) => { + if (!userId) return null; + setPanelError(""); + try { + return await getInsightByUserId(userId); + } catch (error) { + setPanelError(formatApiError(error)); + return null; + } + }, + ); + + const refreshPage = async () => { + setPageError(""); + try { + const tasks: Promise[] = [Promise.resolve(refetchSelfInsight())]; + if (canBrowseStudents()) tasks.push(Promise.resolve(refetchStudents())); + if (canManageRuns()) tasks.push(Promise.resolve(refetchRuns())); + await Promise.all(tasks); + } catch (error) { + setPageError(formatApiError(error)); + } + }; + + const queueSchoolRefresh = async () => { + if (refreshingAll() || !canManageRuns()) return; + setRefreshingAll(true); + setPageError(""); + try { + await postInsightsRefresh(); + flash(tx("insights.refreshQueued")); + await refetchRuns(); + } catch (error) { + setPageError(formatApiError(error)); + } finally { + setRefreshingAll(false); + } + }; + + const queueStudentCompute = async () => { + const student = selectedStudent(); + if (!student || computingStudent()) return; + setComputingStudent(true); + setPanelError(""); + try { + await postInsightComputeByUserId(student.id); + flash(tx("insights.recomputeQueued", { student: personLabel(student) })); + } catch (error) { + setPanelError(formatApiError(error)); + } finally { + setComputingStudent(false); + } + }; + + const openStudent = (student: PersonRef) => { + setPanelError(""); + mutateInsight(null); + setSelectedStudent(student); + }; + + const columns = createMemo[]>(() => [ + { + id: "student", + header: tx("insights.student"), + cell: (cell) => , + }, + { + id: "actions", + header: tx("common.actions"), + meta: { + headerClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap", + cellClass: "w-[110px] min-w-[110px] max-w-[110px] h-[45px] text-center whitespace-nowrap", + }, + cell: (cell) => ( + , + onSelect: () => openStudent(cell.row.original), + }, + ]} + /> + ), + }, + ]); + + return ( +
+ + {pageError()} + + + +
+
+
+

{tx("insights.myAnalysis")}

+

{tx("insights.myAnalysisSubtitle")}

+
+ +
+ {tx("common.loading")}

}> + + void refetchSelfInsight()} /> + + + {(value) => } + +
+
+
+ +

{tx("common.loading")}

}> + + {(value) => ( +
+
+

{tx("insights.myRecommendations")}

+

{tx("insights.myRecommendationsSubtitle")}

+
+ +
+ )} +
+
+ + +
+ }> + + void refetchStudents()} /> + + + + + + + + + } + columns={columns()} + data={students() ?? []} + empty={role() === "parent" ? tx("insights.emptyLinkedStudents") : tx("insights.emptyStudents")} + emptyIllustration="people" + filterPlaceholder={tx("insights.searchStudents")} + filterHint={tx("search.hint.people")} + searchPredicate={(student, query) => matchesSearch(query, student.display_name, student.username)} + enablePagination + pageSize={PAGE_SIZE} + storageKey="insight-students" + onRowClick={openStudent} + /> + + +
+
+ + +
+ }> + + void refetchRuns()} /> + + + + + +
+
+ + { + if (!open) { + setSelectedStudent(null); + mutateInsight(null); + setPanelError(""); + } + }} + title={personLabel(selectedStudent())} + description={tx("insights.studentAnalysis")} + > +
+
+ + +
+ + void refetchInsight()} /> + + +

{tx("common.loading")}

+
+ {(value) => } +
+
+
+ ); +} diff --git a/src/components/ai/note-studio-panel.tsx b/src/components/ai/note-studio-panel.tsx new file mode 100644 index 0000000..0e11615 --- /dev/null +++ b/src/components/ai/note-studio-panel.tsx @@ -0,0 +1,109 @@ +import { Show, Suspense, createMemo, createSignal } from "solid-js"; +import { createResource } from "@/lib/create-resource"; +import { getCourseNotes } from "@/api/course-notes"; +import { getCourses } from "@/api/courses"; +import { getMyCourses } from "@/api/reports"; +import { formatApiError, type CourseNote } from "@/api/client"; +import { PodcastPanel } from "@/components/notes/podcast-panel"; +import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; +import { EmptyState } from "@/components/ui/empty-state"; +import { ErrorAlert } from "@/components/ui/error-alert"; +import { IconWaveform } from "@/components/ui/icons"; +import { Label } from "@/components/ui/label"; +import { PageSpinner } from "@/components/ui/page-spinner"; +import { SearchableSelect } from "@/components/ui/searchable-select"; +import { useAuth } from "@/stores/auth-context"; +import { useT } from "@/stores/preferences-context"; +import { courseNoteFiles } from "@/lib/note-source"; +import { hasMinRole } from "@/lib/roles"; + +type StudioNote = CourseNote & { courseTitle: string; courseCreatorId: string }; + +/** Pick a lesson note, then read its AI outputs and produce its podcast — + * the same two panels the note reader shows, gathered on the AI hub. */ +export function NoteStudioPanel() { + const t = useT(); + const auth = useAuth(); + const [selectedId, setSelectedId] = createSignal(""); + const [notes, { refetch }] = createResource( + () => auth.user()?.role ?? null, + async (role) => { + const courses = role === "student" ? await getMyCourses({ limit: 100 }) : await getCourses({ limit: 100 }); + const rows = await Promise.all( + courses.items.map(async (course) => { + try { + const page = await getCourseNotes(course.id, { limit: 100 }); + return page.items.map((note) => ({ + ...note, + courseTitle: course.title, + courseCreatorId: course.creator.id, + })); + } catch { + return []; + } + }), + ); + return rows.flat(); + }, + ); + const options = createMemo(() => (notes() ?? []).map((note) => ({ value: note.id, label: `${note.courseTitle} · ${note.title}` }))); + const selected = createMemo(() => (notes() ?? []).find((note) => note.id === selectedId()) ?? null); + const canManageSelected = () => { + const note = selected(); + const user = auth.user(); + return !!note && !!user && (hasMinRole(user.role, "manager") || note.courseCreatorId === user.id); + }; + + return ( + }> + + void refetch()} /> + + + 0} + fallback={} + > +
+
+ + +
+ +
+ +
+
+

{t("podcast.selectPrompt")}

+

{t("podcast.selectPromptHint")}

+
+ + } + > + {(note) => ( +
+ + +
+ )} +
+
+
+
+
+ ); +} diff --git a/src/components/insights/insight-data-list.tsx b/src/components/insights/insight-data-list.tsx new file mode 100644 index 0000000..6535f15 --- /dev/null +++ b/src/components/insights/insight-data-list.tsx @@ -0,0 +1,57 @@ +import { For, Show } from "solid-js"; + +type DataEntry = { path: string; value: string }; + +function humanize(value: string): string { + return value + .replace(/[_-]+/g, " ") + .replace(/\b\w/g, (letter) => letter.toLocaleUpperCase("tr-TR")); +} + +function scalar(value: unknown): string | null { + if (value == null) return "—"; + if (typeof value === "boolean") return String(value); + if (typeof value === "string" || typeof value === "number") return String(value); + return null; +} + +function flatten(value: unknown, path = "", depth = 0): DataEntry[] { + const direct = scalar(value); + if (direct != null) return [{ path: path || "Değer", value: direct }]; + if (depth >= 3) return [{ path: path || "Değer", value: JSON.stringify(value) }]; + + if (Array.isArray(value)) { + if (value.length === 0) return []; + return value.flatMap((item, index) => flatten(item, `${path}${path ? " " : ""}${index + 1}`, depth + 1)); + } + + if (typeof value === "object") { + return Object.entries(value as Record).flatMap(([key, item]) => + flatten(item, path ? `${path} · ${humanize(key)}` : humanize(key), depth + 1), + ); + } + + return []; +} + +export function InsightDataList(props: { value: unknown; emptyLabel: string }) { + const entries = () => flatten(props.value); + + return ( + 0} + fallback={

{props.emptyLabel}

} + > +
+ + {(entry) => ( +
+
{entry.path}
+
{entry.value}
+
+ )} +
+
+
+ ); +} diff --git a/src/components/insights/insight-detail.tsx b/src/components/insights/insight-detail.tsx new file mode 100644 index 0000000..b17fb94 --- /dev/null +++ b/src/components/insights/insight-detail.tsx @@ -0,0 +1,228 @@ +import { For, Show } from "solid-js"; +import type { InsightConfidence, StudentInsight } from "@/api/client"; +import { InsightDataList } from "@/components/insights/insight-data-list"; +import { Badge } from "@/components/ui/badge"; +import { EmptyInline } from "@/components/ui/empty-inline"; +import { IconAlert, IconChart, IconSparkles } from "@/components/ui/icons"; +import { cn } from "@/lib/cn"; +import { formatDateTime } from "@/lib/format"; +import { usePreferences } from "@/stores/preferences-context"; + +const percent = (value: number) => `${Math.round(value * 100)}%`; +const clampPercent = (value: number) => Math.min(100, Math.max(0, value * 100)); + +function confidenceVariant(confidence: InsightConfidence) { + if (confidence === "stable") return "success" as const; + if (confidence === "exploratory") return "warning" as const; + return "secondary" as const; +} + +export function InsightDetail(props: { insight: StudentInsight; mode?: "full" | "cards" }) { + const prefs = usePreferences(); + const tx = (key: string, vars?: Record) => prefs.t(key as never, vars); + const confidenceLabel = (confidence: InsightConfidence) => + confidence === "none" || confidence === "exploratory" || confidence === "stable" + ? tx(`insights.confidence.${confidence}`) + : confidence; + const summarySections = () => { + const summary = props.insight.summary; + if (!summary) return []; + return [ + { id: "attendance", label: tx("insights.modules.attendance"), value: summary.attendance }, + { id: "marks", label: tx("insights.modules.marks"), value: summary.marks }, + { id: "study", label: tx("insights.modules.study"), value: summary.study }, + { id: "submission", label: tx("insights.modules.submission"), value: summary.submission }, + ]; + }; + + return ( +
+ +
+
+
+ +

{tx("insights.summary")}

+
+ + {(summary) => ( + + {confidenceLabel(summary().confidence)} + + )} + +
+ + + } + > + {(summary) => ( + <> +
+
+

{tx("insights.computedAt")}

+

{formatDateTime(summary().computed_at, prefs.locale())}

+
+
+

{tx("insights.retainUntil")}

+

{formatDateTime(summary().retain_until, prefs.locale())}

+
+
+
+ + {(section) => ( +
+

{section.label}

+ {tx("insights.sectionNotComputed")}

} + > + +
+
+ )} +
+
+ + )} +
+
+
+ + +
+
+ +

{tx("insights.attention")}

+ {props.insight.attention.length} +
+ 0} + fallback={} + > +
+ + {(item) => ( +
+
+
+

{item.fact}

+

+ {item.course || tx("insights.schoolWide")} · {formatDateTime(item.window_from, prefs.locale())} – {formatDateTime(item.window_to, prefs.locale())} +

+
+ {item.trigger} +
+ +
+ )} +
+
+
+
+
+ +
+
+ +

{tx("insights.recommendations")}

+ {props.insight.cards.length} +
+ 0} + fallback={} + > +
+ + {(card) => ( +
+
+
+ {card.product} + {card.rule_id} · v{card.rule_version} +
+ + {confidenceLabel(card.confidence)} + +
+ +

{[card.course, card.scope].filter(Boolean).join(" · ")}

+
+ +

+ {tx("insights.expiresAt")}: {formatDateTime(card.expires_at, prefs.locale())} +

+
+ )} +
+
+
+
+ + +
+
+ +

{tx("insights.segments")}

+ {props.insight.segments.length} +
+ 0} + fallback={} + > +
+ + {(segment) => ( +
+
+
+

{segment.label}

+

{segment.dimension}

+
+ + {confidenceLabel(segment.confidence)} + +
+
+
+ {tx("insights.accuracy")} + {percent(segment.accuracy)} +
+
+
+
+
+
+
+

{segment.n_correct}/{segment.n_answers}

+

{tx("insights.answers")}

+
+
+

{percent(segment.overall_accuracy)}

+

{tx("insights.overall")}

+
+
+

+ {segment.contrast > 0 ? "+" : ""}{percent(segment.contrast)} +

+

{tx("insights.contrast")}

+
+
+
+ )} +
+
+
+
+
+
+ ); +} diff --git a/src/components/insights/insight-runs-table.tsx b/src/components/insights/insight-runs-table.tsx new file mode 100644 index 0000000..adcf28d --- /dev/null +++ b/src/components/insights/insight-runs-table.tsx @@ -0,0 +1,113 @@ +import { createMemo } from "solid-js"; +import type { ColumnDef } from "@tanstack/solid-table"; +import type { InsightRun } from "@/api/client"; +import { Badge } from "@/components/ui/badge"; +import { DataTable } from "@/components/ui/data-table"; +import { cn } from "@/lib/cn"; +import { formatDateTime, formatDurationMinutes } from "@/lib/format"; +import { usePreferences } from "@/stores/preferences-context"; + +function statusVariant(status: string) { + if (status === "ok") return "success" as const; + if (status === "running") return "info" as const; + if (status === "partial" || status === "skipped") return "warning" as const; + if (status === "failed") return "destructive" as const; + return "secondary" as const; +} + +export function InsightRunsTable(props: { runs: InsightRun[] }) { + const prefs = usePreferences(); + const tx = (key: string, vars?: Record) => prefs.t(key as never, vars); + const statusLabel = (status: string) => + ["running", "ok", "partial", "failed", "skipped"].includes(status) + ? tx(`insights.status.${status}`) + : status; + const columns = createMemo[]>(() => [ + { + accessorKey: "run_day", + header: tx("insights.runDay"), + cell: (cell) => ( +
+

{cell.row.original.run_day}

+

{formatDateTime(cell.row.original.started_at, prefs.locale())}

+
+ ), + }, + { + accessorKey: "status", + header: tx("insights.result"), + cell: (cell) => ( + + {statusLabel(cell.row.original.status)} + + ), + }, + { + id: "processed", + header: tx("insights.processed"), + accessorFn: (row) => row.students_ok, + meta: { align: "right" }, + cell: (cell) => { + const run = cell.row.original; + return ( +
+

{run.students_ok}/{run.students_total}

+

{run.students_failed} / {run.students_skipped}

+
+ ); + }, + }, + { + accessorKey: "rows_written", + header: tx("insights.written"), + meta: { align: "right", cellClass: "mono tabular-nums" }, + }, + { + accessorKey: "duration_ms", + header: tx("insights.duration"), + meta: { align: "right" }, + cell: (cell) => {formatDurationMinutes(cell.row.original.duration_ms, prefs.locale())}, + }, + { + id: "issues", + header: tx("insights.issues"), + enableSorting: false, + cell: (cell) => { + const run = cell.row.original; + const issueCount = run.pending_students.length + run.failed_modules.length; + return ( +
+

0 || run.budget_exceeded ? "text-warning" : "text-muted-foreground")}> + {issueCount > 0 ? tx("insights.issueCount", { count: issueCount }) : tx("insights.noIssues")} +

+ {run.budget_exceeded &&

{tx("insights.budgetExceeded")}

} + {run.pending_students.length > 0 && ( +

+ {tx("insights.pendingStudents", { count: run.pending_students.length })} +

+ )} + {run.failed_modules.length > 0 && ( +

+ {tx("insights.failedModules", { modules: run.failed_modules.join(", ") })} +

+ )} +
+ ); + }, + }, + ]); + + return ( + + ); +} diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx index 9229949..5c56b72 100644 --- a/src/components/layout/app-shell.tsx +++ b/src/components/layout/app-shell.tsx @@ -17,6 +17,7 @@ import { IconChevronLeft, IconSparkles } from "@/components/ui/icons"; import { Toaster } from "@/components/ui/toast"; import { useAuth } from "@/stores/auth-context"; import { useModules } from "@/stores/modules-context"; +import { celebiPanelOpen, openCelebiPanel, setCelebiPanelOpen } from "@/stores/celebi-panel"; import { commandPaletteOpen, openCommandPalette, setCommandPaletteOpen } from "@/stores/command-palette"; import { ShellFeedProvider } from "@/stores/shell-feed-context"; import { usePreferences, useT } from "@/stores/preferences-context"; @@ -33,7 +34,6 @@ export function AppShell(props: ParentProps) { const modules = useModules(); const navigate = useNavigate(); const [mobileOpen, setMobileOpen] = createSignal(false); - const [celebiOpen, setCelebiOpen] = createSignal(false); const [profileOpen, setProfileOpen] = createSignal(false); const collapsed = () => prefs.sidebarCollapsed(); const location = useLocation(); @@ -90,7 +90,7 @@ export function AppShell(props: ParentProps) {
setCelebiOpen(true)} + onOpenCelebi={() => openCelebiPanel()} onOpenProfile={() => setProfileOpen(true)} />
@@ -118,7 +118,7 @@ export function AppShell(props: ParentProps) { open={mobileOpen()} onClose={() => setMobileOpen(false)} onLogout={logout} - onOpenCelebi={() => setCelebiOpen(true)} + onOpenCelebi={() => openCelebiPanel()} onOpenProfile={() => setProfileOpen(true)} /> @@ -154,7 +154,7 @@ export function AppShell(props: ParentProps) { class="topbar-ai-control hidden h-9 shrink-0 items-center justify-center gap-2 rounded-md px-3 text-xs font-semibold outline-hidden focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.98] sm:flex" aria-label={t("ai.askCelebi")} title={t("ai.askCelebi")} - onClick={() => setCelebiOpen(true)} + onClick={() => openCelebiPanel()} > {t("ai.askCelebi")} @@ -187,11 +187,11 @@ export function AppShell(props: ParentProps) { - + setCelebiOpen(true)} + onOpenCelebi={() => openCelebiPanel()} onOpenProfile={() => setProfileOpen(true)} /> diff --git a/src/components/layout/celebi-composer.tsx b/src/components/layout/celebi-composer.tsx index e975ec8..a499b09 100644 --- a/src/components/layout/celebi-composer.tsx +++ b/src/components/layout/celebi-composer.tsx @@ -42,9 +42,13 @@ export function CelebiComposer(props: { // The field itself is transparent over the card, so it names its text and // caret colors: a control that drops its background inherits neither, and // the draft came out unreadable once focused. + // + // The strip also sits on the panel's bottom edge rather than floating above + // a band of background, so its own padding stays small and the panel body + // drops its bottom padding (see the SidePanel's bodyClass in celebi-panel). return (
{ event.preventDefault(); submit(); diff --git a/src/components/layout/celebi-panel.tsx b/src/components/layout/celebi-panel.tsx index f421f49..50ccd07 100644 --- a/src/components/layout/celebi-panel.tsx +++ b/src/components/layout/celebi-panel.tsx @@ -13,6 +13,7 @@ import { EmptyInline } from "@/components/ui/empty-inline"; import { IconAlert, IconBotSquare, IconChevronDown, IconChevronLeft, IconCopy, IconEdit, IconMessage, IconPlus } from "@/components/ui/icons"; import { SidePanel } from "@/components/ui/side-panel"; import { cn } from "@/lib/cn"; +import { matchesSearch } from "@/lib/search-text"; import { usePreferences, useT } from "@/stores/preferences-context"; type PanelMessage = Pick; @@ -129,9 +130,9 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean lastScrollTop = top; }; const filteredMessages = () => { - const query = searchQuery().trim().toLocaleLowerCase(locale()); + const query = searchQuery().trim(); if (!query) return messages(); - return messages().filter((message) => message.content.toLocaleLowerCase(locale()).includes(query)); + return messages().filter((message) => matchesSearch(query, message.content)); }; createEffect(() => { const items = messages(); @@ -279,7 +280,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean }; return ( - +
item.id), })), ).toEqual([ - { id: "school", items: ["students-roster", "teachers-roster", "class-groups", "terms", "schedule"] }, + { id: "school", items: ["students-roster", "teachers-roster", "class-groups", "academic-years", "terms", "schedule"] }, { id: "teaching", items: ["courses", "homework", "exams", "question-bank", "questions", "notes", "whiteboards"] }, { id: "tracking", items: ["student-attendance", "student-marks", "student-pomodoros"] }, { id: "services", items: ["events", "appointments", "school-meals"] }, { id: "institution", items: ["payments-collection", "staff-work", "work", "users", "license-modules", "settings"] }, - { id: "ai", items: ["celebi"] }, - { id: "soon", items: ["mock-exams", "optical-reading", "reports", "data-protection", "hezarfen-zeka", "sound-studio"] }, + { id: "ai", items: ["celebi", "ai-hub"] }, + { id: "soon", items: ["mock-exams", "optical-reading", "reports", "data-protection"] }, ]); }); @@ -65,7 +65,8 @@ test("teacher's sidebar splits into short labelled sections with the soon shelf { id: "tracking", items: ["student-attendance", "student-marks", "student-pomodoros"] }, { id: "teaching", items: ["homework", "exams", "question-bank", "questions", "notes", "whiteboards"] }, { id: "other", items: ["parent-communication", "appointments", "events", "meals", "work", "settings-teacher"] }, - { id: "soon", items: ["student-analysis", "pending-approvals", "question-generation", "sound-studio"] }, + { id: "ai", items: ["celebi", "ai-hub"] }, + { id: "soon", items: ["student-analysis", "pending-approvals", "question-generation"] }, ]); }); @@ -78,9 +79,9 @@ test("student's sidebar splits into short labelled sections with the soon shelf ).toEqual([ { id: "study", items: ["topic-mastery", "exam-results", "my-homework", "pomodoro"] }, { id: "teaching", items: ["courses", "notes", "questions", "whiteboards"] }, - { id: "ai", items: ["celebi"] }, + { id: "ai", items: ["celebi", "ai-hub"] }, { id: "other", items: ["calendar", "events", "messages", "appointments", "meals", "settings-student"] }, - { id: "soon", items: ["study-plan", "sound-studio"] }, + { id: "soon", items: ["study-plan"] }, ]); }); @@ -107,6 +108,8 @@ test("parent's sidebar keeps the Figma Öğrencim / Kurum tree plus every backed ).toEqual([ { id: "my-student", items: ["progress-report", "absence", "child-exam-results", "child-study-plan"] }, { id: "institution", items: ["payment-statement", "appointments", "messages", "calendar", "events", "meals", "settings-parent"] }, + // A parent's only AI surface: their children's analysis on the hub. + { id: "ai", items: ["ai-hub"] }, ]); }); @@ -141,11 +144,25 @@ test("license modules is a real admin page and the work log includes admin", () }); test("entries with no backend yet are flagged soon and route to the shared placeholder", () => { - const hezarfenZeka = visibleNavGroups("admin") + const opticalReading = visibleNavGroups("admin") .flatMap((g) => g.items) - .find((i) => i.id === "hezarfen-zeka"); - expect(hezarfenZeka?.soon).toBe(true); - expect(hezarfenZeka?.to).toBe("/coming-soon/hezarfen-zeka"); + .find((i) => i.id === "optical-reading"); + expect(opticalReading?.soon).toBe(true); + expect(opticalReading?.to).toBe("/coming-soon/optik-okuma"); +}); + +// Every AI feature the backend answers for sits on one hub route; Çelebi keeps +// its own row because it opens the shell panel instead of navigating. +test("the AI group is the hub plus the Çelebi panel, and nothing is a placeholder", () => { + for (const role of ["student", "teacher", "manager", "admin", "parent"] as const) { + const ai = visibleNavGroups(role).find((group) => group.id === "ai"); + expect(ai).toBeDefined(); + const hub = ai?.items.find((item) => item.id === "ai-hub"); + expect(hub?.to).toBe("/ai"); + expect(hub?.soon).toBeFalsy(); + } + expect(routeNavItem("/ai", "student")?.id).toBe("ai-hub"); + expect(routeLabelKey("/ai", "student")).toBe("nav.hezarfenZeka"); }); test("Çelebi and account settings open an existing shell surface instead of navigating", () => { @@ -224,7 +241,11 @@ test("module gate hides nests the school did not buy", () => { expect(teacherPaths).not.toContain("/homework"); expect(teacherPaths).not.toContain("/exams"); expect(teacherPaths).not.toContain("/whiteboards"); - expect(teacherPaths).toContain("/management/classes"); + // Classes is a module too, so an unbought "classes" nest hides it; the + // schedule carries no module and stays. + expect(teacherPaths).not.toContain("/management/classes"); + expect(visibleNavGroups("teacher", ["courses", "classes"]).flatMap((group) => group.items.map((item) => item.to))) + .toContain("/management/classes"); expect(teacherPaths).toContain("/calendar"); }); diff --git a/src/components/layout/nav-items.ts b/src/components/layout/nav-items.ts index 2c5dfc4..d02f936 100644 --- a/src/components/layout/nav-items.ts +++ b/src/components/layout/nav-items.ts @@ -30,7 +30,6 @@ import { IconUserCog, IconUsers, IconUtensils, - IconWaveform, } from "@/components/ui/icons"; import type { MessageKey } from "@/i18n/messages"; import { hasExactRole, roleInRange } from "@/lib/roles"; @@ -78,12 +77,14 @@ const CELEBI_ITEM: NavItem = { action: "celebi", }; -const SOUND_STUDIO_ITEM: NavItem = { - id: "sound-studio", - to: "/coming-soon/ses-atolyesi", - labelKey: "nav.soundStudio", - Icon: IconWaveform, - soon: true, +// The hub gathers the note studio, the insight board and the Çelebi entry — +// what used to be a sound-studio row, an unreachable insights page and a +// "yakında" placeholder. +const AI_HUB_ITEM: NavItem = { + id: "ai-hub", + to: "/ai", + labelKey: "nav.hezarfenZeka", + Icon: IconBotSquare, }; function settingsAction(id: string): NavItem { @@ -165,15 +166,13 @@ const ADMIN_GROUPS: NavGroup[] = [ id: "ai", labelKey: "nav.group.ai", Icon: IconSparkles, - items: [CELEBI_ITEM], + items: [CELEBI_ITEM, AI_HUB_ITEM], }, soonGroup([ { id: "mock-exams", to: "/coming-soon/deneme-sinavlari", labelKey: "nav.mockExams", Icon: IconTarget, soon: true, minRole: "manager" }, { id: "optical-reading", to: "/coming-soon/optik-okuma", labelKey: "nav.opticalReading", Icon: IconScan, soon: true, minRole: "manager" }, { id: "reports", to: "/coming-soon/raporlar", labelKey: "nav.reports", Icon: IconChartPie, soon: true, minRole: "manager" }, { id: "data-protection", to: "/coming-soon/kvkk-denetim", labelKey: "nav.dataProtection", Icon: IconShieldCheck, soon: true, minRole: "admin" }, - { id: "hezarfen-zeka", to: "/coming-soon/hezarfen-zeka", labelKey: "nav.hezarfenZeka", Icon: IconBotSquare, soon: true, minRole: "manager" }, - SOUND_STUDIO_ITEM, ]), ]; @@ -224,11 +223,16 @@ const TEACHER_GROUPS: NavGroup[] = [ settingsAction("settings-teacher"), ], }, + { + id: "ai", + labelKey: "nav.group.ai", + Icon: IconSparkles, + items: [CELEBI_ITEM, AI_HUB_ITEM], + }, soonGroup([ { id: "student-analysis", to: "/coming-soon/ogrenci-analizi", labelKey: "nav.studentAnalysis", Icon: IconChart, soon: true }, { id: "pending-approvals", to: "/coming-soon/bekleyen-onaylar", labelKey: "nav.pendingApprovals", Icon: IconHelpCircle, soon: true }, { id: "question-generation", to: "/coming-soon/soru-uretimi", labelKey: "nav.questionGeneration", Icon: IconEdit, soon: true }, - SOUND_STUDIO_ITEM, ]), ]; @@ -259,7 +263,7 @@ const STUDENT_GROUPS: NavGroup[] = [ id: "ai", labelKey: "nav.group.ai", Icon: IconSparkles, - items: [CELEBI_ITEM], + items: [CELEBI_ITEM, AI_HUB_ITEM], }, { id: "other", @@ -276,7 +280,6 @@ const STUDENT_GROUPS: NavGroup[] = [ }, soonGroup([ { id: "study-plan", to: "/coming-soon/calisma-programim", labelKey: "nav.studyPlan", Icon: IconClock, soon: true }, - SOUND_STUDIO_ITEM, ]), ]; @@ -306,6 +309,12 @@ const PARENT_GROUPS: NavGroup[] = [ settingsAction("settings-parent"), ], }, + { + id: "ai", + labelKey: "nav.group.ai", + Icon: IconSparkles, + items: [AI_HUB_ITEM], + }, ]; const GROUPS_BY_ROLE: Record = { diff --git a/src/components/notes/note-reader-panel.tsx b/src/components/notes/note-reader-panel.tsx index ccde703..0bd65e2 100644 --- a/src/components/notes/note-reader-panel.tsx +++ b/src/components/notes/note-reader-panel.tsx @@ -3,6 +3,7 @@ import type { Note } from "@/api/client"; import type { NoteFileSource } from "@/lib/note-source"; import { NoteFilesPanel } from "@/components/notes/note-files-panel"; import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; +import { PodcastPanel } from "@/components/notes/podcast-panel"; import { SidePanel } from "@/components/ui/side-panel"; import { toRichTextHtml } from "@/lib/rich-text"; import { useT } from "@/stores/preferences-context"; @@ -39,6 +40,7 @@ export function NoteReaderPanel(props: { +
)} diff --git a/src/components/notes/podcast-panel.test.tsx b/src/components/notes/podcast-panel.test.tsx new file mode 100644 index 0000000..9fca1d7 --- /dev/null +++ b/src/components/notes/podcast-panel.test.tsx @@ -0,0 +1,53 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { PodcastPanel } from "@/components/notes/podcast-panel"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const podcastApi = vi.hoisted(() => ({ + postPodcastJob: vi.fn(), + getPodcastJobById: vi.fn(), + getPodcastJobResultById: vi.fn(), + postPodcastJobCancel: vi.fn(), + podcastAudioUrl: vi.fn((id: string) => `/api/podcast/audio?path=${encodeURIComponent(id)}`), +})); + +vi.mock("@/api/podcast", () => podcastApi); + +// The panel asks what the AI tier allows as soon as it mounts; without this the +// real client reaches for a relative URL node's fetch cannot parse. +const aiApi = vi.hoisted(() => ({ + getAiCapabilities: vi.fn(async () => ({ + enabled: true, + protocol: "hezarfen.ai.v1", + capabilities: [{ capability: "podcast.submit", workers: 1, inflight: 0 }], + })), +})); + +vi.mock("@/api/ai", () => aiApi); + +describe("PodcastPanel", () => { + afterEach(() => { + cleanup(); + sessionStorage.clear(); + vi.clearAllMocks(); + }); + + it("submits the selected lesson note and narration format", async () => { + podcastApi.postPodcastJob.mockResolvedValue({ job_id: "j1", state: "queued", eta_secs: 30 }); + + render(() => ( + + + + )); + + fireEvent.change(screen.getByLabelText("Narration style"), { target: { value: "tek_ogretici" } }); + fireEvent.click(screen.getByRole("button", { name: "Create podcast" })); + + await waitFor(() => { + expect(podcastApi.postPodcastJob).toHaveBeenCalledWith({ source_id: "note-7", format: "tek_ogretici" }); + }); + expect(sessionStorage.getItem("hezarfen.podcast.note-7")).toBe("j1"); + expect(screen.getByText("Waiting in queue")).toBeTruthy(); + }); +}); diff --git a/src/components/notes/podcast-panel.tsx b/src/components/notes/podcast-panel.tsx new file mode 100644 index 0000000..3ca58b9 --- /dev/null +++ b/src/components/notes/podcast-panel.tsx @@ -0,0 +1,217 @@ +import { For, Show, createEffect, createSignal, onCleanup } from "solid-js"; +import { createResource } from "@/lib/create-resource"; +import { getAiCapabilities } from "@/api/ai"; +import { + getPodcastJobById, + getPodcastJobResultById, + podcastAudioUrl, + postPodcastJob, + postPodcastJobCancel, +} from "@/api/podcast"; +import { formatApiError, type PodcastFormat, type PodcastJobArtifacts, type PodcastJobStatus } from "@/api/client"; +import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { IconWaveform, IconX } from "@/components/ui/icons"; +import { Label } from "@/components/ui/label"; +import { Select } from "@/components/ui/select"; +import { useT } from "@/stores/preferences-context"; + +const POLL_MS = 2_000; + +export function PodcastPanel(props: { noteId: string; active?: boolean }) { + const t = useT(); + const [format, setFormat] = createSignal("duz_okuma"); + const [jobId, setJobId] = createSignal(""); + const [status, setStatus] = createSignal(null); + const [artifacts, setArtifacts] = createSignal(null); + const [error, setError] = createSignal(""); + const [submitting, setSubmitting] = createSignal(false); + const [cancelling, setCancelling] = createSignal(false); + let timer: ReturnType | undefined; + let generation = 0; + + // Declared before the resource below: its source runs during setup, so a + // later `const active` would be read in its temporal dead zone. + const active = () => props.active !== false; + const [capabilities] = createResource(() => (active() ? getAiCapabilities() : null)); + const storageKey = () => `hezarfen.podcast.${props.noteId}`; + const stopPolling = () => { + if (timer) clearTimeout(timer); + timer = undefined; + }; + + const poll = async (id: string, token: number) => { + try { + const next = await getPodcastJobById(id); + if (token !== generation || !active()) return; + setStatus(next); + if (next.state === "done") { + const result = await getPodcastJobResultById(id); + if (token === generation) setArtifacts(result); + return; + } + if (next.state === "failed") { + setError(t("podcast.failed")); + return; + } + if (next.state === "cancelled") return; + timer = setTimeout(() => void poll(id, token), POLL_MS); + } catch (err) { + if (token === generation) setError(formatApiError(err)); + } + }; + + createEffect(() => { + const noteId = props.noteId; + const enabled = active(); + generation += 1; + const token = generation; + stopPolling(); + setJobId(""); + setStatus(null); + setArtifacts(null); + setError(""); + if (!enabled || !noteId || typeof sessionStorage === "undefined") return; + const stored = sessionStorage.getItem(storageKey()); + if (stored) { + setJobId(stored); + void poll(stored, token); + } + }); + + onCleanup(() => { + generation += 1; + stopPolling(); + }); + + const submit = async () => { + if (submitting()) return; + generation += 1; + const token = generation; + stopPolling(); + setSubmitting(true); + setError(""); + setArtifacts(null); + try { + const receipt = await postPodcastJob({ source_id: props.noteId, format: format() }); + if (token !== generation) return; + setJobId(receipt.job_id); + setStatus({ job_id: receipt.job_id, state: receipt.state, stage: "queued", progress: 0 }); + if (typeof sessionStorage !== "undefined") sessionStorage.setItem(storageKey(), receipt.job_id); + timer = setTimeout(() => void poll(receipt.job_id, token), POLL_MS); + } catch (err) { + setError(formatApiError(err)); + } finally { + if (token === generation) setSubmitting(false); + } + }; + + const cancel = async () => { + const id = jobId(); + if (!id || cancelling()) return; + setCancelling(true); + setError(""); + try { + await postPodcastJobCancel(id); + generation += 1; + stopPolling(); + setStatus((current) => current ? { ...current, state: "cancelled" } : current); + if (typeof sessionStorage !== "undefined") sessionStorage.removeItem(storageKey()); + } catch (err) { + setError(formatApiError(err)); + } finally { + setCancelling(false); + } + }; + + const progress = () => Math.round(Math.min(1, Math.max(0, status()?.progress ?? 0)) * 100); + const working = () => ["queued", "running"].includes(status()?.state ?? ""); + const available = () => { + const current = capabilities(); + if (!current || capabilities.error) return true; + return current.enabled && current.capabilities.some((item) => item.capability === "podcast.submit" && item.workers > 0); + }; + const stateLabel = (state: string) => { + if (state === "queued") return t("podcast.state.queued"); + if (state === "running") return t("podcast.state.running"); + if (state === "done") return t("podcast.state.done"); + if (state === "failed") return t("podcast.state.failed"); + if (state === "cancelled") return t("podcast.state.cancelled"); + return t("podcast.state.running"); + }; + const formatOptions = () => [ + { value: "duz_okuma", label: t("podcast.format.duz_okuma") }, + { value: "tek_ogretici", label: t("podcast.format.tek_ogretici") }, + { value: "ogrenci_hoca", label: t("podcast.format.ogrenci_hoca") }, + ]; + + return ( +
+
+
+ +
+
+

{t("podcast.title")}

+

{t("podcast.description")}

+
+
+ + {(message) => {message()}} + + {t("podcast.unavailable")} + + +
+
+ + +
+ +
+ + + {(current) => ( +
+
+ {stateLabel(current().state)} + {progress()}% +
+
+
+
+ + + +
+ )} + + + + {(result) => ( +
+

{t("podcast.ready")}

+ +
+ )} +
+
+ ); +} diff --git a/src/components/notes/rag-output-content.tsx b/src/components/notes/rag-output-content.tsx new file mode 100644 index 0000000..2a8007e --- /dev/null +++ b/src/components/notes/rag-output-content.tsx @@ -0,0 +1,54 @@ +import { For, Show } from "solid-js"; + +const SUMMARY_KEYS = ["summary", "ozet", "özet", "content", "text", "answer"]; +const LIST_KEYS = ["keywords", "key_points", "topics", "questions", "highlights"]; + +function asRecord(value: unknown): Record | null { + return value != null && typeof value === "object" && !Array.isArray(value) + ? value as Record + : null; +} + +function firstText(record: Record | null): string | null { + if (!record) return null; + for (const key of SUMMARY_KEYS) { + const value = record[key]; + if (typeof value === "string" && value.trim()) return value.trim(); + } + return null; +} + +function firstList(record: Record | null): string[] { + if (!record) return []; + for (const key of LIST_KEYS) { + const value = record[key]; + if (Array.isArray(value)) { + const rows = value.filter((item): item is string => typeof item === "string" && !!item.trim()); + if (rows.length > 0) return rows; + } + } + return []; +} + +/** Render the useful parts of the AI service's open payload without exposing a JSON dump first. */ +export function RagOutputContent(props: { payload: unknown }) { + const record = () => asRecord(props.payload); + const summary = () => typeof props.payload === "string" ? props.payload : firstText(record()); + const points = () => firstList(record()); + + return ( +
+ + {(text) =>

{text()}

} +
+ 0}> +
    + {(point) =>
  • {point}
  • }
    +
+
+ +
{JSON.stringify(props.payload, null, 2)}
+
+
+ ); +} diff --git a/src/components/notes/rag-outputs-panel.tsx b/src/components/notes/rag-outputs-panel.tsx index 996f915..effb7da 100644 --- a/src/components/notes/rag-outputs-panel.tsx +++ b/src/components/notes/rag-outputs-panel.tsx @@ -1,16 +1,19 @@ -import { For, Show, Suspense, createSignal } from "solid-js"; +import { For, Show, Suspense, createSignal, onCleanup } from "solid-js"; import { createResource } from "@/lib/create-resource"; +import { getAiCapabilities } from "@/api/ai"; import { formatApiError } from "@/api/client"; import type { RagOutput } from "@/api/client"; import type { NoteFileSource } from "@/lib/note-source"; import { Alert } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { PageSpinner } from "@/components/ui/page-spinner"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { createFlash } from "@/lib/flash"; import { formatDateTime } from "@/lib/format"; import { usePreferences, useT } from "@/stores/preferences-context"; -import { IconTrash } from "@/components/ui/icons"; +import { IconSparkles, IconTrash } from "@/components/ui/icons"; +import { RagOutputContent } from "@/components/notes/rag-output-content"; const RAG_PAGE_SIZE = 10; @@ -26,13 +29,56 @@ export function RagOutputsPanel(props: { const [error, setError] = createSignal(""); const [flash, setFlash] = createFlash(); const [deleteTarget, setDeleteTarget] = createSignal(null); + const [generating, setGenerating] = createSignal(false); + let pollTimer: ReturnType | undefined; + + onCleanup(() => pollTimer && clearTimeout(pollTimer)); const [list, { refetch }] = createResource( () => (props.active && props.source.listRagOutputs ? props.noteId : null), async (noteId) => props.source.listRagOutputs!(noteId, { limit: RAG_PAGE_SIZE }), ); + const [capabilities] = createResource( + () => (props.active && props.source.reindexRag ? true : null), + () => getAiCapabilities(), + ); const outputs = () => list()?.items ?? []; + const available = () => capabilities.error || capabilities()?.enabled !== false; + + const generate = async () => { + if (!props.source.reindexRag || generating()) return; + setError(""); + setGenerating(true); + const previousId = outputs()[0]?.id; + try { + await props.source.reindexRag(props.noteId); + let attempts = 0; + const poll = async () => { + if (!props.active) { + setGenerating(false); + return; + } + attempts += 1; + const next = await refetch(); + const firstId = next?.items?.[0]?.id; + if ((firstId && firstId !== previousId) || attempts >= 24) { + setGenerating(false); + setFlash(firstId && firstId !== previousId ? t("courseNotes.ragReady") : t("courseNotes.ragQueued")); + return; + } + pollTimer = setTimeout(() => void poll().catch(fail), 2500); + }; + const fail = (err: unknown) => { + setGenerating(false); + setError(formatApiError(err)); + }; + pollTimer = setTimeout(() => void poll().catch(fail), 1500); + } catch (err) { + setGenerating(false); + setError(formatApiError(err)); + } + }; const remove = async () => { const target = deleteTarget(); @@ -51,13 +97,27 @@ export function RagOutputsPanel(props: { return (
-

{t("courseNotes.ragTitle")}

+
+
+

{t("courseNotes.ragTitle")}

+

{t("courseNotes.ragHint")}

+
+ + + +
{flash()} {error()} + + {t("courseNotes.ragUnavailable")} + }> {formatApiError(list.error)} @@ -87,7 +147,7 @@ export function RagOutputsPanel(props: {
-
{JSON.stringify(output.payload, null, 2)}
+ )} diff --git a/src/components/rag/rag-citations.tsx b/src/components/rag/rag-citations.tsx new file mode 100644 index 0000000..f6e90ec --- /dev/null +++ b/src/components/rag/rag-citations.tsx @@ -0,0 +1,44 @@ +import { For, Show } from "solid-js"; +import type { RagCitation } from "@/api/client"; +import { IconBook, IconFileText } from "@/components/ui/icons"; + +export function RagCitations(props: { + citations: RagCitation[]; + labels: { sources: string; source: string; subject: string; pages: string; document: string }; +}) { + return ( + 0}> +
+

+ {props.labels.sources} +

+
    + + {(citation) => ( +
  1. +
    + + {citation.n} + +
    +

    + }> + + + {citation.ders || props.labels.document} +

    + 0}> +

    + {props.labels.pages}: {citation.pages.join(", ")} +

    +
    +
    +
    +
  2. + )} +
    +
+
+
+ ); +} diff --git a/src/components/rag/rag-composer.tsx b/src/components/rag/rag-composer.tsx new file mode 100644 index 0000000..4c81e6f --- /dev/null +++ b/src/components/rag/rag-composer.tsx @@ -0,0 +1,69 @@ +import { createEffect } from "solid-js"; +import { Button } from "@/components/ui/button"; +import { IconSend } from "@/components/ui/icons"; +import { Textarea } from "@/components/ui/textarea"; + +const MAX_HEIGHT_PX = 176; + +export function RagComposer(props: { + value: string; + placeholder: string; + sendLabel: string; + hint: string; + disabled: boolean; + onInput: (value: string) => void; + onSubmit: () => void; +}) { + let field: HTMLTextAreaElement | undefined; + + const resize = () => { + if (!field) return; + field.style.height = "auto"; + field.style.height = `${Math.min(field.scrollHeight, MAX_HEIGHT_PX)}px`; + }; + + createEffect(() => { + void props.value; + resize(); + }); + + return ( + { + event.preventDefault(); + if (!props.disabled) props.onSubmit(); + }} + > +
+