From 2dcef80d79dd92bbeca8eceee49c358d61c3d6d7 Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 14:48:12 +0100 Subject: [PATCH 1/2] admin: content/ records are read-only in every section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories, companies, roadmaps, roadmap steps and answers imported from content/ now show the "из content/" badge with edit, delete and status controls disabled, instead of failing with 409 on save. Roadmap list and item responses now carry source. --- app/schemas/roadmap.py | 2 + app/services/roadmap.py | 3 ++ frontend/openapi.json | 12 +++++ .../components/Admin/Answers/AnswersTable.tsx | 39 +++++++++----- .../src/components/Admin/Categories/index.tsx | 40 ++++++++++----- .../src/components/Admin/Companies/index.tsx | 29 +++++++---- .../Admin/Questions/QuestionsTable.tsx | 51 ++++++++++--------- .../Admin/RoadmapItems/ItemsManager.tsx | 23 +++++---- .../src/components/Admin/Roadmaps/index.tsx | 40 ++++++++++----- frontend/src/components/Admin/common.tsx | 18 ++++++- .../src/components/Admin/contentManaged.ts | 9 ++++ frontend/src/services/roadmapService.ts | 3 ++ frontend/src/types/api.generated.ts | 12 +++++ frontend/src/types/index.ts | 8 ++- tests/test_content_import.py | 21 ++++++++ 15 files changed, 227 insertions(+), 83 deletions(-) create mode 100644 frontend/src/components/Admin/contentManaged.ts diff --git a/app/schemas/roadmap.py b/app/schemas/roadmap.py index 0f9c0bb..4bc9c42 100644 --- a/app/schemas/roadmap.py +++ b/app/schemas/roadmap.py @@ -27,6 +27,7 @@ class RoadmapItemUpdate(BaseModel): class RoadmapItemResponse(BaseModel): """Схема ответа для элемента roadmap.""" + source: str = Field("admin", description="content — запись из content/ (read-only в админке)") id: UUID roadmap_id: UUID category_id: UUID @@ -81,6 +82,7 @@ class RoadmapResponse(BaseModel): class RoadmapListResponse(BaseModel): """Ответ с списком roadmaps.""" + source: str = Field("admin", description="content — запись из content/ (read-only в админке)") id: UUID title: str slug: str diff --git a/app/services/roadmap.py b/app/services/roadmap.py index 37b9d8d..febc8c8 100644 --- a/app/services/roadmap.py +++ b/app/services/roadmap.py @@ -258,6 +258,7 @@ async def get_all_roadmaps(self, is_active: bool = True) -> list[RoadmapListResp detail = details[roadmap.id] result.append( RoadmapListResponse( + source=roadmap.source, id=roadmap.id, title=roadmap.title, slug=roadmap.slug, @@ -422,6 +423,7 @@ def _roadmap_to_response(self, roadmap: Roadmap) -> RoadmapResponse: """Конвертировать Roadmap в RoadmapResponse.""" items = [ RoadmapItemResponse( + source=item.source, id=item.id, roadmap_id=item.roadmap_id, category_id=item.category_id, @@ -435,6 +437,7 @@ def _roadmap_to_response(self, roadmap: Roadmap) -> RoadmapResponse: ] return RoadmapResponse( + source=roadmap.source, id=roadmap.id, title=roadmap.title, slug=roadmap.slug, diff --git a/frontend/openapi.json b/frontend/openapi.json index 65665e2..7b7523a 100644 --- a/frontend/openapi.json +++ b/frontend/openapi.json @@ -2789,6 +2789,12 @@ "title": "Roadmap Id", "type": "string" }, + "source": { + "default": "admin", + "description": "content — запись из content/ (read-only в админке)", + "title": "Source", + "type": "string" + }, "title": { "anyOf": [ { @@ -2870,6 +2876,12 @@ "title": "Slug", "type": "string" }, + "source": { + "default": "admin", + "description": "content — запись из content/ (read-only в админке)", + "title": "Source", + "type": "string" + }, "steps_count": { "anyOf": [ { diff --git a/frontend/src/components/Admin/Answers/AnswersTable.tsx b/frontend/src/components/Admin/Answers/AnswersTable.tsx index f0a8fda..a1b59de 100644 --- a/frontend/src/components/Admin/Answers/AnswersTable.tsx +++ b/frontend/src/components/Admin/Answers/AnswersTable.tsx @@ -20,6 +20,8 @@ import { radius, useTokens } from '../../../theme/tokens'; import { plural } from '../../../utils/difficulty'; import type { Answer } from '../../../types'; import { PublishToggle } from '../Questions/PublishToggle'; +import { ContentSourceChip } from '../common'; +import { editHint, isContentManaged } from '../contentManaged'; import { formatAnswerDate, getContentPreview } from './utils'; interface AnswersTableProps { @@ -72,6 +74,7 @@ export const AnswersTable = ({ {answers.map((answer) => { const blockCount = answer.content?.length || 0; const hasCode = answer.content?.some((block) => block.type === 'code'); + const managed = isContentManaged(answer); return ( @@ -91,6 +94,7 @@ export const AnswersTable = ({ Обновлён: {formatAnswerDate(answer.updated_at || answer.created_at)} + {managed && } @@ -108,24 +112,35 @@ export const AnswersTable = ({ onTogglePublished(answer)} /> - - onEdit(answer)} sx={actionButtonSx}> - - + + + onEdit(answer)} + disabled={managed} + sx={actionButtonSx} + > + + + - - onDelete(answer)} - sx={{ ...actionButtonSx, '&:hover': { color: c.danger, backgroundColor: c.dangerSoft } }} - > - - + + + onDelete(answer)} + disabled={managed} + sx={{ ...actionButtonSx, '&:hover': { color: c.danger, backgroundColor: c.dangerSoft } }} + > + + + diff --git a/frontend/src/components/Admin/Categories/index.tsx b/frontend/src/components/Admin/Categories/index.tsx index a0403e6..cc5cc5d 100644 --- a/frontend/src/components/Admin/Categories/index.tsx +++ b/frontend/src/components/Admin/Categories/index.tsx @@ -23,7 +23,8 @@ import type { Category } from '../../../types'; import { fonts } from '../../../theme/tokens'; import { plural } from '../../../utils/difficulty'; import { ConfirmDialog, EmptyState } from '../../ui'; -import { SectionHeader, StatusChip } from '../common'; +import { ContentSourceChip, SectionHeader, StatusChip } from '../common'; +import { editHint, isContentManaged } from '../contentManaged'; import { CategoryDialog, type CategoryFormData } from './CategoryDialog'; const ITEMS_PER_PAGE = 10; @@ -203,9 +204,12 @@ export const AdminCategories: React.FC = () => { return categories.map((category) => ( - - {category.name} - + + + {category.name} + + {isContentManaged(category) && } + @@ -223,13 +227,14 @@ export const AdminCategories: React.FC = () => { - + {updatingIds.has(category.id) ? ( ) : ( handleToggleActive(category)} slotProps={{ input: { 'aria-label': `Статус категории ${category.name}` } }} /> @@ -241,15 +246,24 @@ export const AdminCategories: React.FC = () => { - - handleOpenDialog(category)} aria-label="Редактировать"> - - + + + handleOpenDialog(category)} disabled={isContentManaged(category)} aria-label="Редактировать"> + + + - - setDeleteTarget(category)} aria-label="Удалить" sx={{ '&:hover': { color: 'error.main' } }}> - - + + + setDeleteTarget(category)} + disabled={isContentManaged(category)} + aria-label="Удалить" + sx={{ '&:hover': { color: 'error.main' } }} + > + + + diff --git a/frontend/src/components/Admin/Companies/index.tsx b/frontend/src/components/Admin/Companies/index.tsx index ffe0079..40ec11c 100644 --- a/frontend/src/components/Admin/Companies/index.tsx +++ b/frontend/src/components/Admin/Companies/index.tsx @@ -30,7 +30,8 @@ import type { Company, CompanyCreate, CompanyUpdate, Question } from '../../../t import { fonts, radius, useTokens } from '../../../theme/tokens'; import { plural } from '../../../utils/difficulty'; import { ConfirmDialog, EmptyState, SearchInput } from '../../ui'; -import { SectionHeader, StatusChip } from '../common'; +import { ContentSourceChip, SectionHeader, StatusChip } from '../common'; +import { editHint, isContentManaged } from '../contentManaged'; import { CompanyDialog, type CompanyFormData } from './CompanyDialog'; import { CompanyQuestionsDialog } from './CompanyQuestionsDialog'; @@ -231,6 +232,7 @@ export const AdminCompanies: React.FC = () => { {company.name} + {isContentManaged(company) && } @@ -249,15 +251,24 @@ export const AdminCompanies: React.FC = () => { - - handleOpenDialog(company)} aria-label="Редактировать"> - - + + + handleOpenDialog(company)} disabled={isContentManaged(company)} aria-label="Редактировать"> + + + - - setDeleteTarget(company)} aria-label="Удалить" sx={{ '&:hover': { color: 'error.main' } }}> - - + + + setDeleteTarget(company)} + disabled={isContentManaged(company)} + aria-label="Удалить" + sx={{ '&:hover': { color: 'error.main' } }} + > + + + diff --git a/frontend/src/components/Admin/Questions/QuestionsTable.tsx b/frontend/src/components/Admin/Questions/QuestionsTable.tsx index 4bfabc1..43d155e 100644 --- a/frontend/src/components/Admin/Questions/QuestionsTable.tsx +++ b/frontend/src/components/Admin/Questions/QuestionsTable.tsx @@ -1,7 +1,6 @@ import { Box, Button, - Chip, CircularProgress, IconButton, Stack, @@ -21,6 +20,8 @@ import { CategoryChip, DifficultyChip, EmptyState } from '../../ui'; import { radius, useTokens } from '../../../theme/tokens'; import type { Category, Question } from '../../../types'; import { PublishToggle } from './PublishToggle'; +import { ContentSourceChip } from '../common'; +import { editHint, isContentManaged } from '../contentManaged'; import { ADMIN_PAGE_SIZES } from '../../../queries/admin'; interface QuestionsTableProps { @@ -122,11 +123,7 @@ export const QuestionsTable = ({ {question.slug} - {question.source === 'content' && ( - - - - )} + {isContentManaged(question) && } @@ -138,31 +135,35 @@ export const QuestionsTable = ({ onTogglePublished(question)} /> - - onEdit(question)} - disabled={question.source === 'content'} - sx={actionButtonSx} - > - - + + + onEdit(question)} + disabled={isContentManaged(question)} + sx={actionButtonSx} + > + + + - - onDelete(question)} - disabled={question.source === 'content'} - sx={{ ...actionButtonSx, '&:hover': { color: c.danger, backgroundColor: c.dangerSoft } }} - > - - + + + onDelete(question)} + disabled={isContentManaged(question)} + sx={{ ...actionButtonSx, '&:hover': { color: c.danger, backgroundColor: c.dangerSoft } }} + > + + + diff --git a/frontend/src/components/Admin/RoadmapItems/ItemsManager.tsx b/frontend/src/components/Admin/RoadmapItems/ItemsManager.tsx index 8c65732..a112eb2 100644 --- a/frontend/src/components/Admin/RoadmapItems/ItemsManager.tsx +++ b/frontend/src/components/Admin/RoadmapItems/ItemsManager.tsx @@ -32,7 +32,8 @@ import type { RoadmapItem, RoadmapItemCreate, RoadmapListResponse, RoadmapRespon import type { Category, Question } from '../../../types'; import { plural } from '../../../utils/difficulty'; import { CategoryChip, ConfirmDialog, EmptyState } from '../../ui'; -import { SectionHeader } from '../common'; +import { ContentManagedNotice, SectionHeader } from '../common'; +import { editHint, isContentManaged } from '../contentManaged'; import { ItemDialog } from './ItemDialog'; const COLUMNS = 5; @@ -79,6 +80,8 @@ interface ItemsManagerProps { } export const ItemsManager = ({ roadmap, onBack }: ItemsManagerProps) => { + // Шаги роадмапа из content/ правятся в YAML: API ответит 409 на любую правку. + const locked = isContentManaged(roadmap); const [roadmapDetail, setRoadmapDetail] = useState(null); const [items, setItems] = useState([]); const [categories, setCategories] = useState([]); @@ -297,7 +300,7 @@ export const ItemsManager = ({ roadmap, onBack }: ItemsManagerProps) => { title="Шагов пока нет" description="Добавьте первый шаг и выберите для него вопросы." action={ - } @@ -314,7 +317,7 @@ export const ItemsManager = ({ roadmap, onBack }: ItemsManagerProps) => { handleMoveItem(item.id, 'up')} - disabled={isMoving || index === 0} + disabled={locked || isMoving || index === 0} aria-label="Переместить выше" > @@ -331,7 +334,7 @@ export const ItemsManager = ({ roadmap, onBack }: ItemsManagerProps) => { handleMoveItem(item.id, 'down')} - disabled={isMoving || index === sortedItems.length - 1} + disabled={locked || isMoving || index === sortedItems.length - 1} aria-label="Переместить ниже" > @@ -371,18 +374,18 @@ export const ItemsManager = ({ roadmap, onBack }: ItemsManagerProps) => { - + - handleOpenDialog(item)} disabled={isMoving} aria-label="Редактировать"> + handleOpenDialog(item)} disabled={locked || isMoving} aria-label="Редактировать"> - + setDeleteTarget(item)} - disabled={isMoving} + disabled={locked || isMoving} aria-label="Удалить" sx={{ '&:hover': { color: 'error.main' } }} > @@ -410,12 +413,14 @@ export const ItemsManager = ({ roadmap, onBack }: ItemsManagerProps) => { : `${roadmap.profession} · ${sortedItems.length} ${plural(sortedItems.length, ['шаг', 'шага', 'шагов'])}` } action={ - } /> + {locked && } + {error && !openDialog && ( setError(null)}> {error} diff --git a/frontend/src/components/Admin/Roadmaps/index.tsx b/frontend/src/components/Admin/Roadmaps/index.tsx index 95c0f56..a3186b6 100644 --- a/frontend/src/components/Admin/Roadmaps/index.tsx +++ b/frontend/src/components/Admin/Roadmaps/index.tsx @@ -30,7 +30,8 @@ import type { RoadmapListResponse } from '../../../services/roadmapService'; import { fonts } from '../../../theme/tokens'; import { plural } from '../../../utils/difficulty'; import { ConfirmDialog, EmptyState } from '../../ui'; -import { SectionHeader, StatusChip } from '../common'; +import { ContentSourceChip, SectionHeader, StatusChip } from '../common'; +import { editHint, isContentManaged } from '../contentManaged'; import { RoadmapDialog, type RoadmapFormData } from './RoadmapDialog'; const COLUMNS = 7; @@ -231,9 +232,12 @@ export const AdminRoadmaps = () => { return roadmaps.map((roadmap) => ( - - {roadmap.title} - + + + {roadmap.title} + + {isContentManaged(roadmap) && } + {roadmap.description && ( {roadmap.description.length > 200 ? `${roadmap.description.substring(0, 200)}…` : roadmap.description} @@ -256,13 +260,14 @@ export const AdminRoadmaps = () => { - + {updatingIds.has(roadmap.id) ? ( ) : ( handleToggleActive(roadmap)} slotProps={{ input: { 'aria-label': `Статус роадмапа ${roadmap.title}` } }} /> @@ -279,15 +284,24 @@ export const AdminRoadmaps = () => { - - handleOpenDialog(roadmap)} aria-label="Редактировать"> - - + + + handleOpenDialog(roadmap)} disabled={isContentManaged(roadmap)} aria-label="Редактировать"> + + + - - setDeleteTarget(roadmap)} aria-label="Удалить" sx={{ '&:hover': { color: 'error.main' } }}> - - + + + setDeleteTarget(roadmap)} + disabled={isContentManaged(roadmap)} + aria-label="Удалить" + sx={{ '&:hover': { color: 'error.main' } }} + > + + + diff --git a/frontend/src/components/Admin/common.tsx b/frontend/src/components/Admin/common.tsx index 47ee40a..34994cb 100644 --- a/frontend/src/components/Admin/common.tsx +++ b/frontend/src/components/Admin/common.tsx @@ -1,7 +1,8 @@ import type { ReactNode } from 'react'; -import { Box, Chip, Stack, Typography } from '@mui/material'; +import { Alert, Box, Chip, Stack, Tooltip, Typography } from '@mui/material'; import { alpha } from '@mui/material/styles'; import { useTokens } from '../../theme/tokens'; +import { CONTENT_MANAGED_HINT } from './contentManaged'; interface SectionHeaderProps { title: string; @@ -51,3 +52,18 @@ export const StatusChip = ({ active, activeLabel, inactiveLabel }: StatusChipPro /> ); }; + + +export const ContentSourceChip = () => ( + + + +); + +/** Плашка над списком, целиком управляемым content/ (например, шаги роадмапа). */ +export const ContentManagedNotice = ({ file }: { file: string }) => ( + + Управляется каталогом content/ — меняйте файл {file} в репозитории. Изменения применятся при + следующем деплое. + +); diff --git a/frontend/src/components/Admin/contentManaged.ts b/frontend/src/components/Admin/contentManaged.ts new file mode 100644 index 0000000..c13db45 --- /dev/null +++ b/frontend/src/components/Admin/contentManaged.ts @@ -0,0 +1,9 @@ +import type { ContentSource } from '../../types'; + +/** Запись импортирована из content/: API отвечает 409 на правку и удаление. */ +export const isContentManaged = (item?: { source?: ContentSource } | null) => item?.source === 'content'; + +export const CONTENT_MANAGED_HINT = 'Запись управляется каталогом content/: правьте YAML в репозитории'; + +/** Подсказка для отключённых кнопок правки у записей из content/. */ +export const editHint = (managed: boolean, title: string) => (managed ? CONTENT_MANAGED_HINT : title); diff --git a/frontend/src/services/roadmapService.ts b/frontend/src/services/roadmapService.ts index 1a86792..9113d12 100644 --- a/frontend/src/services/roadmapService.ts +++ b/frontend/src/services/roadmapService.ts @@ -1,4 +1,5 @@ import api from './api'; +import type { ContentSource } from '../types'; export interface RoadmapItem { id: string; @@ -9,6 +10,7 @@ export interface RoadmapItem { title?: string | null; created_at: string; updated_at: string; + source?: ContentSource; // Новые поля для вопроса question?: { id: string; @@ -33,6 +35,7 @@ export interface RoadmapListResponse { questions_count?: number; created_at: string; updated_at: string; + source?: ContentSource; } export interface RoadmapResponse extends RoadmapListResponse { diff --git a/frontend/src/types/api.generated.ts b/frontend/src/types/api.generated.ts index 8edde6a..28d52bb 100644 --- a/frontend/src/types/api.generated.ts +++ b/frontend/src/types/api.generated.ts @@ -2353,6 +2353,12 @@ export interface components { * Format: uuid */ roadmap_id: string; + /** + * Source + * @description content — запись из content/ (read-only в админке) + * @default admin + */ + source: string; /** Title */ title?: string | null; /** @@ -2391,6 +2397,12 @@ export interface components { questions_count?: number | null; /** Slug */ slug: string; + /** + * Source + * @description content — запись из content/ (read-only в админке) + * @default admin + */ + source: string; /** Steps Count */ steps_count?: number | null; /** Title */ diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index e240ddf..f5871f5 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -30,6 +30,9 @@ export interface UserUpdate { } // Question types +/** content — запись импортирована из каталога content/ и в админке только для чтения. */ +export type ContentSource = 'content' | 'admin'; + export interface Question { id: string; title: string; @@ -44,7 +47,7 @@ export interface Question { company_id?: string | null; // ID первой компании (для старых клиентов) companies?: QuestionCompany[]; user_id?: string | null; // кто создал (только аудит) - source?: 'content' | 'admin'; // content — запись из content/ (read-only) + source?: ContentSource; answers?: Answer[]; // Ответы на вопрос exclude_inactive_categories?: boolean, is_completed?: boolean; @@ -112,6 +115,7 @@ export interface Answer { created_at?: string; updated_at?: string; is_published?: boolean; + source?: ContentSource; } export interface AnswerCreate { @@ -131,6 +135,7 @@ export interface Category { description?: string; is_active: boolean; question_count: number; + source?: ContentSource; } export interface CategoryCreate { @@ -164,6 +169,7 @@ export interface Company { updated_at: string; questions_count?: number; completed_questions_count?: number; + source?: ContentSource; } export interface CompanyCreate { diff --git a/tests/test_content_import.py b/tests/test_content_import.py index 039c4e0..25a7db1 100644 --- a/tests/test_content_import.py +++ b/tests/test_content_import.py @@ -349,6 +349,27 @@ async def test_api_blocks_changes_to_content_category_company_roadmap_answer( ).status_code == 409 +async def test_admin_lists_expose_content_source_for_read_only_ui( + engine, admin_client, session, catalog +): + """Админка отключает правку по полю source: оно нужно во всех списках, которые она читает.""" + await apply_content(catalog) + api = "/api/v1" + cats = (await admin_client.get(f"{api}/questions/categories/?include_inactive=true")).json() + assert {c["source"] for c in cats["items"]} == {"content"} + companies = (await admin_client.get(f"{api}/companies/")).json() + assert {c["source"] for c in companies["items"]} == {"content"} + roadmaps = (await admin_client.get(f"{api}/roadmaps/")).json() + assert [r["source"] for r in roadmaps] == ["content"] + detail = (await admin_client.get(f"{api}/roadmaps/python")).json() + assert detail["source"] == "content" + assert {i["source"] for i in detail["roadmap_items"]} == {"content"} + ans = await session.scalar(select(Answer)) + answers = (await admin_client.get(f"{api}/questions/{ans.question_id}/answers/")).json() + items = answers["items"] if isinstance(answers, dict) else answers + assert {a["source"] for a in items} == {"content"} + + async def test_admin_created_records_stay_editable_and_expose_source(admin_client): r = await admin_client.post( "/api/v1/questions/categories/", json={"name": "Ручная", "slug": "manual"} From 8a58382b7b87a601c922c211d536c8385b08a679 Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 15:30:28 +0100 Subject: [PATCH 2/2] interview: AI sets the grade, peeking at the reference fails the question; Bit hosts the interview MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Grade comes from the AI score (8-10 passed, 5-7 partial, 0-4 failed); self-assessment only as a fallback when AI is off, out of quota or the check failed - "Подсмотреть эталон" before grading asks once, then marks the question failed and locks the AI check; after grading the reference opens freely - Side panel with the possible grades and how to answer; progress dots colored by grade - Bit as the on-page interviewer (BitHost/BitAvatar): announces questions, reacts to reviews, dictation and silence; background reactions to favorites and mastery --- .../components/interview/AnswerPanel.test.tsx | 107 +++++++++++ .../src/components/interview/AnswerPanel.tsx | 177 +++++++++++------ .../src/components/interview/GradeScale.tsx | 101 ++++++++++ .../components/interview/InterviewResults.tsx | 6 +- .../src/components/interview/bitInterview.ts | 84 ++++++++ .../src/components/interview/session.test.ts | 7 + frontend/src/components/interview/session.ts | 11 +- frontend/src/components/ui/BitAvatar.tsx | 181 ++++++++++++++++++ frontend/src/components/ui/BitHost.tsx | 52 +++++ .../src/components/ui/PracticeMascot.test.tsx | 12 +- frontend/src/components/ui/PracticeMascot.tsx | 82 +++----- frontend/src/components/ui/bitReactions.ts | 70 +++++++ frontend/src/components/ui/bitSenses.test.tsx | 109 +++++++++++ frontend/src/components/ui/bitSenses.ts | 137 +++++++++++++ frontend/src/components/ui/bitVoice.ts | 145 +++++++++++++- frontend/src/pages/FavoritesPage.tsx | 17 ++ .../src/pages/HomePage/CategoriesSection.tsx | 31 +-- frontend/src/pages/InterviewModePage.test.tsx | 23 ++- frontend/src/pages/InterviewModePage.tsx | 133 +++++++++---- .../src/pages/QuestionDetailPage/hooks.ts | 5 + .../src/pages/QuestionDetailPage/index.tsx | 9 +- .../src/pages/RoadmapsPage/bitRoadmap.test.ts | 35 ++++ frontend/src/pages/RoadmapsPage/bitRoadmap.ts | 58 ++++++ frontend/src/pages/RoadmapsPage/index.tsx | 25 ++- frontend/src/queries/progress.ts | 17 +- 25 files changed, 1444 insertions(+), 190 deletions(-) create mode 100644 frontend/src/components/interview/AnswerPanel.test.tsx create mode 100644 frontend/src/components/interview/GradeScale.tsx create mode 100644 frontend/src/components/interview/bitInterview.ts create mode 100644 frontend/src/components/ui/BitAvatar.tsx create mode 100644 frontend/src/components/ui/BitHost.tsx create mode 100644 frontend/src/components/ui/bitReactions.ts create mode 100644 frontend/src/components/ui/bitSenses.test.tsx create mode 100644 frontend/src/components/ui/bitSenses.ts create mode 100644 frontend/src/pages/RoadmapsPage/bitRoadmap.test.ts create mode 100644 frontend/src/pages/RoadmapsPage/bitRoadmap.ts diff --git a/frontend/src/components/interview/AnswerPanel.test.tsx b/frontend/src/components/interview/AnswerPanel.test.tsx new file mode 100644 index 0000000..64c4b52 --- /dev/null +++ b/frontend/src/components/interview/AnswerPanel.test.tsx @@ -0,0 +1,107 @@ +import { useState } from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { ThemeProvider as MuiThemeProvider } from '@mui/material'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ThemeProvider } from '../../context/ThemeContext'; +import { darkTheme } from '../../theme/muiTheme'; +import type { AIReview, AIReviewStatus } from '../../types'; +import { AnswerPanel } from './AnswerPanel'; +import { GradeScale } from './GradeScale'; +import type { QuestionResult } from './session'; + +const setMastery = vi.fn(); +const reviewMutate = vi.fn(); +let reviewState = { isPending: false, isError: false, error: null as unknown }; + +vi.mock('../../queries/progress', () => ({ useSetMastery: () => ({ mutate: setMastery }) })); +vi.mock('../../queries/interview', () => ({ + useAIReview: () => ({ mutate: reviewMutate, ...reviewState }), + aiReviewErrorMessage: () => 'ИИ недоступен', +})); + +const aiOn: AIReviewStatus = { enabled: true, daily_limit: 30, used_today: 0 } as AIReviewStatus; + +/** Панель вместе со шкалой, как на странице: результат живёт в состоянии, как в сессии. */ +const Harness = ({ ai, initial }: { ai: AIReviewStatus | undefined; initial?: QuestionResult }) => { + const [result, setResult] = useState(initial); + return ( + <> + setResult((r) => ({ answer: '', ...r, ...patch }))} + ai={ai} + aiPending={false} + answerBlocks={[{ type: 'text', data: { text: 'ЭТАЛОН' } } as never]} + answersLoading={false} + answersFailed={false} + /> + + + ); +}; + +const renderPanel = (ai: AIReviewStatus | undefined, initial?: QuestionResult) => + render( + + + + + , + ); + +describe('AnswerPanel grading', () => { + beforeEach(() => { + setMastery.mockReset(); + reviewMutate.mockReset(); + reviewState = { isPending: false, isError: false, error: null }; + }); + + it('hides self-assessment while AI grades, and sets the level from the AI score', () => { + reviewMutate.mockImplementation((_vars, { onSuccess }) => onSuccess({ score: 6, summary: 'ok', strengths: [], gaps: [], mistakes: [] } as unknown as AIReview)); + renderPanel(aiOn); + expect(screen.queryByRole('group', { name: 'Своя оценка ответа' })).not.toBeInTheDocument(); + expect(screen.getByText('Оценку поставит ИИ, когда сдадите ответ.')).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('Ваш ответ'), { target: { value: 'мой ответ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Сдать ответ' })); + + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'partial' }); + expect(screen.getByText('Оценка ИИ: 6/10')).toBeInTheDocument(); + expect(screen.queryByRole('group', { name: 'Своя оценка ответа' })).not.toBeInTheDocument(); + }); + + it('peeking at the reference before grading counts as failed and locks the AI check', () => { + renderPanel(aiOn, { answer: 'черновик' }); + fireEvent.click(screen.getByRole('button', { name: 'Подсмотреть эталон' })); + // сначала спрашиваем: случайный клик не должен стоить вопроса + expect(setMastery).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Подсмотреть' })); + + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'failed' }); + expect(screen.getByText('ЭТАЛОН')).toBeInTheDocument(); + expect(screen.getByText('Подсмотрен эталон')).toBeInTheDocument(); + // диалог ещё закрывается и прячет страницу от a11y-дерева + expect(screen.getByRole('button', { name: 'Сдать ответ', hidden: true })).toBeDisabled(); + expect(screen.queryByRole('group', { name: 'Своя оценка ответа', hidden: true })).not.toBeInTheDocument(); + }); + + it('opens the reference freely once the answer is graded', () => { + renderPanel(aiOn, { answer: 'x', self: 'knew', review: { score: 9, summary: '', strengths: [], gaps: [], mistakes: [] } as unknown as AIReview }); + fireEvent.click(screen.getByRole('button', { name: 'Показать эталон' })); + expect(screen.getByText('ЭТАЛОН')).toBeInTheDocument(); + expect(setMastery).not.toHaveBeenCalled(); + }); + + it('falls back to self-assessment when AI is off or failed', () => { + const { unmount } = renderPanel({ ...aiOn, enabled: false }); + expect(screen.getByRole('group', { name: 'Своя оценка ответа' })).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /Частично/ })); + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'partial' }); + unmount(); + + reviewState = { isPending: false, isError: true, error: new Error('x') }; + renderPanel(aiOn, { answer: 'x' }); + expect(screen.getByText(/ИИ не смог проверить ответ/)).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/components/interview/AnswerPanel.tsx b/frontend/src/components/interview/AnswerPanel.tsx index ada6be8..4263b8c 100644 --- a/frontend/src/components/interview/AnswerPanel.tsx +++ b/frontend/src/components/interview/AnswerPanel.tsx @@ -16,6 +16,7 @@ import { AutoAwesomeOutlined as AIIcon, ExpandLess as ExpandLessIcon, ExpandMore as ExpandMoreIcon, + FlagOutlined as FlagIcon, MicNoneOutlined as MicIcon, StopCircleOutlined as StopIcon, VisibilityOffOutlined as VisibilityOffIcon, @@ -23,21 +24,20 @@ import { } from '@mui/icons-material'; import { ContentRenderer } from '../ContentRenderer'; import { aiReviewErrorMessage, useAIReview } from '../../queries/interview'; -import { useProgress, useSetMastery } from '../../queries/progress'; +import { useSetMastery } from '../../queries/progress'; +import { ConfirmDialog } from '../ui/ConfirmDialog'; import { MasteryIcon } from '../ui/Mastery'; import { MASTERY_LABEL, levelFromScore, useMasteryColor } from '../ui/masteryLevels'; import { radius, useTokens } from '../../theme/tokens'; -import type { AIReview, AIReviewStatus, ContentBlock, MasteryLevel } from '../../types'; +import type { AIReview, AIReviewStatus, ContentBlock } from '../../types'; import { ScoreBadge } from './ScoreBadge'; import { scoreLabel } from './score'; -import type { QuestionResult, SelfMark } from './session'; +import { LEVEL_TO_SELF, SELF_TO_LEVEL, type QuestionResult, type SelfMark } from './session'; import { appendDictation, useSpeechRecognition } from './useSpeechRecognition'; +import { bitSay, holdBitMood } from '../ui/bitVoice'; +import { DICTATION_LINE, REVIEW_FAILED, revealLine, reviewLine, selfLine } from './bitInterview'; const ANSWER_MAX = 5000; - -/** Самооценка в сессии хранится по-старому (knew/partial/missed), в прогрессе — как степень знания. */ -const SELF_TO_LEVEL: Record = { knew: 'passed', partial: 'partial', missed: 'failed' }; -const LEVEL_TO_SELF: Record = { passed: 'knew', partial: 'partial', failed: 'missed' }; const SELF_MARKS: SelfMark[] = ['knew', 'partial', 'missed']; const ReviewList = ({ title, items, color }: { title: string; items: string[]; color: string }) => @@ -124,23 +124,30 @@ interface AnswerPanelProps { result: QuestionResult | undefined; onChange: (patch: Partial) => void; ai: AIReviewStatus | undefined; + /** Статус ИИ ещё грузится: не показываем ручную оценку раньше времени. */ + aiPending: boolean; answerBlocks: ContentBlock[] | undefined; answersLoading: boolean; answersFailed: boolean; } -/** Ответ кандидата, ИИ-проверка, эталон и самооценка для одного вопроса. */ -export const AnswerPanel = ({ questionId, result, onChange, ai, answerBlocks, answersLoading, answersFailed }: AnswerPanelProps) => { +/** + * Ответ кандидата, ИИ-проверка и эталон для одного вопроса. + * Уровень ставит ИИ по оценке; сам кандидат оценивает себя, только когда ИИ недоступен или не ответил. + * Эталон, открытый до оценки, засчитывает вопрос как «Не прошёл». + */ +export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answerBlocks, answersLoading, answersFailed }: AnswerPanelProps) => { const { c } = useTokens(); const masteryColor = useMasteryColor(); const [showReference, setShowReference] = useState(false); - const [suggested, setSuggested] = useState(false); + const [confirmReveal, setConfirmReveal] = useState(false); const review = useAIReview(); - const progress = useProgress(); const setMastery = useSetMastery(); const answer = result?.answer ?? ''; - const savedLevel = progress.levelOf(questionId); const remaining = ai ? Math.max(0, ai.daily_limit - ai.used_today) : 0; + const revealed = Boolean(result?.revealed); + const graded = Boolean(result?.review || result?.self); + const aiUsable = Boolean(ai?.enabled) && remaining > 0; // Надиктованное дописывается к актуальному тексту, а не к тому, что был на момент нажатия const answerRef = useRef(answer); @@ -157,11 +164,33 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, answerBlocks, an ); const speech = useSpeechRecognition(onDictated); - const canCheck = Boolean(ai?.enabled) && remaining > 0 && answer.trim().length > 0 && answer.length <= ANSWER_MAX && !review.isPending; + // Бит слушает диктовку и «думает», пока ИИ проверяет ответ + useEffect(() => { + if (!speech.listening) return; + bitSay(DICTATION_LINE.text, DICTATION_LINE.tone); + return holdBitMood('listening'); + }, [speech.listening]); + useEffect(() => (review.isPending ? holdBitMood('thinking') : undefined), [review.isPending]); + + const canCheck = aiUsable && !revealed && answer.trim().length > 0 && answer.length <= ANSWER_MAX && !review.isPending; - const chooseSelf = (value: SelfMark | null, fromAI = false) => { + /** Ручная оценка — запасной путь: ИИ выключен, лимит кончился или проверка упала. */ + const manualReason = revealed || result?.review || (aiPending && !ai) + ? null + : review.isError + ? 'ИИ не смог проверить ответ' + : !ai?.enabled + ? 'ИИ-проверка сейчас недоступна' + : remaining === 0 + ? 'Лимит ИИ-проверок на сегодня исчерпан' + : null; + + const chooseSelf = (value: SelfMark | null) => { + if (value) { + const line = selfLine(value); + bitSay(line.text, line.tone); + } onChange({ self: value ?? undefined }); - setSuggested(fromAI); setMastery.mutate({ id: questionId, level: value ? SELF_TO_LEVEL[value] : null }); }; @@ -172,14 +201,29 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, answerBlocks, an { questionId, answer: text }, { onSuccess: (data) => { - onChange({ review: data, reviewedAnswer: text }); - // Уровень по оценке ИИ ставится, только пока пользователь не выбрал его сам - if (!result?.self || suggested) chooseSelf(LEVEL_TO_SELF[levelFromScore(data.score)], true); + const line = reviewLine(data.score); + bitSay(line.text, line.tone); + const level = levelFromScore(data.score); + onChange({ review: data, reviewedAnswer: text, self: LEVEL_TO_SELF[level] }); + setMastery.mutate({ id: questionId, level }); }, + onError: () => bitSay(REVIEW_FAILED.text, REVIEW_FAILED.tone), }, ); }; + /** После оценки эталон — разбор ошибок; до неё — подсказка, и вопрос не засчитывается. */ + const reveal = () => { + setConfirmReveal(false); + if (speech.listening) speech.stop(); + setShowReference(true); + onChange({ revealed: true, self: 'missed' }); + setMastery.mutate({ id: questionId, level: 'failed' }); + const line = revealLine(); + bitSay(line.text, line.tone, { move: 'shake' }); + }; + const referenceFree = graded || revealed; + return ( : } sx={{ bgcolor: c.accent, color: c.onAccent, '&:hover': { bgcolor: c.accentHover } }} > - {review.isPending ? 'ИИ проверяет…' : result?.review ? 'Проверить ещё раз' : 'Проверить с ИИ'} + {review.isPending ? 'ИИ проверяет…' : result?.review ? 'Проверить ещё раз' : 'Сдать ответ'} )} : } aria-pressed={speech.listening} sx={{ width: { xs: '100%', sm: 'auto' } }} @@ -250,20 +294,28 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, answerBlocks, an {ai?.enabled && ( - {remaining > 0 ? `ИИ-проверок сегодня: осталось ${remaining} из ${ai.daily_limit}` : 'Лимит ИИ-проверок на сегодня исчерпан'} + {remaining > 0 ? `Проверок сегодня: ${remaining} из ${ai.daily_limit}` : 'Лимит ИИ-проверок на сегодня исчерпан'} )} + {revealed && !result?.review && ( + } sx={{ mt: 2 }}> + Эталон открыт до ответа — вопрос засчитан как «Не прошёл». Прочитайте и вернитесь к нему после итогов. + + )} {review.isError && ( {aiReviewErrorMessage(review.error)} @@ -294,41 +346,46 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, answerBlocks, an )} - - - Уровень знания: - - chooseSelf(value)} - aria-label="Уровень знания вопроса" - > - {SELF_MARKS.map((mark) => { - const level = SELF_TO_LEVEL[mark]; - return ( - - - {MASTERY_LABEL[level]} - - ); - })} - - - - {result?.self && suggested - ? 'Уровень предложен по оценке ИИ и сохранён в прогрессе. Можно изменить.' - : result?.self - ? 'Сохранено в прогрессе.' - : savedLevel - ? `Сейчас в прогрессе: ${MASTERY_LABEL[savedLevel].toLowerCase()}.` - : '«Прошёл» — ответили полностью, «Частично» — суть верна, но есть пробелы.'} - + {manualReason && ( + + + {manualReason}. Оцените ответ сами — честно, как оценил бы интервьюер: + + chooseSelf(value)} + aria-label="Своя оценка ответа" + sx={{ flexWrap: 'wrap' }} + > + {SELF_MARKS.map((mark) => { + const level = SELF_TO_LEVEL[mark]; + return ( + + + {MASTERY_LABEL[level]} + + ); + })} + + + )} + + setConfirmReveal(false)} + /> ); }; diff --git a/frontend/src/components/interview/GradeScale.tsx b/frontend/src/components/interview/GradeScale.tsx new file mode 100644 index 0000000..dcb2993 --- /dev/null +++ b/frontend/src/components/interview/GradeScale.tsx @@ -0,0 +1,101 @@ +import { Box, Stack, Typography } from '@mui/material'; +import { MasteryIcon } from '../ui/Mastery'; +import { MASTERY_LABEL, MASTERY_LEVELS, useMasteryColor } from '../ui/masteryLevels'; +import { radius, useTokens } from '../../theme/tokens'; +import type { MasteryLevel } from '../../types'; +import { SELF_TO_LEVEL, type QuestionResult } from './session'; + +/** Что стоит за каждым уровнем: диапазон оценки ИИ и как его заработать. */ +const SCALE: Record = { + passed: { range: '8–10', hint: 'Полный ответ: суть, как устроено, пример' }, + partial: { range: '5–7', hint: 'Суть верна, но интервьюер копнул бы глубже' }, + failed: { range: '0–4', hint: 'Ошибки, пустой ответ или подсмотренный эталон' }, +}; + +const HOW_TO = ['Суть в одной фразе', 'Как это устроено', 'Пример из практики', 'Подводные камни']; + +const sourceOf = (result: QuestionResult | undefined) => + result?.review + ? `Оценка ИИ: ${result.review.score}/10` + : result?.revealed + ? 'Подсмотрен эталон' + : result?.self + ? 'Своя оценка' + : null; + +/** + * Шкала собеседования сбоку от вопроса: какие уровни можно получить и за что. + * Полученный уровень подсвечивается, но выставляет его ИИ, а не кандидат. + */ +export const GradeScale = ({ result, aiAvailable }: { result: QuestionResult | undefined; aiAvailable: boolean }) => { + const { c } = useTokens(); + const color = useMasteryColor(); + const current = result?.self ? SELF_TO_LEVEL[result.self] : null; + const source = sourceOf(result); + + return ( + + + + Что можно получить + + + {MASTERY_LEVELS.map((level) => { + const active = current === level; + const { fg, bg } = color(level); + return ( + + + + + {MASTERY_LABEL[level]} + {SCALE[level].range} + + {SCALE[level].hint} + + + ); + })} + + + {source ?? (aiAvailable ? 'Оценку поставит ИИ, когда сдадите ответ.' : 'ИИ недоступен — оцените ответ сами под полем ответа.')} + + + + + + Как отвечать + + + {HOW_TO.map((step) => ( + + {step} + + ))} + + + Эталон до сдачи ответа — сразу «Не прошёл». + + + + ); +}; diff --git a/frontend/src/components/interview/InterviewResults.tsx b/frontend/src/components/interview/InterviewResults.tsx index 2a4ee6b..a24af2a 100644 --- a/frontend/src/components/interview/InterviewResults.tsx +++ b/frontend/src/components/interview/InterviewResults.tsx @@ -100,7 +100,11 @@ export const InterviewResults = ({ session, questions, completed, onRetry, onNew {label.text} - {result?.self && !result.review ? ` · уровень: ${SELF_LABEL[result.self]}` : ''} + {result?.revealed && !result.review + ? ' · подсмотрен эталон' + : result?.self && !result.review + ? ` · своя оценка: ${SELF_LABEL[result.self]}` + : ''} {result?.review && } diff --git a/frontend/src/components/interview/bitInterview.ts b/frontend/src/components/interview/bitInterview.ts new file mode 100644 index 0000000..1ef7e18 --- /dev/null +++ b/frontend/src/components/interview/bitInterview.ts @@ -0,0 +1,84 @@ +import { pickLine } from '../ui/bitVoice'; +import type { BitTone } from '../ui/bitVoice'; +import { plural } from '../../utils/difficulty'; +import type { Question } from '../../types'; +import type { InterviewSession, SelfMark } from './session'; +import { STRONG_SCORE } from './session'; + +/** Реплики Бита-интервьюера. */ + +type Line = { text: string; tone: BitTone }; +const Q: [string, string, string] = ['вопрос', 'вопроса', 'вопросов']; + +export const INTERVIEW_ROLE = 'Бит · интервьюер'; + +export const SETUP_LINE = 'Сегодня я интервьюер. Выбери, сколько вопросов и какой сложности, — и начнём.'; + +export const startLine = (count: number): Line => ({ + tone: 'cheer', + text: `Начинаем! ${count} ${plural(count, Q)}. Отвечай так, будто я сижу напротив.`, +}); + +const BY_DIFFICULTY: Record = { + easy: { tone: 'calm', lines: ['Разминочный. Ответь коротко и по делу.', 'Простой — значит, проверяют базу. Не торопись.'] }, + medium: { tone: 'focus', lines: ['Классика собеседований. Сначала определение, потом пример.', 'Такой спрашивают часто. Расскажи, как это устроено внутри.'] }, + hard: { tone: 'fire', lines: ['Со звёздочкой. Проговори идею, детали подтянутся.', 'Сложный. Если не уверен — рассуждай вслух, это тоже засчитывается.'] }, +}; + +export const questionLine = (index: number, total: number, question: Question, revisit: boolean): Line => { + const head = `Вопрос ${index + 1} из ${total}.`; + if (revisit) return { tone: 'calm', text: `${head} Возвращаемся — можно дополнить ответ.` }; + if (total > 1 && index === total - 1) return { tone: 'fire', text: `${head} Последний! Финишная прямая.` }; + const { tone, lines } = BY_DIFFICULTY[question.difficulty] ?? BY_DIFFICULTY.medium; + return { tone, text: `${head} ${pickLine(`iq:${question.difficulty}`, lines)}` }; +}; + +export const SILENCE_LINES = [ + 'Тишина в эфире… Начни с того, что точно знаешь.', + 'Застрял? Назови, для чего это нужно, — дальше пойдёт легче.', + 'Можно надиктовать ответ: жми «Надиктовать», я послушаю.', +]; + +export const selfLine = (mark: SelfMark): Line => + mark === 'knew' + ? { tone: 'cheer', text: pickLine('self:knew', ['Чётко! Записываю в сильные стороны.', 'Уверенный ответ. Следующий!']) } + : mark === 'partial' + ? { tone: 'focus', text: pickLine('self:partial', ['Наполовину — уже хорошо. Глянь эталон и добей пробел.', 'Записал «частично». После собеседования вернёмся.']) } + : { tone: 'calm', text: pickLine('self:missed', ['Не страшно, на собеседовании такое бывает. Отмечу на повтор.', 'Честно — это плюс. Разберём после итогов.']) }; + +export const reviewLine = (score: number): Line => + score >= 9 + ? { tone: 'cheer', text: `${score}/10! Я бы тебя нанял.` } + : score >= STRONG_SCORE + ? { tone: 'cheer', text: `${score}/10 — хороший ответ. Глянь, что ИИ советует добавить.` } + : score >= 5 + ? { tone: 'focus', text: `${score}/10. База есть, но интервьюер копнул бы глубже — смотри «Чего не хватает».` } + : { tone: 'fire', text: `${score}/10. Не расстраивайся: открой эталон и попробуй ещё раз своими словами.` }; + +export const REVIEW_FAILED: Line = { tone: 'calm', text: 'ИИ не ответил. Оцени себя сам — это тоже считается.' }; + +/** Эталон открыт до ответа: вопрос не засчитан. */ +export const revealLine = (): Line => ({ + tone: 'calm', + text: pickLine('reveal', [ + 'Подсмотрел — значит, «не прошёл». Зато теперь запомнишь: прочитай и перескажи своими словами.', + 'Засчитываю как «не прошёл». На настоящем собеседовании шпаргалки не будет — разберём после итогов.', + ]), +}); +export const DICTATION_LINE: Line = { tone: 'focus', text: 'Слушаю! Говори как на настоящем собеседовании.' }; + +export const resultsLine = (session: InterviewSession): Line => { + const results = session.ids.map((id) => session.results[id]); + const answered = results.filter((r) => r?.answer?.trim() || r?.self).length; + const strong = results.filter((r) => r?.self === 'knew' || (r?.review && r.review.score >= STRONG_SCORE)).length; + const total = session.ids.length; + if (!answered) return { tone: 'calm', text: 'Ни одного ответа — ничего, такое собеседование тоже чему-то учит. Попробуем ещё раз?' }; + if (strong === total) return { tone: 'cheer', text: `Все ${total} — уверенно. Оффер почти в кармане!` }; + if (strong * 2 >= total) return { tone: 'cheer', text: `Уверенно на ${strong} из ${total}. Добей остальные — и можно на реальное собеседование.` }; + return { tone: 'focus', text: `Ответов: ${answered} из ${total}, уверенно — ${strong}. Ниже список, что повторить.` }; +}; + +export const markedLine = (count: number): Line => ({ + tone: 'cheer', + text: `Отметил ${count} ${plural(count, Q)} как пройденные. Прогресс растёт!`, +}); diff --git a/frontend/src/components/interview/session.test.ts b/frontend/src/components/interview/session.test.ts index f2ede90..0f2ef90 100644 --- a/frontend/src/components/interview/session.test.ts +++ b/frontend/src/components/interview/session.test.ts @@ -35,4 +35,11 @@ describe('interview session', () => { expect(sum.strongIds).toEqual(['a']); expect(sum.weakIds).toEqual(['b', 'c', 'd']); }); + + it('counts a question as failed when the reference was revealed before grading', () => { + expect(outcomeOf({ answer: 'x', revealed: true, self: 'missed' })).toBe('weak'); + expect(outcomeOf({ answer: '', revealed: true })).toBe('weak'); + // эталон после оценки ИИ — разбор ошибок, оценка остаётся + expect(outcomeOf({ answer: 'x', review: review(9), revealed: true })).toBe('strong'); + }); }); diff --git a/frontend/src/components/interview/session.ts b/frontend/src/components/interview/session.ts index 7b85df2..5e8abf1 100644 --- a/frontend/src/components/interview/session.ts +++ b/frontend/src/components/interview/session.ts @@ -1,14 +1,20 @@ -import type { AIReview, Question } from '../../types'; +import type { AIReview, MasteryLevel, Question } from '../../types'; -/** Самооценка, когда ИИ не используется (или в дополнение к нему). */ +/** Уровень по вопросу: ставит ИИ, сам кандидат — только если ИИ недоступен. */ export type SelfMark = 'knew' | 'partial' | 'missed'; +/** В сессии уровень хранится по-старому (knew/partial/missed), в прогрессе — как степень знания. */ +export const SELF_TO_LEVEL: Record = { knew: 'passed', partial: 'partial', missed: 'failed' }; +export const LEVEL_TO_SELF: Record = { passed: 'knew', partial: 'partial', failed: 'missed' }; + export interface QuestionResult { answer: string; review?: AIReview; /** Текст, который проверял ИИ: если ответ потом правили, оценка относится к старой версии. */ reviewedAnswer?: string; self?: SelfMark; + /** Эталон открыт до оценки: вопрос засчитан как «Не прошёл», проверка ИИ закрыта. */ + revealed?: boolean; } export interface InterviewOptions { @@ -92,6 +98,7 @@ export type Outcome = 'strong' | 'ok' | 'weak' | 'skipped'; /** Итог по вопросу: оценка ИИ важнее самооценки. */ export const outcomeOf = (result: QuestionResult | undefined): Outcome => { + if (result?.revealed && !result.review) return 'weak'; if (result?.review) { if (result.review.score >= STRONG_SCORE) return 'strong'; return result.review.score >= WEAK_SCORE ? 'ok' : 'weak'; diff --git a/frontend/src/components/ui/BitAvatar.tsx b/frontend/src/components/ui/BitAvatar.tsx new file mode 100644 index 0000000..071d4ca --- /dev/null +++ b/frontend/src/components/ui/BitAvatar.tsx @@ -0,0 +1,181 @@ +import { Box } from '@mui/material'; +import bit from '../../assets/mascot/bit.webp'; +import { useBitPose } from './bitVoice'; +import type { BitMood, BitMove } from './bitVoice'; + +const MOTION = '@media (prefers-reduced-motion: no-preference)'; + +/** Разовые движения: длительность и число повторов. */ +const MOVES: Record = { + hop: 'bit-hop .55s cubic-bezier(.3,.7,.4,1) 2', + shake: 'bit-shake .45s ease-in-out 2', + nod: 'bit-nod .45s ease-in-out 2', + tilt: 'bit-tilt 1.1s ease-in-out 1', + spin: 'bit-spin 1.1s cubic-bezier(.5,0,.3,1) 1', + glanceL: 'bit-glance-l .5s ease-out 1', + glanceR: 'bit-glance-r .5s ease-out 1', + perk: 'bit-perk .35s ease-out 1', + wake: 'bit-wake .9s ease-out 1', +}; + +/** Длительные состояния. */ +const MOODS: Record = { + idle: 'bit-greeting 10s ease-in-out infinite', + listening: 'bit-listen .8s ease-in-out infinite alternate', + thinking: 'bit-think 1.6s ease-in-out infinite', + sleeping: 'bit-breathe 3.2s ease-in-out infinite', +}; + +const keyframes = { + '@keyframes bit-greeting': { + '0%, 19%, 100%': { transform: 'none' }, + '5%': { transform: 'translateX(-1px) rotate(-5deg)' }, + '7%': { transform: 'translateX(1px) rotate(4deg)' }, + '12%': { transform: 'translateY(2px) scaleY(.92) rotate(-2deg)' }, + '16%': { transform: 'translateY(-1px) rotate(2deg)' }, + }, + // кивает в такт печати + '@keyframes bit-listen': { + from: { transform: 'rotate(-2deg)' }, + to: { transform: 'translateY(1.5px) rotate(3deg) scaleY(.97)' }, + }, + // покачивается, «прокручивая» мысль + '@keyframes bit-think': { + '0%, 100%': { transform: 'rotate(0)' }, + '25%': { transform: 'rotate(-7deg) translateX(-1px)' }, + '75%': { transform: 'rotate(7deg) translateX(1px)' }, + }, + '@keyframes bit-breathe': { + '0%, 100%': { transform: 'translateY(1px) scale(1, .95)' }, + '50%': { transform: 'translateY(0) scale(1, 1)' }, + }, + '@keyframes bit-hop': { + '0%, 100%': { transform: 'none' }, + '20%': { transform: 'translateY(2px) scale(1.06, .88)' }, + '50%': { transform: 'translateY(-8px) scale(.95, 1.06)' }, + '80%': { transform: 'translateY(1px) scale(1.04, .94)' }, + }, + '@keyframes bit-shake': { + '0%, 100%': { transform: 'none' }, + '20%': { transform: 'translateX(-3px) rotate(-6deg)' }, + '40%': { transform: 'translateX(3px) rotate(6deg)' }, + '60%': { transform: 'translateX(-2px) rotate(-3deg)' }, + '80%': { transform: 'translateX(2px) rotate(3deg)' }, + }, + '@keyframes bit-nod': { + '0%, 100%': { transform: 'none' }, + '45%': { transform: 'translateY(3px) scaleY(.92) rotate(2deg)' }, + }, + '@keyframes bit-tilt': { + '0%, 100%': { transform: 'none' }, + '30%, 70%': { transform: 'rotate(-11deg) translateX(-1px)' }, + }, + '@keyframes bit-spin': { + '0%': { transform: 'none' }, + '60%': { transform: 'rotate(380deg) scale(.9)' }, + '75%': { transform: 'rotate(350deg)' }, + '88%': { transform: 'rotate(366deg)' }, + '100%': { transform: 'rotate(360deg)' }, + }, + '@keyframes bit-glance-l': { + '0%, 100%': { transform: 'none' }, + '35%, 70%': { transform: 'translateX(-1px) rotate(-8deg)' }, + }, + '@keyframes bit-glance-r': { + '0%, 100%': { transform: 'none' }, + '35%, 70%': { transform: 'translateX(1px) rotate(8deg)' }, + }, + '@keyframes bit-perk': { + '0%, 100%': { transform: 'none' }, + '50%': { transform: 'translateY(-4px) scaleY(1.04)' }, + }, + '@keyframes bit-wake': { + '0%': { transform: 'scale(1, .9)' }, + '35%': { transform: 'translateY(-5px) scale(.94, 1.12)' }, + '60%': { transform: 'translateY(0) rotate(-6deg)' }, + '80%': { transform: 'rotate(5deg)' }, + '100%': { transform: 'none' }, + }, + '@keyframes bit-wink': { + '0%, 8%, 15%, 100%': { opacity: 0 }, + '9%, 13%': { opacity: 1 }, + }, + '@keyframes bit-blink': { + '0%, 92%, 100%': { opacity: 0 }, + '94%, 97%': { opacity: 1 }, + }, + '@keyframes bit-zzz': { + '0%': { opacity: 0, transform: 'translate(0, 4px) scale(.7)' }, + '30%': { opacity: 1 }, + '100%': { opacity: 0, transform: 'translate(6px, -10px) scale(1.1)' }, + }, +}; + +/** Закрытый глаз: тёмная заплатка с полоской поверх нарисованного глаза. */ +const Lid = ({ left, animation, shown }: { left: string; animation?: string; shown: boolean }) => ( + +); + +interface BitAvatarProps { + /** Высота аватара; ширина считается по пропорциям картинки. */ + height?: number | Record; +} + +/** + * Бит, который двигается: разовые движения (по репликам и кликам) поверх длительного состояния. + * Два вложенных слоя, чтобы прыжок не сбрасывал покачивание «слушаю» и наоборот. + */ +export const BitAvatar = ({ height = { xs: 37, md: 42 } }: BitAvatarProps) => { + const { move, moveId, mood } = useBitPose(); + const asleep = mood === 'sleeping'; + return ( + + + + {/* подмигивает в покое, моргает, пока слушает, закрывает оба глаза во сне */} + + + + {asleep && ( + + z + + )} + + ); +}; diff --git a/frontend/src/components/ui/BitHost.tsx b/frontend/src/components/ui/BitHost.tsx new file mode 100644 index 0000000..674a253 --- /dev/null +++ b/frontend/src/components/ui/BitHost.tsx @@ -0,0 +1,52 @@ +import { useEffect, useState } from 'react'; +import { Box, Typography } from '@mui/material'; +import { radius, useTokens } from '../../theme/tokens'; +import { BitAvatar } from './BitAvatar'; +import { registerBitHost, useBitPose, useBitVoice } from './bitVoice'; +import type { BitTone } from './bitVoice'; + +interface BitHostProps { + /** Подпись над репликой: роль Бита на этой странице. */ + role: string; + /** Что Бит говорит, пока ничего не сказал сам. */ + fallback: string; +} + +/** + * Бит-ведущий прямо на странице (например, интервьюер в собеседовании). Пока он на экране, + * реплики Бита идут сюда, а облачко в шапке молчит. Аватар двигается синхронно с шапкой. + */ +export const BitHost = ({ role, fallback }: BitHostProps) => { + const { c } = useTokens(); + const voice = useBitVoice(); + const { mood } = useBitPose(); + // сказанное до появления ведущего не повторяем + const [seenId] = useState(() => voice?.id ?? 0); + useEffect(() => registerBitHost(), []); + + const line = voice && voice.id > seenId ? voice : null; + const toneColor: Record = { calm: c.accent, cheer: c.success, fire: c.danger, focus: c.warning }; + const color = line ? toneColor[line.tone] : c.accent; + const status = mood === 'thinking' ? 'думает' : mood === 'listening' ? 'слушает' : mood === 'sleeping' ? 'задремал' : null; + + return ( + + + + + {role} + {status && · {status}…} + + + {line?.text ?? fallback} + + + + ); +}; diff --git a/frontend/src/components/ui/PracticeMascot.test.tsx b/frontend/src/components/ui/PracticeMascot.test.tsx index 16a7882..6a1eecd 100644 --- a/frontend/src/components/ui/PracticeMascot.test.tsx +++ b/frontend/src/components/ui/PracticeMascot.test.tsx @@ -17,7 +17,7 @@ beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); -const renderMascot = () => +const renderMascot = (extra?: React.ReactNode) => render( @@ -25,6 +25,7 @@ const renderMascot = () => + {extra} @@ -45,4 +46,13 @@ describe('PracticeMascot speech', () => { fireEvent.click(bubble); expect(screen.getByRole('status')).toHaveTextContent(''); }); + + it('keeps a line said in reply to the click that happened outside the bubble', async () => { + renderMascot(); + act(() => bitSay('старая реплика')); + await screen.findByText('старая реплика', { selector: 'p' }); + await act(async () => new Promise((r) => setTimeout(r, 450))); + fireEvent.click(screen.getByRole('button', { name: 'Отметить' })); + expect(screen.getByRole('status')).toHaveTextContent('Бит: Шаг закрыт!'); + }); }); diff --git a/frontend/src/components/ui/PracticeMascot.tsx b/frontend/src/components/ui/PracticeMascot.tsx index 1f25f52..474d768 100644 --- a/frontend/src/components/ui/PracticeMascot.tsx +++ b/frontend/src/components/ui/PracticeMascot.tsx @@ -1,12 +1,13 @@ -import { useEffect, useId, useState } from 'react'; +import { type MutableRefObject, useEffect, useId, useRef, useState } from 'react'; import { Box, Button, ClickAwayListener, Dialog, DialogContent, DialogTitle, Grow, IconButton, Popper, Stack, Typography } from '@mui/material'; import { ArrowForward, Close, Loop } from '@mui/icons-material'; import { Link as RouterLink, useLocation } from 'react-router-dom'; import { useAuth } from '../../context/auth-context'; import { useTokens } from '../../theme/tokens'; -import bit from '../../assets/mascot/bit.webp'; -import { useBitVoice } from './bitVoice'; +import { bitMove, useBitHosted, useBitPose, useBitVoice } from './bitVoice'; import type { BitTone } from './bitVoice'; +import { BitAvatar } from './BitAvatar'; +import { useBitSenses } from './bitSenses'; type TipSet = [string, string]; @@ -56,6 +57,9 @@ function getSection(pathname: string) { return 'home'; } +/** Реплика моложе этого — ответ на текущий клик, «клик мимо» её не закрывает. */ +const CLICK_REPLY_MS = 400; + const comments = [ 'Компилирую улыбку', 'Нашёл баг в кофе', @@ -63,49 +67,7 @@ const comments = [ 'Код сам себя не прочтёт', ]; -const BitAvatar = ({ talking = false }: { talking?: boolean }) => ( - - - - -); - -const MascotPanel = ({ pathname }: { pathname: string }) => { +const MascotPanel = ({ pathname, selfRef }: { pathname: string; selfRef: MutableRefObject }) => { const titleId = useId(); const { isAuthenticated } = useAuth(); const { c, shadow } = useTokens(); @@ -119,7 +81,11 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { const [hiddenId, setHiddenId] = useState(0); const [anchor, setAnchor] = useState(null); const [arrow, setArrow] = useState(null); - const said = voice && voice.id > seenId && voice.id > hiddenId && !open ? voice : null; + // Когда на странице есть ведущий (BitHost), реплики показывает он, а не облачко в шапке. + const hosted = useBitHosted(); + const { mood } = useBitPose(); + const fresh = voice && voice.id > seenId && voice.id > hiddenId ? voice : null; + const said = fresh && !open && !hosted ? fresh : null; useEffect(() => { if (!voice) return; const timer = window.setTimeout(() => setHiddenId(voice.id), 6500); @@ -134,7 +100,7 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { return () => window.clearInterval(timer); }, []); - const comment = comments[commentIndex]; + const comment = mood === 'sleeping' ? 'Сплю… тапни, если что' : mood === 'thinking' ? 'Думаю…' : mood === 'listening' ? 'Слушаю…' : comments[commentIndex]; const keepPracticing = section === 'questions' || section === 'roadmap' || section === 'interview'; const to = section === 'account' ? '/' : isAuthenticated ? '/questions' : '/register'; const action = section === 'account' ? 'К демовопросу' : isAuthenticated ? 'К вопросам' : 'Начать подготовку'; @@ -142,7 +108,11 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { return ( <> @@ -182,7 +152,8 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { {({ TransitionProps }) => ( - voice && setHiddenId(voice.id)}> + {/* клик мимо закрывает облачко, но не реплику, которую Бит сказал в ответ на этот же клик */} + voice && Date.now() - voice.at > CLICK_REPLY_MS && setHiddenId(voice.id)}> voice && setHiddenId(voice.id)} sx={{ @@ -232,7 +203,7 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { }} > - + Бит setOpen(false)} sx={{ ml: 'auto' }}> @@ -269,5 +240,8 @@ const MascotPanel = ({ pathname }: { pathname: string }) => { export const PracticeMascot = () => { const { pathname } = useLocation(); - return ; + // «Чувства» живут вне панели: панель пересоздаётся на каждой странице, а сон и счётчик кликов — нет. + const selfRef = useRef(null); + useBitSenses(selfRef); + return ; }; diff --git a/frontend/src/components/ui/bitReactions.ts b/frontend/src/components/ui/bitReactions.ts new file mode 100644 index 0000000..2ac5d70 --- /dev/null +++ b/frontend/src/components/ui/bitReactions.ts @@ -0,0 +1,70 @@ +import type { MasteryLevel } from '../../types'; +import { bitSay, pickLine } from './bitVoice'; + +/** + * Фоновые реакции Бита на действия, которые случаются на разных страницах (избранное, отметки). + * Приоритет 0: если страница уже сказала что-то своё, Бит её не перебивает. + */ + +const quiet = { priority: 0 } as const; + +export const reactFavorite = (on: boolean) => + on + ? bitSay(pickLine('fav:on', [ + 'Сохранил! Вернёмся к нему, когда будет минутка.', + 'В избранное! Положил на самую видную полку.', + 'Запомнил. Через пару дней спрошу ещё раз.', + ]), 'cheer', quiet) + : bitSay(pickLine('fav:off', [ + 'Убрал из избранного. Значит, уже не страшен?', + 'Окей, вычеркнул. Полка стала легче.', + ]), 'calm', quiet); + +export const reactMastery = (level: MasteryLevel | null) => { + if (level === 'passed') { + return bitSay(pickLine('m:passed', [ + 'Засчитано! Ещё один вопрос в копилку.', + 'Бип-бип, зелёная лампочка! Так держать.', + 'Чисто. Через неделю проверим, не остыло ли.', + ]), 'cheer', quiet); + } + if (level === 'partial') { + return bitSay(pickLine('m:partial', [ + 'Почти! Добей пробел, пока тема свежая.', + 'Половина пути. Перечитай кусок, где споткнулся.', + ]), 'focus', quiet); + } + if (level === 'failed') { + return bitSay(pickLine('m:failed', [ + 'Честно — значит полезно. Вернёмся к нему позже.', + 'Не беда, на собеседовании лучше уже не будет сюрпризом.', + ]), 'calm', { ...quiet, move: 'nod' }); + } + return bitSay('Снял отметку. Начнём с чистого листа.', 'calm', quiet); +}; + +// ---- «чувства»: реакции на стиль взаимодействия ---- + +export const DIZZY_LINES = [ + 'Ого, сколько кликов! У меня аж байты закружились.', + 'Полегче, я не кликер-игра!', + 'Тыц-тыц-тыц… Что-то ищешь? Могу подсказать.', +]; + +export const WAKE_LINES = [ + 'А? Я не спал, я кэшировал! Продолжим?', + 'О, ты тут! Я чуть не ушёл в спящий режим.', + 'Проснулся. Давай один вопрос — и снова в поток.', +]; + +export const RETURN_LINES = [ + 'С возвращением! Где мы остановились?', + 'Ты вернулся! Я держал место.', +]; + +export const greetingLine = (hour: number) => { + if (hour < 5) return 'Ночная смена? Уважаю. Только не забудь поспать.'; + if (hour < 12) return 'Доброе утро! Свежая голова — лучшее время для сложных вопросов.'; + if (hour < 18) return 'Привет! Один вопрос сейчас лучше десяти «потом».'; + return 'Добрый вечер! Пара вопросов перед сном отлично закрепляется.'; +}; diff --git a/frontend/src/components/ui/bitSenses.test.tsx b/frontend/src/components/ui/bitSenses.test.tsx new file mode 100644 index 0000000..18f2a6c --- /dev/null +++ b/frontend/src/components/ui/bitSenses.test.tsx @@ -0,0 +1,109 @@ +import { useRef } from 'react'; +import { act, fireEvent, render, renderHook } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { bitSay, holdBitMood, resetBitForTests, useBitPose, useBitVoice } from './bitVoice'; +import { SLEEP_AFTER_MS, useBitSenses } from './bitSenses'; + +const Senses = () => { + const ref = useRef(null); + useBitSenses(ref); + return ( + <> + bit + +