From d2429f8f1c190245d5765e3b6fceaf09646824c9 Mon Sep 17 00:00:00 2001 From: Grisha Lavrov Date: Fri, 4 Dec 2026 17:44:38 +0100 Subject: [PATCH] =?UTF-8?q?interview:=20constructor=20with=5Ftext=20?= =?UTF-8?q?=E2=80=94=20assemble=20the=20algorithm=20and=20explain=20it=20i?= =?UTF-8?q?n=20words,=20final=20score=20is=20the=20average?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - content: build.mode: with_text + text_prompt (what to explain in words), loader and validator check the pair - AI review: the prompt tells the model the algorithm is graded separately and to grade only the written part; the reference solution goes in as ordered steps - frontend: BuildPanel renders two parts — the builder and AnswerPanel in part mode (no own reference or mastery); final = floor((build + text) / 2), text = AI score or self-assessment; the level is set only when both are graded, one reference for the whole task, Bit announces both parts and the final - number of islands switched to with_text --- app/content/loader.py | 22 +- app/services/ai_review.py | 21 ++ app/validators.py | 6 + .../algorithms/algo-number-of-islands.yaml | 2 + docs/content.md | 14 ++ frontend/src/components/ContentRenderer.tsx | 8 + .../src/components/interview/AnswerPanel.tsx | 58 ++++-- .../src/components/interview/GradeScale.tsx | 51 ++++- .../components/interview/InterviewResults.tsx | 4 +- .../src/components/interview/bitInterview.ts | 21 +- .../interview/constructor/BuildPanel.test.tsx | 99 ++++++++- .../interview/constructor/BuildPanel.tsx | 192 +++++++++++++++--- .../interview/constructor/sequence.test.ts | 6 +- .../interview/constructor/sequence.ts | 15 +- .../src/components/interview/session.test.ts | 14 +- frontend/src/components/interview/session.ts | 25 ++- frontend/src/pages/InterviewModePage.tsx | 9 +- frontend/src/types/index.ts | 16 +- tests/test_ai_review.py | 32 +++ tests/test_content_constructor.py | 30 +++ 20 files changed, 559 insertions(+), 86 deletions(-) diff --git a/app/content/loader.py b/app/content/loader.py index 21b2d08..c49bf37 100644 --- a/app/content/loader.py +++ b/app/content/loader.py @@ -164,14 +164,18 @@ class BuildTask(Strict): """ kind: Literal["sequence"] = "sequence" - # replace — конструктор вместо текстового ответа - mode: Literal["replace"] = "replace" + # replace — конструктор вместо текстового ответа; with_text — рядом с ним + mode: Literal["replace", "with_text"] = "replace" prompt: str = Field(min_length=5, max_length=300) + # with_text: что кандидат объясняет словами (ИИ оценивает только эту часть) + text_prompt: str | None = Field(None, min_length=5, max_length=300) steps: list[BuildStep] = Field(min_length=3, max_length=12) distractors: list[str] = Field(default_factory=list, max_length=4) @model_validator(mode="after") def check_steps(self) -> BuildTask: + if (self.mode == "with_text") != (self.text_prompt is not None): + raise ValueError("text_prompt нужен для mode: with_text и только для него") if self.steps[0].indent != 0: raise ValueError("первый шаг конструктора должен быть без отступа") for prev, cur in zip(self.steps, self.steps[1:], strict=False): @@ -198,15 +202,11 @@ def question_block(self, slug: str) -> dict[str, Any]: step_ids = [p["id"] for p in pieces[: len(self.steps)]] if [p["id"] for p in shuffled if p["id"] in step_ids] == step_ids: shuffled.reverse() # перемешивание не должно случайно совпасть с ответом - return { - "type": "constructor", - "data": { - "kind": self.kind, - "mode": self.mode, - "prompt": self.prompt.strip(), - "pieces": shuffled, - }, - } + data: dict[str, Any] = {"kind": self.kind, "mode": self.mode, "prompt": self.prompt.strip()} + if self.text_prompt: + data["text_prompt"] = self.text_prompt.strip() + data["pieces"] = shuffled + return {"type": "constructor", "data": data} def answer_block(self, slug: str) -> dict[str, Any]: """Эталон: шаги в правильном порядке с вложенностью.""" diff --git a/app/services/ai_review.py b/app/services/ai_review.py index bd972f2..d08baf7 100644 --- a/app/services/ai_review.py +++ b/app/services/ai_review.py @@ -148,9 +148,30 @@ def blocks_to_text(blocks: list[dict[str, Any]] | None, limit: int) -> str: parts.append(f"```{data.get('language') or ''}\n{code}\n```") elif kind in ("diagram", "image") and data.get("caption"): parts.append(f"[{kind}] {data['caption']}") + elif kind == "constructor": + parts.append(_constructor_text(data)) return "\n\n".join(p.strip() for p in parts if p.strip())[:limit] +def _constructor_text(data: dict[str, Any]) -> str: + """Задание-конструктор в промпте: алгоритм кандидат собирает из блоков, его балл считается без ИИ. + + В вопросе — что объяснить словами, в эталоне — правильный порядок шагов как ориентир. + """ + if data.get("solution"): + steps = "\n".join( + f"{i}. {' ' * int(s.get('indent') or 0)}{s.get('text', '')}" + for i, s in enumerate(data["solution"], 1) + ) + return f"Reference algorithm steps (graded separately):\n{steps}" + if data.get("mode") == "with_text" and data.get("text_prompt"): + return ( + "[The candidate assembles the algorithm from blocks; that part is graded separately " + "without you. Grade ONLY the written answer to this task:] " + str(data["text_prompt"]) + ) + return "" + + def build_payload( ai: AIConfig, *, diff --git a/app/validators.py b/app/validators.py index 6999add..8e39e6a 100644 --- a/app/validators.py +++ b/app/validators.py @@ -53,12 +53,18 @@ def validate_content_structure(contents: list[dict[str, Any]]) -> list[dict[str, CONSTRUCTOR_KINDS = ("sequence",) +CONSTRUCTOR_MODES = ("replace", "with_text") def _validate_constructor(data: Any) -> None: """Блок конструктора: в вопросе — перемешанные куски (pieces), в ответе — эталон (solution).""" if not isinstance(data, dict) or data.get("kind") not in CONSTRUCTOR_KINDS: raise ValueError(f"Constructor-блок: data.kind должен быть одним из {CONSTRUCTOR_KINDS}") + mode = data.get("mode", "replace") + if mode not in CONSTRUCTOR_MODES: + raise ValueError(f"Constructor-блок: data.mode должен быть одним из {CONSTRUCTOR_MODES}") + if mode == "with_text" and not str(data.get("text_prompt", "")).strip(): + raise ValueError("Constructor-блок with_text должен содержать data.text_prompt") items = data.get("pieces") if "pieces" in data else data.get("solution") if not isinstance(items, list) or not items: raise ValueError("Constructor-блок должен содержать непустой data.pieces или data.solution") diff --git a/content/questions/algorithms/algo-number-of-islands.yaml b/content/questions/algorithms/algo-number-of-islands.yaml index 1ff86a0..42aedd4 100644 --- a/content/questions/algorithms/algo-number-of-islands.yaml +++ b/content/questions/algorithms/algo-number-of-islands.yaml @@ -93,7 +93,9 @@ answer: - info: 'Уточняющие вопросы интервьюера: можно ли менять входную матрицу; как посчитать площадь наибольшего острова (обход возвращает размер); как быть, если суша добавляется по одной клетке и после каждой нужен ответ (Union-Find, вариант «острова II»); как подсчитать различные по форме острова (нормализовать координаты относительно стартовой клетки и сложить формы во множество).' build: kind: sequence + mode: with_text prompt: 'Соберите итеративный обход сетки из блоков: расставьте шаги по порядку и задайте вложенность. Лишние блоки оставьте в стороне.' + text_prompt: 'Объясните словами: почему клетку помечают водой при добавлении в стек, а не при снятии, и какая у обхода сложность по времени и памяти.' steps: - text: 'Скопировать сетку и завести счётчик островов = 0' - text: 'Для каждой клетки (r, c) сетки' diff --git a/docs/content.md b/docs/content.md index 28e7792..a0aa8c7 100644 --- a/docs/content.md +++ b/docs/content.md @@ -131,6 +131,20 @@ build: - 'Отсортировать символы строки' ``` +С `mode: with_text` конструктор стоит рядом с текстовым ответом: нужен `text_prompt` — что кандидат +объясняет словами (например, почему шаги именно такие и какая сложность). Сборку оценивает эталон, +объяснение — ИИ (или самооценка, если ИИ недоступен), итог — среднее двух баллов с округлением вниз. +ИИ видит только `text_prompt` и оценивает только объяснение; эталонный порядок шагов идёт ему как ориентир. + +```yaml +build: + kind: sequence + mode: with_text + prompt: 'Соберите обход сетки из блоков' + text_prompt: 'Объясните, почему клетку помечают при добавлении в стек, и какая сложность обхода' + steps: [...] +``` + Тексты шагов и отвлекающих блоков не повторяются, каждый шаг — одно действие до 200 символов. Балл считает браузер: 10 × (наибольшая общая подпоследовательность с эталоном) / число шагов, минус 1 за неверную вложенность и минус 2 за каждый взятый отвлекающий блок. Вопрос с `build` должен быть diff --git a/frontend/src/components/ContentRenderer.tsx b/frontend/src/components/ContentRenderer.tsx index 247d307..ac62da6 100644 --- a/frontend/src/components/ContentRenderer.tsx +++ b/frontend/src/components/ContentRenderer.tsx @@ -141,6 +141,14 @@ const ConstructorBlockView = ({ block }: { block: ContentBlock }) => { ))} + {block.data?.text_prompt && ( + + + Словами:{' '} + + {block.data.text_prompt} + + )} Собрать решение из этих блоков можно в режиме собеседования: порядок и вложенность проверятся автоматически. diff --git a/frontend/src/components/interview/AnswerPanel.tsx b/frontend/src/components/interview/AnswerPanel.tsx index 1fc4491..6bcfaab 100644 --- a/frontend/src/components/interview/AnswerPanel.tsx +++ b/frontend/src/components/interview/AnswerPanel.tsx @@ -163,6 +163,14 @@ interface AnswerPanelProps { answerBlocks: ContentBlock[] | undefined; answersLoading: boolean; answersFailed: boolean; + /** + * Текстовая часть задания-конструктора: уровень и эталон ведёт родитель, + * панель не трогает прогресс и не показывает свой эталон. + */ + part?: boolean; + /** Подпись и подсказка поля ответа. */ + label?: string; + placeholder?: string; } /** @@ -170,7 +178,19 @@ interface AnswerPanelProps { * Уровень ставит ИИ по оценке; сам кандидат оценивает себя, только когда ИИ недоступен или не ответил. * Эталон, открытый до оценки, засчитывает вопрос как «Не прошёл». */ -export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answerBlocks, answersLoading, answersFailed }: AnswerPanelProps) => { +export const AnswerPanel = ({ + questionId, + result, + onChange, + ai, + aiPending, + answerBlocks, + answersLoading, + answersFailed, + part = false, + label = 'Ваш ответ', + placeholder = 'Ответьте так, как ответили бы интервьюеру: суть, как это устроено, пример, подводные камни', +}: AnswerPanelProps) => { const { c } = useTokens(); const masteryColor = useMasteryColor(); const [showReference, setShowReference] = useState(false); @@ -225,7 +245,7 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe bitSay(line.text, line.tone); } onChange({ self: value ?? undefined }); - setMastery.mutate({ id: questionId, level: value ? SELF_TO_LEVEL[value] : null }); + if (!part) setMastery.mutate({ id: questionId, level: value ? SELF_TO_LEVEL[value] : null }); }; const runCheck = () => { @@ -239,7 +259,7 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe 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 }); + if (!part) setMastery.mutate({ id: questionId, level }); }, onError: () => bitSay(REVIEW_FAILED.text, REVIEW_FAILED.tone), }, @@ -261,8 +281,8 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe return ( - + {!part && ( + + )} {ai?.enabled && ( {remaining > 0 ? `Проверок сегодня: ${remaining} из ${ai.daily_limit}` : 'Лимит ИИ-проверок на сегодня исчерпан'} @@ -345,7 +367,7 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe )} - {revealed && !result?.review && } + {revealed && !result?.review && !part && } {review.isError && ( {aiReviewErrorMessage(review.error)} @@ -353,7 +375,7 @@ export const AnswerPanel = ({ questionId, result, onChange, ai, aiPending, answe )} {result?.review && } - {showReference && } + {showReference && !part && } {manualReason && ( diff --git a/frontend/src/components/interview/GradeScale.tsx b/frontend/src/components/interview/GradeScale.tsx index 8887d84..4596222 100644 --- a/frontend/src/components/interview/GradeScale.tsx +++ b/frontend/src/components/interview/GradeScale.tsx @@ -2,8 +2,8 @@ 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'; +import type { ConstructorMode, MasteryLevel } from '../../types'; +import { SELF_TO_LEVEL, type QuestionResult, scoreOf, textScoreOf } from './session'; /** Что стоит за каждым уровнем: диапазон оценки ИИ и как его заработать. */ const SCALE: Record = { @@ -14,8 +14,22 @@ const SCALE: Record = { const HOW_TO = ['Суть в одной фразе', 'Как это устроено', 'Пример из практики', 'Подводные камни']; +/** Откуда уровень: для сборки с текстом — итог и обе части. */ +const withTextSource = (result: QuestionResult) => { + const final = scoreOf(result); + const build = result.build?.score; + const text = textScoreOf(result); + if (result.revealed && final === undefined) return 'Подсмотрен эталон'; + if (final !== undefined) return `Итог: ${final}/10 (сборка ${build}, объяснение ${text})`; + if (build !== undefined) return `Сборка: ${build}/10, объяснение ещё не оценено`; + if (text !== undefined) return `Объяснение: ${text}/10, сборка не сдана`; + return null; +}; + const sourceOf = (result: QuestionResult | undefined) => - result?.review + result?.withText + ? withTextSource(result) + : result?.review ? `Оценка ИИ: ${result.review.score}/10` : result?.build?.score !== undefined ? `Сборка: ${result.build.score}/10` @@ -34,11 +48,30 @@ const BUILD_SCALE: Record = { const BUILD_HOW_TO = ['Что нужно до цикла', 'Заголовок цикла или условия', 'Тело — с отступом вправо', 'Лишние блоки не брать']; +/** Сборка с текстом: уровень по среднему двух частей. */ +const WITH_TEXT_SCALE: Record = { + passed: 'В среднем 8+: и сборка, и объяснение сильные', + partial: 'В среднем 5–7: одна из частей хромает', + failed: 'Обе части слабые или подсмотренный эталон', +}; + +const WITH_TEXT_HOW_TO = ['Собрать алгоритм из блоков', 'Сдать сборку', 'Объяснить словами, что спрошено', 'Итог — среднее двух баллов']; + /** * Шкала собеседования сбоку от вопроса: какие уровни можно получить и за что. * Полученный уровень подсвечивается, но выставляет его ИИ, а не кандидат. */ -export const GradeScale = ({ result, aiAvailable, build = false }: { result: QuestionResult | undefined; aiAvailable: boolean; build?: boolean }) => { +export const GradeScale = ({ + result, + aiAvailable, + build = false, +}: { + result: QuestionResult | undefined; + aiAvailable: boolean; + /** Задание-конструктор: replace — только сборка, with_text — сборка и объяснение. */ + build?: false | ConstructorMode; +}) => { + const withText = build === 'with_text'; const { c } = useTokens(); const color = useMasteryColor(); const current = result?.self ? SELF_TO_LEVEL[result.self] : null; @@ -70,7 +103,7 @@ export const GradeScale = ({ result, aiAvailable, build = false }: { result: Que {MASTERY_LABEL[level]} {SCALE[level].range} - {build ? BUILD_SCALE[level] : SCALE[level].hint} + {withText ? WITH_TEXT_SCALE[level] : build ? BUILD_SCALE[level] : SCALE[level].hint} ); @@ -78,7 +111,9 @@ export const GradeScale = ({ result, aiAvailable, build = false }: { result: Que {source ?? - (build + (withText + ? 'Сборку оценит эталон, объяснение — ИИ; итог — среднее.' + : build ? 'Балл посчитается по эталону сразу после сдачи сборки.' : aiAvailable ? 'Оценку поставит ИИ, когда сдадите ответ.' @@ -88,10 +123,10 @@ export const GradeScale = ({ result, aiAvailable, build = false }: { result: Que - {build ? 'Как собирать' : 'Как отвечать'} + {build === 'replace' ? 'Как собирать' : 'Как отвечать'} - {(build ? BUILD_HOW_TO : HOW_TO).map((step) => ( + {(withText ? WITH_TEXT_HOW_TO : build ? BUILD_HOW_TO : HOW_TO).map((step) => ( : { tone: 'fire', text: `${score}/10. Не расстраивайся: открой эталон и попробуй ещё раз своими словами.` }; /** Вопрос-конструктор: объявляем формат вместо обычной подсказки по сложности. */ -export const buildQuestionLine = (index: number, total: number, revisit: boolean): Line => { +export const buildQuestionLine = (index: number, total: number, revisit: boolean, withText = false): Line => { const head = `Вопрос ${index + 1} из ${total}.`; if (revisit) return { tone: 'calm', text: `${head} Возвращаемся к сборке.` }; + if (withText) { + return { + tone: 'focus', + text: `${head} ${pickLine('build:text', [ + 'Две части: собери алгоритм из блоков, потом объясни словами то, что спрошено. Итог — среднее.', + 'Сначала конструктор, потом пара фраз своими словами. Оцениваю обе части.', + ])}`, + }; + } return { tone: 'focus', text: `${head} ${pickLine('build:start', [ @@ -84,6 +93,16 @@ export const buildLine = (score: number): Line => ? { tone: 'focus', text: `${score}/10. Каркас верный, но порядок или вложенность хромают — смотри пометки.` } : { tone: 'fire', text: `${score}/10. Открой эталон и пройди алгоритм по шагам, потом соберём ещё раз.` }; +/** Обе части задания с текстом оценены: итог — среднее. */ +export const combinedLine = (score: number, build: number, text: number): Line => { + const parts = `Сборка ${build}, объяснение ${text}`; + return score >= STRONG_SCORE + ? { tone: 'cheer', text: `Итог ${score}/10. ${parts} — так и отвечают на собеседовании.` } + : score >= 5 + ? { tone: 'focus', text: `Итог ${score}/10. ${parts}: подтяни слабую часть, и будет зачёт.` } + : { tone: 'fire', text: `Итог ${score}/10. ${parts}. Открой эталон и разбери обе части.` }; +}; + export const REVIEW_FAILED: Line = { tone: 'calm', text: 'ИИ не ответил. Оцени себя сам — это тоже считается.' }; /** Эталон открыт до ответа: вопрос не засчитан. */ diff --git a/frontend/src/components/interview/constructor/BuildPanel.test.tsx b/frontend/src/components/interview/constructor/BuildPanel.test.tsx index 8b2e657..a68f5cb 100644 --- a/frontend/src/components/interview/constructor/BuildPanel.test.tsx +++ b/frontend/src/components/interview/constructor/BuildPanel.test.tsx @@ -4,14 +4,19 @@ 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 { ContentBlock } from '../../../types'; +import type { AIReview, AIReviewStatus, ContentBlock } from '../../../types'; import { GradeScale } from '../GradeScale'; import type { QuestionResult } from '../session'; import { BuildPanel } from './BuildPanel'; import type { SequenceTask } from './sequence'; const setMastery = vi.fn(); +const reviewMutate = vi.fn(); vi.mock('../../../queries/progress', () => ({ useSetMastery: () => ({ mutate: setMastery }) })); +vi.mock('../../../queries/interview', () => ({ + useAIReview: () => ({ mutate: reviewMutate, isPending: false, isError: false, error: null }), + aiReviewErrorMessage: () => 'ИИ недоступен', +})); const STEPS = ['Завести стек', 'Для каждого символа', 'Положить в стек']; const task: SequenceTask = { @@ -23,7 +28,11 @@ const task: SequenceTask = { { id: 'a', text: STEPS[0] }, { id: 'b', text: STEPS[1] }, ], + mode: 'replace', }; +const withTextTask: SequenceTask = { ...task, mode: 'with_text', textPrompt: 'Объясните сложность' }; +const aiOn = { enabled: true, daily_limit: 30, used_today: 0 } as AIReviewStatus; +const aiOff = { enabled: false, daily_limit: 0, used_today: 0 } as AIReviewStatus; const answer: ContentBlock[] = [ { type: 'paragraph', data: { text: 'Суть' } }, { @@ -40,13 +49,13 @@ const answer: ContentBlock[] = [ ]; let latest: QuestionResult | undefined; -const Harness = ({ initial }: { initial?: QuestionResult }) => { +const Harness = ({ initial, t = task, ai }: { initial?: QuestionResult; t?: SequenceTask; ai?: AIReviewStatus }) => { const [result, setResult] = useState(initial); return ( <> setResult((r) => { @@ -57,17 +66,18 @@ const Harness = ({ initial }: { initial?: QuestionResult }) => { answerBlocks={answer} answersLoading={false} answersFailed={false} + ai={ai} /> - + ); }; -const renderPanel = (initial?: QuestionResult) => +const renderPanel = (initial?: QuestionResult, t?: SequenceTask, ai?: AIReviewStatus) => render( - + , ); @@ -78,6 +88,7 @@ const solutionRows = () => within(screen.getByRole('list', { name: 'Ваше р describe('BuildPanel', () => { beforeEach(() => { setMastery.mockReset(); + reviewMutate.mockReset(); latest = undefined; }); @@ -147,3 +158,79 @@ describe('BuildPanel', () => { expect(screen.getByText('Подсмотрен эталон')).toBeInTheDocument(); }); }); + +describe('BuildPanel with_text', () => { + beforeEach(() => { + setMastery.mockReset(); + reviewMutate.mockReset(); + latest = undefined; + }); + + const buildExactly = () => { + add(STEPS[0]); + add(STEPS[1]); + add(STEPS[2]); + fireEvent.keyDown(screen.getByLabelText(`3. ${STEPS[2]}`), { key: 'ArrowRight', altKey: true }); + fireEvent.click(screen.getByRole('button', { name: 'Сдать сборку' })); + }; + + it('waits for both parts, then sets the level from the average of the build and the AI score', () => { + renderPanel(undefined, withTextTask, aiOn); + expect(screen.getByText('Объясните сложность')).toBeInTheDocument(); + // один эталон на всё задание: у текстовой части своей кнопки нет + expect(screen.getAllByRole('button', { name: 'Подсмотреть эталон' })).toHaveLength(1); + + buildExactly(); + expect(latest?.build?.score).toBe(10); + expect(latest?.self).toBeUndefined(); + expect(setMastery).not.toHaveBeenCalled(); + expect(screen.getByText('Сборка: 10/10, объяснение ещё не оценено')).toBeInTheDocument(); + // без итога эталон всё ещё стоит «Не прошёл» + expect(screen.getByRole('button', { name: 'Подсмотреть эталон' })).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText('Ваше объяснение'), { target: { value: 'O(n) по времени и памяти' } }); + fireEvent.click(screen.getByRole('button', { name: 'Сдать ответ' })); + expect(reviewMutate).toHaveBeenCalledWith({ questionId: 'q1', answer: 'O(n) по времени и памяти' }, expect.anything()); + const { onSuccess } = reviewMutate.mock.calls[0][1]; + onSuccess({ score: 7, summary: 'ok', strengths: [], gaps: [], mistakes: [], improved_answer: '', follow_up: '' } as unknown as AIReview); + + // (10 + 7) / 2 = 8.5 → 8, «Прошёл»; оценка ИИ стала частью итога, а не уровнем вопроса + return waitFor(() => { + expect(latest?.self).toBe('knew'); + expect(latest?.textSelf).toBe('partial'); + expect(setMastery).toHaveBeenCalledTimes(1); + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'passed' }); + expect(screen.getByText('Итог: 8/10 (сборка 10, объяснение 7)')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Показать эталон' })).toBeInTheDocument(); + }); + }); + + it('uses the self-assessment of the text when AI is off', async () => { + renderPanel(undefined, withTextTask, aiOff); + fireEvent.click(screen.getByRole('button', { name: /Частично/ })); + expect(latest?.textSelf).toBe('partial'); + expect(latest?.self).toBeUndefined(); + expect(setMastery).not.toHaveBeenCalled(); + + buildExactly(); + // (10 + 6) / 2 = 8 + await waitFor(() => expect(latest?.self).toBe('knew')); + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'passed' }); + expect(screen.getByText(/Сборка 10\/10 · объяснение 6\/10 \(своя оценка\)/)).toBeInTheDocument(); + + // самооценку сняли — итога снова нет + fireEvent.click(screen.getByRole('button', { name: /Частично/ })); + expect(latest?.self).toBeUndefined(); + expect(setMastery).toHaveBeenLastCalledWith({ id: 'q1', level: null }); + }); + + it('peeking before both parts are graded fails the whole question', async () => { + renderPanel({ answer: '', withText: true, build: { order: [{ id: 'a', indent: 0 }], score: 9 } }, withTextTask, aiOn); + fireEvent.click(screen.getByRole('button', { name: 'Подсмотреть эталон' })); + fireEvent.click(screen.getByRole('button', { name: 'Подсмотреть' })); + expect(latest?.revealed).toBe(true); + expect(latest?.self).toBe('missed'); + expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'failed' }); + await waitFor(() => expect(screen.getByRole('button', { name: 'Сдать ответ' })).toBeDisabled()); + }); +}); diff --git a/frontend/src/components/interview/constructor/BuildPanel.tsx b/frontend/src/components/interview/constructor/BuildPanel.tsx index 6495664..4d923f7 100644 --- a/frontend/src/components/interview/constructor/BuildPanel.tsx +++ b/frontend/src/components/interview/constructor/BuildPanel.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { type ReactNode, useState } from 'react'; import { Alert, Box, Button, Stack, Typography } from '@mui/material'; import { FactCheckOutlined as SubmitIcon, @@ -11,12 +11,12 @@ import { ConfirmDialog } from '../../ui/ConfirmDialog'; import { bitSay } from '../../ui/bitVoice'; import { levelFromScore } from '../../ui/masteryLevels'; import { radius, useTokens } from '../../../theme/tokens'; -import type { ContentBlock } from '../../../types'; -import { ReferenceAnswer, RevealedAlert } from '../AnswerPanel'; -import { buildLine, revealLine } from '../bitInterview'; +import type { AIReviewStatus, ContentBlock } from '../../../types'; +import { AnswerPanel, ReferenceAnswer, RevealedAlert } from '../AnswerPanel'; +import { buildLine, combinedLine, revealLine } from '../bitInterview'; import { ScoreBadge } from '../ScoreBadge'; import { scoreLabel } from '../score'; -import { LEVEL_TO_SELF, type QuestionResult } from '../session'; +import { LEVEL_TO_SELF, type QuestionResult, scoreOf, textScoreOf } from '../session'; import { SequenceBuilder } from './SequenceBuilder'; import { findSequenceSolution, scoreSequence, type PlacedStep, type SequenceTask } from './sequence'; @@ -28,55 +28,137 @@ interface BuildPanelProps { answerBlocks: ContentBlock[] | undefined; answersLoading: boolean; answersFailed: boolean; + /** Статус ИИ-проверки: нужен текстовой части в режиме with_text. */ + ai?: AIReviewStatus; + aiPending?: boolean; } +const PartHeading = ({ n, title, children }: { n: number; title: string; children: ReactNode }) => { + const { c } = useTokens(); + return ( + + + Часть {n} · {title} + + + {children} + + + ); +}; + /** * Ответ-конструктор: кандидат собирает алгоритм из блоков, балл считается по эталону без ИИ. * Первая сдача фиксирует оценку; эталон до сдачи, как и в текстовом ответе, — «Не прошёл». + * В режиме with_text рядом со сборкой — текстовый ответ на ИИ-проверке, итог — среднее двух баллов. */ -export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, answersLoading, answersFailed }: BuildPanelProps) => { +export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, answersLoading, answersFailed, ai, aiPending = false }: BuildPanelProps) => { const { c } = useTokens(); const setMastery = useSetMastery(); const [showReference, setShowReference] = useState(false); const [confirmReveal, setConfirmReveal] = useState(false); + const withText = task.mode === 'with_text'; const build = result?.build; const order = build?.order ?? []; const submitted = build?.score !== undefined; const revealed = Boolean(result?.revealed); const solution = findSequenceSolution(answerBlocks); - const referenceFree = submitted || revealed; + const final = withText ? scoreOf({ answer: '', ...result, withText: true }) : build?.score; + // с текстом эталон без штрафа — только когда оценены обе части: иначе он подскажет объяснение + const referenceFree = final !== undefined || revealed; const canSubmit = !submitted && !revealed && order.length > 0 && Boolean(solution); - const setOrder = (next: PlacedStep[]) => onChange({ build: { order: next } }); + /** Правка результата; для with_text итоговый уровень пересчитывается, когда оценены обе части. */ + const update = (patch: Partial) => { + if (!withText) { + onChange(patch); + return; + } + const prev: QuestionResult = { answer: '', ...result, withText: true }; + const next: QuestionResult = { ...prev, ...patch }; + const before = prev.revealed ? undefined : scoreOf(prev); + const after = next.revealed ? undefined : scoreOf(next); + if (after !== undefined) { + const level = levelFromScore(after); + onChange({ withText: true, ...patch, self: LEVEL_TO_SELF[level] }); + if (after !== before) { + setMastery.mutate({ id: questionId, level }); + const line = combinedLine(after, next.build!.score!, textScoreOf(next)!); + bitSay(line.text, line.tone); + } + } else if (before !== undefined) { + // самооценку текста сняли: итога больше нет + onChange({ withText: true, ...patch, self: undefined }); + setMastery.mutate({ id: questionId, level: null }); + } else { + onChange({ withText: true, ...patch }); + } + }; + + const setOrder = (next: PlacedStep[]) => update({ build: { order: next } }); const submit = () => { if (!solution) return; const { score, marks, missing } = scoreSequence(solution, order); + const line = buildLine(score); + bitSay(line.text, line.tone); + if (withText) { + update({ build: { order, score, marks, missing } }); + return; + } const level = levelFromScore(score); onChange({ build: { order, score, marks, missing }, self: LEVEL_TO_SELF[level] }); setMastery.mutate({ id: questionId, level }); - const line = buildLine(score); - bitSay(line.text, line.tone); }; const reveal = () => { setConfirmReveal(false); setShowReference(true); - onChange({ revealed: true, self: 'missed' }); + onChange({ ...(withText ? { withText: true } : {}), revealed: true, self: 'missed' }); setMastery.mutate({ id: questionId, level: 'failed' }); const line = revealLine(); bitSay(line.text, line.tone, { move: 'shake' }); }; + /** Текстовая часть: её самооценка хранится отдельно от итогового уровня. */ + const textResult: QuestionResult = { answer: '', ...result, self: result?.textSelf }; + const onTextChange = (patch: Partial) => { + const { self, ...rest } = patch; + update('self' in patch ? { ...rest, textSelf: self } : rest); + }; + const placedCount = build?.marks?.filter((m) => m === 'ok').length ?? 0; const extraCount = build?.marks?.filter((m) => m === 'extra').length ?? 0; + const buildSummary = `На месте ${placedCount} из ${solution?.length ?? order.length}${extraCount ? ` · лишних блоков: ${extraCount}` : ''}${ + build?.missing?.length ? ` · пропущено: ${build.missing.length}` : '' + }`; + const textScore = textScoreOf(result); + + const referenceButton = ( + + ); return ( - - {task.prompt} - + {withText ? ( + + {task.prompt} + + ) : ( + + {task.prompt} + + )} )} - + {!withText && referenceButton} {!submitted && !revealed && ( Оценка — по первой сдаче, проверка без ИИ )} + {withText && submitted && build?.score !== undefined && ( + + + + {buildSummary} + + + )} {!solution && !answersLoading && ( @@ -121,9 +202,39 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a {answersFailed ? 'Не удалось загрузить эталон для проверки. Обновите страницу.' : 'У задания нет эталона — сдать сборку нельзя.'} )} - {revealed && !submitted && } - {submitted && build?.score !== undefined && ( + {withText && ( + + + {task.textPrompt} + + + + {referenceButton} + {!referenceFree && ( + + Без штрафа эталон откроется, когда оценены обе части + + )} + + + )} + + {revealed && final === undefined && } + + {!withText && submitted && build?.score !== undefined && ( {scoreLabel(build.score)} - На месте {placedCount} из {solution?.length ?? order.length} - {extraCount ? ` · лишних блоков: ${extraCount}` : ''} - {build.missing?.length ? ` · пропущено: ${build.missing.length}` : ''} + {buildSummary} + + + + + )} + + {withText && final !== undefined && !revealed && ( + + + + + Итог: {scoreLabel(final).toLowerCase()} + + Сборка {build?.score}/10 · объяснение {textScore}/10 + {result?.review ? '' : ' (своя оценка)'} · итог — среднее с округлением вниз @@ -148,7 +276,11 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a { ]; it('finds the task in the question and the solution in the answer', () => { - expect(findSequenceTask(question)).toEqual({ prompt: 'Соберите', pieces: [{ id: 'a', text: 'A' }] }); + expect(findSequenceTask(question)).toEqual({ prompt: 'Соберите', pieces: [{ id: 'a', text: 'A' }], mode: 'replace' }); + const withText: ContentBlock = { type: 'constructor', data: { ...question[1].data!, kind: 'sequence', mode: 'with_text', text_prompt: 'Объясните' } }; + expect(findSequenceTask([withText])).toMatchObject({ mode: 'with_text', textPrompt: 'Объясните' }); + const noPrompt: ContentBlock = { type: 'constructor', data: { ...question[1].data!, kind: 'sequence', mode: 'with_text' } }; + expect(findSequenceTask([noPrompt])?.mode).toBe('replace'); expect(findSequenceTask(answer)).toBeNull(); expect(findSequenceSolution(answer)).toBe(solution); expect(findSequenceSolution(undefined)).toBeNull(); diff --git a/frontend/src/components/interview/constructor/sequence.ts b/frontend/src/components/interview/constructor/sequence.ts index 8c7728f..59b61ff 100644 --- a/frontend/src/components/interview/constructor/sequence.ts +++ b/frontend/src/components/interview/constructor/sequence.ts @@ -1,9 +1,12 @@ -import type { ContentBlock, ConstructorPiece, ConstructorStep } from '../../../types'; +import type { ContentBlock, ConstructorMode, ConstructorPiece, ConstructorStep } from '../../../types'; /** Задание-конструктор вида «алгоритм из блоков» (задача Парсонса). */ export interface SequenceTask { prompt: string; pieces: ConstructorPiece[]; + mode: ConstructorMode; + /** with_text: что объяснить словами рядом со сборкой. */ + textPrompt?: string; } /** Строка собранного решения: какой кусок и на каком уровне вложенности. */ @@ -30,7 +33,15 @@ const isConstructor = (b: ContentBlock | undefined) => b?.type === 'constructor' /** Задание-конструктор в блоках вопроса, если оно есть. */ export const findSequenceTask = (blocks: ContentBlock[] | undefined): SequenceTask | null => { const block = blocks?.find((b) => isConstructor(b) && Array.isArray(b.data?.pieces) && b.data!.pieces!.length > 0); - return block ? { prompt: block.data?.prompt ?? 'Соберите решение из блоков', pieces: block.data!.pieces! } : null; + if (!block) return null; + const textPrompt = block.data?.text_prompt?.trim(); + return { + prompt: block.data?.prompt ?? 'Соберите решение из блоков', + pieces: block.data!.pieces!, + // with_text без формулировки текстовой части превращается в обычную сборку + mode: block.data?.mode === 'with_text' && textPrompt ? 'with_text' : 'replace', + ...(textPrompt ? { textPrompt } : {}), + }; }; /** Эталон сборки в блоках ответа. */ diff --git a/frontend/src/components/interview/session.test.ts b/frontend/src/components/interview/session.test.ts index 862dae7..ac19034 100644 --- a/frontend/src/components/interview/session.test.ts +++ b/frontend/src/components/interview/session.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import type { AIReview, Question } from '../../types'; -import { buildPlan, DEFAULT_OPTIONS, eligibleQuestions, newSession, outcomeOf, summarize } from './session'; +import { buildPlan, DEFAULT_OPTIONS, eligibleQuestions, newSession, outcomeOf, scoreOf, summarize } from './session'; const q = (id: string, difficulty = 'easy') => ({ id, title: id, difficulty }) as unknown as Question; const review = (score: number) => ({ score }) as AIReview; @@ -58,4 +58,16 @@ describe('interview session', () => { expect(sum.reviewed).toBe(2); expect(sum.strongIds).toEqual(['a']); }); + + it('averages the build and the text for with_text and waits for both parts', () => { + const order = [{ id: 'a', indent: 0 }]; + expect(scoreOf({ answer: 'x', withText: true, build: { order, score: 8 } })).toBeUndefined(); + expect(scoreOf({ answer: 'x', withText: true, review: review(9) })).toBeUndefined(); + expect(scoreOf({ answer: 'x', withText: true, build: { order, score: 8 }, review: review(7) })).toBe(7); + expect(scoreOf({ answer: 'x', withText: true, build: { order, score: 10 }, textSelf: 'knew' })).toBe(9); + // одна часть оценена — вопрос начат, но итога ещё нет + expect(outcomeOf({ answer: 'x', withText: true, build: { order, score: 10 } })).toBe('ok'); + expect(outcomeOf({ answer: 'x', withText: true, build: { order, score: 10 }, review: review(9) })).toBe('strong'); + expect(outcomeOf({ answer: '', withText: true, revealed: true, self: 'missed' })).toBe('weak'); + }); }); diff --git a/frontend/src/components/interview/session.ts b/frontend/src/components/interview/session.ts index d44ca2e..2237bbd 100644 --- a/frontend/src/components/interview/session.ts +++ b/frontend/src/components/interview/session.ts @@ -18,6 +18,10 @@ export interface QuestionResult { revealed?: boolean; /** Задание-конструктор: собранный порядок, после сдачи — балл и пометки строк. */ build?: BuildResult; + /** Конструктор рядом с текстом: итог — среднее балла сборки и балла ответа. */ + withText?: boolean; + /** Самооценка текстовой части, когда ИИ недоступен (в with_text `self` — итоговый уровень). */ + textSelf?: SelfMark; } export interface BuildResult { @@ -28,8 +32,25 @@ export interface BuildResult { missing?: string[]; } -/** Балл по вопросу: оценка ИИ или балл сборки конструктора. */ -export const scoreOf = (result: QuestionResult | undefined): number | undefined => result?.review?.score ?? result?.build?.score; +/** Самооценка текстовой части в баллах: середина диапазона уровня. */ +export const TEXT_SELF_SCORE: Record = { knew: 9, partial: 6, missed: 2 }; + +/** Балл текстового ответа: оценка ИИ, иначе самооценка. */ +export const textScoreOf = (result: QuestionResult | undefined): number | undefined => + result?.review?.score ?? (result?.textSelf ? TEXT_SELF_SCORE[result.textSelf] : undefined); + +/** + * Балл по вопросу: оценка ИИ или балл сборки конструктора. + * Для сборки с текстом — среднее двух частей с округлением вниз, пока обе не оценены — нет балла. + */ +export const scoreOf = (result: QuestionResult | undefined): number | undefined => { + if (result?.withText) { + const build = result.build?.score; + const text = textScoreOf(result); + return build === undefined || text === undefined ? undefined : Math.floor((build + text) / 2); + } + return result?.review?.score ?? result?.build?.score; +}; /** На вопрос ответили: есть текст, оценка или начатая сборка. */ export const isAnswered = (result: QuestionResult | undefined) => diff --git a/frontend/src/pages/InterviewModePage.tsx b/frontend/src/pages/InterviewModePage.tsx index 8a26e66..8954668 100644 --- a/frontend/src/pages/InterviewModePage.tsx +++ b/frontend/src/pages/InterviewModePage.tsx @@ -146,6 +146,8 @@ const QuestionView = ({ question, result, onChange }: QuestionViewProps) => { answerBlocks={card.data?.answers?.[0]?.content} answersLoading={card.isPending} answersFailed={card.isError} + ai={ai.data} + aiPending={ai.isPending} /> ) : ( { if (!currentQuestion) return; const revisit = isAnswered(session?.results[currentQuestion.id]); - const line = findSequenceTask(currentQuestion.content) - ? buildQuestionLine(currentIndex, plan.length, revisit) + const task = findSequenceTask(currentQuestion.content); + const line = task + ? buildQuestionLine(currentIndex, plan.length, revisit, task.mode === 'with_text') : questionLine(currentIndex, plan.length, currentQuestion, revisit); if (startedRef.current && currentIndex === 0) { bitSay(`${startLine(startedRef.current).text} ${line.text}`, 'cheer'); @@ -413,7 +416,7 @@ export const InterviewFlow = ({ - + diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index dee4806..371de12 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -235,13 +235,24 @@ export interface ConstructorStep extends ConstructorPiece { indent: number; } +/** replace — конструктор вместо текстового ответа, with_text — сборка плюс объяснение словами. */ +export type ConstructorMode = 'replace' | 'with_text'; + /** * Задание-конструктор: кандидат собирает алгоритм из блоков. * В вопросе лежат перемешанные куски (pieces), в эталонном ответе — решение (solution). */ export interface ConstructorBlock extends BlockBase { type: 'constructor'; - data?: { kind: 'sequence'; mode?: 'replace'; prompt?: string; pieces?: ConstructorPiece[]; solution?: ConstructorStep[] }; + data?: { + kind: 'sequence'; + mode?: ConstructorMode; + prompt?: string; + /** with_text: что объяснить словами — эту часть оценивает ИИ. */ + text_prompt?: string; + pieces?: ConstructorPiece[]; + solution?: ConstructorStep[]; + }; } /** Блок контента в формате API (data зависит от type; поля опциональны для совместимости). */ @@ -255,8 +266,9 @@ export interface ContentBlock { alt?: string; caption?: string; kind?: 'sequence'; - mode?: 'replace'; + mode?: ConstructorMode; prompt?: string; + text_prompt?: string; pieces?: ConstructorPiece[]; solution?: ConstructorStep[]; }; diff --git a/tests/test_ai_review.py b/tests/test_ai_review.py index 50c65ad..dfa91fb 100644 --- a/tests/test_ai_review.py +++ b/tests/test_ai_review.py @@ -232,3 +232,35 @@ def test_blocks_to_text_keeps_prose_and_code_but_drops_mermaid_and_sources(): assert "Суть" in out and "print(1)" in out and "Поток" in out and "Осторожно" in out assert "A-->B" not in out and "example.com" not in out assert len(blocks_to_text(blocks, 5)) == 5 + + +def test_blocks_to_text_scopes_constructor_with_text_to_the_written_part(): + pieces = [{"id": "a", "text": "Шаг A"}, {"id": "b", "text": "Шаг B"}] + question = [ + {"type": "paragraph", "data": {"text": "Условие"}}, + { + "type": "constructor", + "data": { + "kind": "sequence", + "mode": "with_text", + "prompt": "Соберите", + "text_prompt": "Объясните сложность", + "pieces": pieces, + }, + }, + ] + out = blocks_to_text(question, 10_000) + assert "Grade ONLY the written answer" in out and "Объясните сложность" in out + # куски задания модели не нужны: порядок она оценивать не должна + assert "Шаг A" not in out + replace_only = [{"type": "constructor", "data": {"kind": "sequence", "pieces": pieces}}] + assert blocks_to_text(replace_only, 10_000) == "" + + solution = [ + {"id": "a", "text": "Шаг A", "indent": 0}, + {"id": "b", "text": "Шаг B", "indent": 1}, + ] + reference = blocks_to_text( + [{"type": "constructor", "data": {"kind": "sequence", "solution": solution}}], 10_000 + ) + assert "1. Шаг A" in reference and "2. Шаг B" in reference diff --git a/tests/test_content_constructor.py b/tests/test_content_constructor.py index 908a2d7..0a1e34e 100644 --- a/tests/test_content_constructor.py +++ b/tests/test_content_constructor.py @@ -100,10 +100,40 @@ def test_loader_rejects_broken_build(tmp_path, body, needle): assert any("gil.yaml" in e and needle in e for e in errors), errors +def test_with_text_mode_passes_the_written_task_to_the_question(tmp_path): + root = make_catalog(tmp_path) + add_build( + root, + BUILD.replace( + " prompt: Соберите алгоритм из блоков\n", + " mode: with_text\n prompt: Соберите алгоритм из блоков\n text_prompt: Объясните сложность\n", + ), + ) + content = load_content(root) + assert content.errors == [] + data = build_question_blocks(gil(content))[-1]["data"] + assert data["mode"] == "with_text" and data["text_prompt"] == "Объясните сложность" + + +@pytest.mark.parametrize( + "body", + [ + BUILD.replace("kind: sequence", "kind: sequence\n mode: with_text"), + BUILD.replace("kind: sequence", "kind: sequence\n text_prompt: Объясните сложность"), + ], +) +def test_text_prompt_is_required_exactly_for_with_text(tmp_path, body): + root = make_catalog(tmp_path) + add_build(root, body) + assert any("text_prompt" in e for e in load_content(root).errors) + + @pytest.mark.parametrize( "data", [ None, + {"kind": "sequence", "mode": "mixed", "pieces": [{"id": "a", "text": "x"}]}, + {"kind": "sequence", "mode": "with_text", "pieces": [{"id": "a", "text": "x"}]}, {"kind": "graph", "pieces": [{"id": "a", "text": "x"}]}, {"kind": "sequence", "pieces": []}, {"kind": "sequence", "solution": [{"id": "a", "text": " "}]},