diff --git a/src/components/ai/insights-board.tsx b/src/components/ai/insights-board.tsx index 1014a11..23340f1 100644 --- a/src/components/ai/insights-board.tsx +++ b/src/components/ai/insights-board.tsx @@ -1,37 +1,28 @@ -import { Show, Suspense, createMemo, createSignal } from "solid-js"; +import { Show, Suspense, createEffect, createMemo, createSignal, on } 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 { getInsightRuns, getMyInsight, postInsightsRefresh } from "@/api/insights"; +import { formatApiError, type Role } from "@/api/client"; import { InsightDetail } from "@/components/insights/insight-detail"; +import { InsightOverview } from "@/components/insights/insight-overview"; import { InsightRunsTable } from "@/components/insights/insight-runs-table"; -import { RosterPersonCell } from "@/components/users/roster-person-cell"; +import { InsightStudentsTable } from "@/components/insights/insight-students-table"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; -import { DataTable, DataTableSkeleton } from "@/components/ui/data-table"; +import { 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 { IconRefresh, IconSparkles } from "@/components/ui/icons"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { createFlash } from "@/lib/flash"; -import { matchesSearch } from "@/lib/search-text"; +import { toStudentSignal, type StudentSignal } from "@/lib/insight-run-report"; +import { insightOverview, loadInsightStudents, loadStudentSignals } from "@/lib/insight-students"; 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. */ +/** Every insight surface in one board: the viewer's own analysis, the picture + * over the students they may browse (with each one's analysis in the table), + * and the school-wide run log for managers. A student opens as a full page. */ export function InsightsBoard() { const auth = useAuth(); const prefs = usePreferences(); @@ -39,12 +30,10 @@ export function InsightsBoard() { 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 [insightTab, setInsightTab] = createSignal<"zeka" | "runs">("zeka"); + const [flashMessage, flash] = createFlash(); const [selfInsight, { refetch: refetchSelfInsight }] = createResource( () => auth.user()?.id ?? null, @@ -52,28 +41,26 @@ export function InsightsBoard() { ); 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, + async (viewerRole: Role) => loadInsightStudents(viewerRole), ); 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; - } - }, - ); + // Each student's analysis lands in its row as it is read; rows start as + // "not loaded" so the table and the overview never show a guessed value. + const [signals, setSignals] = createSignal>({}); + let readGeneration = 0; + createEffect(on(() => students.latest, (list) => { + if (!list) return; + const generation = ++readGeneration; + setSignals(Object.fromEntries(list.map((person) => [person.id, toStudentSignal({ id: person.id, name: personLabel(person) }, null, null)]))); + void loadStudentSignals(list, (row) => { + if (generation === readGeneration) setSignals((current) => ({ ...current, [row.id]: row })); + }); + })); + const rows = createMemo(() => Object.values(signals())); + const overview = createMemo(() => insightOverview(rows(), students.latest?.length ?? 0)); const refreshPage = async () => { setPageError(""); @@ -102,54 +89,58 @@ export function InsightsBoard() { } }; - 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 studentAnalysis = () => ( + + }> + + void refetchStudents()} /> + + + +
+ + + + + + + } + /> +
+
+
+
+ ); - 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), - }, - ]} - /> - ), - }, - ]); + const runAnalysis = () => ( +
+ }> + + void refetchRuns()} /> + + + + + +
+ ); return (
@@ -194,98 +185,25 @@ export function InsightsBoard() { - -
- }> - - 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} - /> - - -
+ + {flashMessage()} - -
- }> - - void refetchRuns()} /> - - - - - -
+ + setInsightTab(value as "zeka" | "runs")} class="space-y-4"> + + {tx("insights.title")} + {tx("insights.runs")} + + + {studentAnalysis()} + + + {runAnalysis()} + + - { - 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/insights/insight-overview.tsx b/src/components/insights/insight-overview.tsx new file mode 100644 index 0000000..9ed2014 --- /dev/null +++ b/src/components/insights/insight-overview.tsx @@ -0,0 +1,51 @@ +import { Show } from "solid-js"; +import { runReportDecimal, runReportPercent } from "@/lib/insight-run-report"; +import type { InsightOverview as Overview } from "@/lib/insight-students"; +import { cn } from "@/lib/cn"; +import { usePreferences } from "@/stores/preferences-context"; + +/** + * The picture over the students read so far: how many have an analysis, how + * many need attention, and the mean mark and attendance their summaries + * measured. A figure no summary measured reads "no data", never 0. + */ +export function InsightOverview(props: { overview: Overview }) { + const prefs = usePreferences(); + const t = (key: string, vars?: Record) => prefs.t(key as never, vars); + const tile = (label: string, value: string, hint: string, tone?: "warn") => ( +
+

{label}

+

{value}

+

{hint}

+
+ ); + const o = () => props.overview; + return ( +
+
+ {tile(t("insights.overview.analysed"), String(o().analysed), t("insights.overview.ofTotal", { total: o().total }))} + {tile( + t("insights.overview.needAttention"), + String(o().needAttention), + t("insights.overview.ofTotal", { total: o().total }), + o().needAttention > 0 ? "warn" : undefined, + )} + {tile( + t("insights.overview.marks"), + o().marksAverage == null ? "—" : runReportDecimal(o().marksAverage!, prefs.locale()), + o().marksAverage == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }), + )} + {tile( + t("insights.overview.attendance"), + o().attendanceRate == null ? "—" : runReportPercent(o().attendanceRate, prefs.locale()), + o().attendanceRate == null ? t("insights.overview.noData") : t("insights.overview.ofTotal", { total: o().analysed }), + )} +
+ +

+ {t("insights.overview.reading", { loaded: o().loaded, total: o().total })} +

+
+
+ ); +} diff --git a/src/components/insights/insight-runs-table.tsx b/src/components/insights/insight-runs-table.tsx index ffa2646..416d7e8 100644 --- a/src/components/insights/insight-runs-table.tsx +++ b/src/components/insights/insight-runs-table.tsx @@ -5,7 +5,6 @@ import { InsightRunReport } from "@/components/insights/insight-run-report"; import { Badge } from "@/components/ui/badge"; import { DataTable } from "@/components/ui/data-table"; import { IconFileText } from "@/components/ui/icons"; -import { SidePanel } from "@/components/ui/side-panel"; import { TableRowActions } from "@/components/ui/table-row-actions"; import { runReportText, type RunReportKey } from "@/i18n/insights-run-report"; import { cn } from "@/lib/cn"; @@ -31,6 +30,7 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { { accessorKey: "run_day", header: tx("insights.runDay"), + meta: { align: "center" }, cell: (cell) => (

{cell.row.original.run_day}

@@ -41,6 +41,7 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { { accessorKey: "status", header: tx("insights.result"), + meta: { align: "center" }, cell: (cell) => ( {runReportStatusLabel(prefs.locale(), cell.row.original.status)} @@ -51,11 +52,11 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { id: "processed", header: tx("insights.processed"), accessorFn: (row) => row.students_ok, - meta: { align: "right" }, + meta: { align: "center" }, cell: (cell) => { const run = cell.row.original; return ( -
+

{run.students_ok}/{run.students_total}

{run.students_failed} / {run.students_skipped}

@@ -65,23 +66,24 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { { accessorKey: "rows_written", header: tx("insights.written"), - meta: { align: "right", cellClass: "mono tabular-nums" }, + meta: { align: "center", cellClass: "mono tabular-nums" }, }, { accessorKey: "duration_ms", header: tx("insights.duration"), - meta: { align: "right" }, + meta: { align: "center" }, cell: (cell) => {formatDurationMinutes(cell.row.original.duration_ms, prefs.locale())}, }, { id: "issues", header: tx("insights.issues"), enableSorting: false, + meta: { align: "center" }, 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" : "text-muted-foreground")}> {issueCount > 0 ? tx("insights.issueCount", { count: issueCount }) : tx("insights.noIssues")}

@@ -133,7 +135,7 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { columns={columns()} data={props.runs} empty={tx("insights.emptyRuns")} - tableClass="min-w-[980px]" + tableClass="insight-grid-table min-w-[980px]" enablePagination pageSize={10} storageKey="insight-runs" @@ -142,16 +144,22 @@ export function InsightRunsTable(props: { runs: InsightRun[] }) { {(run) => ( - { - if (!open) setSelectedRun(null); - }} - title={rtx("panelDescription", { day: run.run_day })} - > +
+
+
+

{rtx("open")}

+

{rtx("panelDescription", { day: run.run_day })}

+
+ +
- +
)}
diff --git a/src/components/insights/insight-student-analysis-tabs.tsx b/src/components/insights/insight-student-analysis-tabs.tsx new file mode 100644 index 0000000..55ace1a --- /dev/null +++ b/src/components/insights/insight-student-analysis-tabs.tsx @@ -0,0 +1,237 @@ +import { For, Show } from "solid-js"; +import type { StudentInsight } from "@/api/client"; +import { InsightDetail } from "@/components/insights/insight-detail"; +import { InsightModuleView } from "@/components/insights/insight-module-views"; +import { EmptyInline } from "@/components/ui/empty-inline"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { isRecord, type UnknownRecord } from "@/lib/is-record"; +import { usePreferences } from "@/stores/preferences-context"; + +type Rec = UnknownRecord; + +const obj = (value: unknown): Rec => (isRecord(value) ? value : {}); +const num = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) ? value : null; + +function ChartCard(props: { label: string; value: string; hint?: string }) { + return ( +
+

{props.label}

+

{props.value}

+ +

{props.hint}

+
+
+ ); +} + +function BarChart(props: { + items: Array<{ label: string; value: number | null; color?: string }>; + format?: (value: number) => string; +}) { + const max = () => Math.max(...props.items.map((item) => item.value ?? 0), 1); + const format = (value: number) => props.format?.(value) ?? String(value); + return ( +
+ + {(item) => ( +
+
+ {item.label} + + {item.value == null ? "—" : format(item.value)} + +
+
+
+
+
+ )} + +
+ ); +} + +function AttendanceChart(props: { value: unknown; t: (key: string) => string }) { + const overall = () => obj(obj(props.value).overall); + const count = (key: string) => num(overall()[key]) ?? 0; + const rate = () => num(overall().rate); + return ( +
+
+ + + +
+ +
+ ); +} + +function MarksChart(props: { value: unknown; t: (key: string) => string }) { + const courses = () => Object.entries(obj(obj(props.value).courses)); + const items = () => courses().map(([id, raw]) => { + const stat = obj(raw); + return { label: String(stat.course_title ?? id).slice(0, 32), value: num(stat.average) }; + }); + const averages = () => items().map((item) => item.value).filter((value): value is number => value != null); + const average = () => averages().length ? averages().reduce((sum, value) => sum + value, 0) / averages().length : null; + return ( +
+
+ + + +
+ 0} fallback={}> + value.toLocaleString("tr-TR", { maximumFractionDigits: 1 })} /> + +
+ ); +} + +function StudyChart(props: { value: unknown; t: (key: string) => string }) { + const recent = () => obj(obj(props.value).recent_28d); + const hours = () => { + const milliseconds = num(recent().total_focus_ms); + return milliseconds == null ? null : milliseconds / 3_600_000; + }; + return ( +
+
+ + + +
+ value.toLocaleString("tr-TR", { maximumFractionDigits: 1 })} + /> +
+ ); +} + +function SubmissionChart(props: { value: unknown; t: (key: string) => string }) { + const overall = () => obj(obj(props.value).overall); + const count = (key: string) => num(overall()[key]) ?? 0; + const total = () => count("n"); + const submittedRate = () => total() > 0 ? count("n_submitted") / total() : null; + return ( +
+
+ + + +
+ +
+ ); +} + +function ModuleTab(props: { + module: "attendance" | "marks" | "study" | "submission"; + value: unknown; + courseTitle: (id: string) => string | null; + t: (key: string) => string; +}) { + const chart = () => { + if (props.module === "attendance") return ; + if (props.module === "marks") return ; + if (props.module === "study") return ; + return ; + }; + return ( + }> +
+
+
+

{props.t(`insights.modules.${props.module}`)}

+ {props.t("insights.analysis.visual")} +
+ {chart()} +
+
+ +
+
+
+ ); +} + +export function InsightStudentAnalysisTabs(props: { insight: StudentInsight }) { + const prefs = usePreferences(); + const t = (key: string) => prefs.t(key as never); + const summary = () => props.insight.summary; + const courseTitle = (id: string) => { + const courses = obj(obj(summary()?.marks).courses); + const course = obj(courses[id]); + return typeof course.course_title === "string" ? course.course_title : null; + }; + const moduleValue = (module: "attendance" | "marks" | "study" | "submission") => summary()?.[module] ?? null; + + return ( + + + {t("insights.analysis.overview")} + {t("insights.modules.attendance")} + {t("insights.modules.marks")} + {t("insights.modules.study")} + {t("insights.modules.submission")} + + + +
+ + { + const values = Object.values(obj(obj(moduleValue("marks")).courses)).map((raw) => num(obj(raw).average)).filter((value): value is number => value != null); + return values.length ? (values.reduce((sum, value) => sum + value, 0) / values.length).toLocaleString("tr-TR", { maximumFractionDigits: 1 }) : "—"; + })()} /> + { + const milliseconds = num(obj(obj(moduleValue("study")).recent_28d).total_focus_ms); + return milliseconds == null ? "—" : `${(milliseconds / 3_600_000).toLocaleString("tr-TR", { maximumFractionDigits: 1 })} sa`; + })()} /> + { + const overall = obj(obj(moduleValue("submission")).overall); + const total = num(overall.n) ?? 0; + const submitted = num(overall.n_submitted) ?? 0; + return total > 0 ? `%${Math.round((submitted / total) * 100)}` : "—"; + })()} /> +
+ +
+ + + + + + + + + + + + + +
+ ); +} diff --git a/src/components/insights/insight-students-table.tsx b/src/components/insights/insight-students-table.tsx new file mode 100644 index 0000000..7b61e91 --- /dev/null +++ b/src/components/insights/insight-students-table.tsx @@ -0,0 +1,221 @@ +import { For, createMemo, createSignal, type JSX } from "solid-js"; +import { Link, useNavigate } from "@tanstack/solid-router"; +import type { ColumnDef } from "@tanstack/solid-table"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { DataTable } from "@/components/ui/data-table"; +import { IconEye } from "@/components/ui/icons"; +import { TableRowActions } from "@/components/ui/table-row-actions"; +import { runReportText } from "@/i18n/insights-run-report"; +import { + confidenceText, + studentAttendanceText, + studentMarksText, + studentStatusText, + type StudentSignal, +} from "@/lib/insight-run-report"; +import { cn } from "@/lib/cn"; +import { matchesSearch } from "@/lib/search-text"; +import { usePreferences } from "@/stores/preferences-context"; + +type Filter = "all" | "attention" | "none"; + +/** + * Every student's analysis at a glance: status, attention items, cards, the + * marks, attendance and focus their summary measured, confidence and when it + * was computed. Numeric columns sort on the real value; a row opens the + * student's full analysis page. + */ +export function InsightStudentsTable(props: { + rows: StudentSignal[]; + title: string; + description: string; + empty: string; + actions?: JSX.Element; +}) { + const prefs = usePreferences(); + const navigate = useNavigate(); + const locale = () => prefs.locale(); + const t = (key: string, vars?: Record) => prefs.t(key as never, vars); + const rt = (key: Parameters[1]) => runReportText(locale(), key); + const [filter, setFilter] = createSignal("all"); + const visible = createMemo(() => + props.rows.filter((row) => + filter() === "attention" ? row.attention > 0 : filter() === "none" ? row.state === "no_summary" : true, + ), + ); + const counts = createMemo(() => ({ + all: props.rows.length, + attention: props.rows.filter((row) => row.attention > 0).length, + none: props.rows.filter((row) => row.state === "no_summary").length, + })); + const loaded = (row: StudentSignal) => row.state === "ok"; + const muted = "text-muted-foreground"; + const calculatedDate = (value: number | null | undefined) => { + if (value == null) return "—"; + return new Intl.DateTimeFormat(locale() === "tr" ? "tr-TR" : "en-US", { + day: "2-digit", + month: "2-digit", + year: "numeric", + }).format(new Date(value)); + }; + + const columns = createMemo[]>(() => [ + { + id: "student", + accessorFn: (row) => row.name, + header: rt("student"), + size: 220, + meta: { align: "center" }, + cell: (cell) => ( + + {cell.row.original.name} + + ), + }, + { + id: "status", + accessorFn: (row) => row.state, + header: rt("status" as never), + meta: { align: "center" }, + cell: (cell) => { + const row = cell.row.original; + return ( + + {row.state === "error" ? t("insights.readFailed") : studentStatusText(locale(), row)} + + ); + }, + }, + { + id: "attention", + accessorFn: (row) => row.attention, + header: rt("attention"), + meta: { align: "center" }, + cell: (cell) => ( + 0 ? "font-semibold text-warning-text" : muted)}> + {loaded(cell.row.original) || cell.row.original.state === "no_summary" ? cell.row.original.attention : "—"} + + ), + }, + { + id: "cards", + accessorFn: (row) => row.cards, + header: rt("cards"), + meta: { align: "center" }, + cell: (cell) => {cell.row.original.state === "not_loaded" ? "—" : cell.row.original.cards}, + }, + { + id: "marks", + accessorFn: (row) => row.marks.average ?? -1, + header: rt("marksAverage"), + meta: { align: "center" }, + cell: (cell) => {studentMarksText(locale(), cell.row.original)}, + }, + { + id: "attendance", + accessorFn: (row) => (row.attendance.observed > 0 ? row.attendance.rate ?? -1 : -1), + header: rt("attendanceRate"), + meta: { align: "center" }, + cell: (cell) => { + const row = cell.row.original; + const low = loaded(row) && row.attendance.observed > 0 && (row.attendance.rate ?? 1) < 0.85; + return {studentAttendanceText(locale(), row)}; + }, + }, + { + id: "study", + accessorFn: (row) => row.study.stints, + header: t("insights.studyStints"), + meta: { align: "center" }, + cell: (cell) => {loaded(cell.row.original) ? cell.row.original.study.stints : "—"}, + }, + { + id: "confidence", + accessorFn: (row) => row.confidence ?? "", + header: rt("confidence"), + meta: { align: "center" }, + cell: (cell) => {cell.row.original.confidence ? confidenceText(locale(), cell.row.original.confidence) : "—"}, + }, + { + id: "computedAt", + accessorFn: (row) => row.computed_at ?? 0, + header: t("insights.computedAt"), + meta: { align: "center", cellClass: "mono text-xs text-muted-foreground whitespace-nowrap" }, + cell: (cell) => calculatedDate(cell.row.original.computed_at), + }, + { + id: "actions", + header: t("common.actions"), + enableSorting: false, + meta: { + align: "center", + headerClass: "text-center", + cellClass: "text-center", + }, + cell: (cell) => ( + , + onSelect: () => void navigate({ to: "/ai/insights/$userId", params: { userId: cell.row.original.id } }), + }]} + /> + ), + }, + ]); + + const filters: { id: Filter; label: string }[] = [ + { id: "all", label: t("insights.filter.all") }, + { id: "attention", label: t("insights.filter.attention") }, + { id: "none", label: t("insights.filter.noAnalysis") }, + ]; + + return ( + void navigate({ to: "/ai/insights/$userId", params: { userId: row.id } })} + empty={props.empty} + emptyIllustration="people" + filterPlaceholder={t("insights.searchStudents")} + filterHint={t("search.hint.people")} + searchPredicate={(row, query) => matchesSearch(query, row.name)} + filters={ +
+ + {(item) => ( + + )} + +
+ } + enablePagination + pageSize={10} + tableClass="insight-grid-table min-w-[70rem]" + storageKey="insight-students-v2" + /> + ); +} diff --git a/src/components/layout/nav-items.test.ts b/src/components/layout/nav-items.test.ts index a94d262..4ee1ac2 100644 --- a/src/components/layout/nav-items.test.ts +++ b/src/components/layout/nav-items.test.ts @@ -163,12 +163,13 @@ test("the AI group exposes four separate module routes", () => { expect(routeLabelKey("/ai/studio", "student")).toBe("aiHub.tab.studio"); }); -test("AI modules navigate while account settings still opens a shell surface", () => { +test("AI modules navigate while Çelebi and account settings open shell surfaces", () => { const celebi = visibleNavGroups("student") .flatMap((g) => g.items) .find((i) => i.id === "ai-celebi"); - expect(celebi?.to).toBe("/ai/celebi"); - expect(celebi?.action).toBeUndefined(); + expect(celebi?.to).toBe(""); + expect(celebi?.action).toBe("celebi"); + expect(routeNavItem("/ai/celebi", "student")).toBeUndefined(); const settings = visibleNavGroups("student") .flatMap((g) => g.items) .find((i) => i.id === "settings-student"); diff --git a/src/components/layout/nav-items.ts b/src/components/layout/nav-items.ts index da7941b..60a0199 100644 --- a/src/components/layout/nav-items.ts +++ b/src/components/layout/nav-items.ts @@ -97,9 +97,10 @@ const AI_INSIGHTS_ITEM: NavItem = { const AI_CELEBI_ITEM: NavItem = { id: "ai-celebi", - to: "/ai/celebi", + to: "", labelKey: "nav.celebi", Icon: IconSparkles, + action: "celebi", }; const AI_GROUP: NavGroup = { diff --git a/src/components/rag/rag-study-panel.tsx b/src/components/rag/rag-study-panel.tsx index 0a36c86..f732724 100644 --- a/src/components/rag/rag-study-panel.tsx +++ b/src/components/rag/rag-study-panel.tsx @@ -18,8 +18,7 @@ import { RagThreadList } from "@/components/rag/rag-thread-list"; import { Alert } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { EmptyInline } from "@/components/ui/empty-inline"; -import { IconPlus } from "@/components/ui/icons"; +import { IconEdit, IconPlus } from "@/components/ui/icons"; import { scopeFromCitations } from "@/lib/rag-study-scope"; import { usePreferences } from "@/stores/preferences-context"; @@ -35,6 +34,7 @@ export function RagStudyPanel() { const { locale } = usePreferences(); const copy = () => ragCopy(locale()); const [threadId, setThreadId] = createSignal(); + const [activeThread, setActiveThread] = createSignal(); const [threadsVersion, setThreadsVersion] = createSignal(0); const [messages, setMessages] = createSignal([]); const [draft, setDraft] = createSignal(""); @@ -113,6 +113,7 @@ export function RagStudyPanel() { stopStream(); setError(""); setThreadId(thread.id); + setActiveThread(thread); try { setMessages((await getRagThreadMessages(thread.id, { limit: 500 })).items); } catch (err) { @@ -124,6 +125,7 @@ export function RagStudyPanel() { stopStream(); setError(""); setThreadId(undefined); + setActiveThread(undefined); setMessages([]); }; @@ -139,14 +141,17 @@ export function RagStudyPanel() { { id: `local-${now}`, thread_id: threadId() ?? "", role: "user", status: "complete", content, abstained: false, reason: "", citations: [], created_at: now }, ]); try { - const activeThread = threadId() ?? (await postRagThread()).id; - setThreadId(activeThread); - const accepted = await postRagMessage(activeThread, content); + const currentThread = threadId(); + const createdThread = currentThread ? undefined : await postRagThread(); + const resolvedThreadId = currentThread ?? createdThread!.id; + if (createdThread) setActiveThread(createdThread); + setThreadId(resolvedThreadId); + const accepted = await postRagMessage(resolvedThreadId, content); setMessages((items) => [ ...items, - { id: accepted.message_id, thread_id: activeThread, role: "assistant", status: "pending", content: "", abstained: false, reason: "", citations: [], created_at: Date.now() }, + { id: accepted.message_id, thread_id: resolvedThreadId, role: "assistant", status: "pending", content: "", abstained: false, reason: "", citations: [], created_at: Date.now() }, ]); - streamAnswer(activeThread, accepted.message_id); + streamAnswer(resolvedThreadId, accepted.message_id); setThreadsVersion((version) => version + 1); } catch (err) { setError(formatApiError(err)); @@ -163,8 +168,8 @@ export function RagStudyPanel() { }; return ( -
-