From 7545e47b52d87c45511091f8306fd757fb55c909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Frnka?= Date: Wed, 25 Nov 2026 11:19:12 +0100 Subject: [PATCH 01/10] TMP --- plugin/src/client.ts | 26 +++ .../components/QuestionnaireChangeBadge.tsx | 31 ++- .../QuestionnaireChangesModal.module.css | 71 +++++++ .../components/QuestionnaireChangesModal.tsx | 192 ++++++++++++++++++ plugin/src/types.ts | 21 ++ .../ai/generation/dmp_generator_component.py | 126 +----------- .../ai/knowledgemodel/questionnaire_diff.py | 179 ++++++++++++++++ .../knowledgemodel/questionnaire_snapshot.py | 130 ++++++++++++ .../ai/knowledgemodel/reachable_replies.py | 67 ++++++ .../ai/persistence/database.py | 52 +++++ .../ai/persistence/schema.py | 32 +++ .../ai/run_pipeline.py | 4 + .../api/pipeline_routes.py | 10 + .../ai_document_plugin_service/api/types.py | 24 ++- ...261120_02_create_generation_reply_table.py | 60 ++++++ .../service/pipeline_service.py | 35 ++++ .../service/questionnaire_state_service.py | 16 +- .../tests/generation/test_dmp_generator.py | 107 ---------- .../knowledgemodel/test_questionnaire_diff.py | 173 ++++++++++++++++ .../test_questionnaire_snapshot.py | 114 +++++++++++ .../knowledgemodel/test_reachable_replies.py | 125 ++++++++++++ 21 files changed, 1353 insertions(+), 242 deletions(-) create mode 100644 plugin/src/components/QuestionnaireChangesModal.module.css create mode 100644 plugin/src/components/QuestionnaireChangesModal.tsx create mode 100644 service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py create mode 100644 service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py create mode 100644 service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py create mode 100644 service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py create mode 100644 service/tests/knowledgemodel/test_questionnaire_diff.py create mode 100644 service/tests/knowledgemodel/test_questionnaire_snapshot.py create mode 100644 service/tests/knowledgemodel/test_reachable_replies.py diff --git a/plugin/src/client.ts b/plugin/src/client.ts index 9161d52..47f5aa5 100644 --- a/plugin/src/client.ts +++ b/plugin/src/client.ts @@ -8,6 +8,7 @@ import type { LlmSettingsUpdate, PipelineStatusResponse, PipelineSummaryItem, + QuestionnaireChangesResponse, TemplateDetail, TemplateOption, TemplateScope, @@ -243,6 +244,31 @@ export const getLatestQuestionnaireEventUuid = async ( return latest.uuid } +export const getQuestionnaireChanges = async ( + runId: string, +): Promise => { + const url = `${getApiBaseUrl()}/pipelines/status/${encodeURIComponent(runId)}/changes` + const response = await apiFetch(url) + const data = await readApiResponse( + response, + url, + ) + + if (!response.ok) { + throw new Error( + 'detail' in data && data.detail + ? data.detail + : 'Failed to load the changes of the questionnaire.', + ) + } + + if (!('changes' in data) || !Array.isArray(data.changes)) { + throw new Error('Invalid questionnaire changes returned.') + } + + return data +} + export const deletePipeline = async (runId: string): Promise => { const url = `${getApiBaseUrl()}/pipelines/status/${encodeURIComponent(runId)}` const response = await apiFetch(url, { method: 'DELETE' }) diff --git a/plugin/src/components/QuestionnaireChangeBadge.tsx b/plugin/src/components/QuestionnaireChangeBadge.tsx index 0b67e77..9d78694 100644 --- a/plugin/src/components/QuestionnaireChangeBadge.tsx +++ b/plugin/src/components/QuestionnaireChangeBadge.tsx @@ -1,6 +1,8 @@ import { Badge } from '@ds-wizard/plugin-sdk/ui/Badge' import { Spinner } from '@ds-wizard/plugin-sdk/ui/Icon' +import { useState } from 'react' +import { QuestionnaireChangesModal } from '@/components/QuestionnaireChangesModal' import type { RunRecord } from '@/hooks/useGenerationHistory' import { isQuestionnaireChanged, @@ -8,12 +10,17 @@ import { } from '@/hooks/useLatestQuestionnaireEvent' type QuestionnaireChangeBadgeProps = { - run: Pick + run: Pick latestEvent: LatestQuestionnaireEvent } -/** A small badge saying whether the questionnaire answers may have changed since the document was generated. */ +/** + * A small badge saying whether the questionnaire answers may have changed since the document was generated. + * Clicking it lists what changed. + */ export function QuestionnaireChangeBadge({ run, latestEvent }: QuestionnaireChangeBadgeProps) { + const [isOpen, setIsOpen] = useState(false) + if (run.status !== 'succeeded') return null if (latestEvent.status === 'loading') { @@ -24,12 +31,18 @@ export function QuestionnaireChangeBadge({ run, latestEvent }: QuestionnaireChan if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null return ( - - Questionnaire changed after the DMP was generated - + <> + setIsOpen(true)} + > + Questionnaire changed after the DMP was generated + + {isOpen && ( + setIsOpen(false)} /> + )} + ) } diff --git a/plugin/src/components/QuestionnaireChangesModal.module.css b/plugin/src/components/QuestionnaireChangesModal.module.css new file mode 100644 index 0000000..e7c184b --- /dev/null +++ b/plugin/src/components/QuestionnaireChangesModal.module.css @@ -0,0 +1,71 @@ +.chapters { + display: grid; + gap: var(--ui-space-4); +} + +.chapter { + margin: 0 0 var(--ui-space-2); + font-size: 1rem; + font-weight: 600; +} + +.list { + display: grid; + gap: var(--ui-space-3); + margin: 0; + padding: 0; + list-style: none; +} + +.change { + display: grid; + gap: 0.25rem; + padding-bottom: var(--ui-space-3); + border-bottom: 1px solid var(--ui-border); + overflow-wrap: anywhere; +} + +.change:last-child { + padding-bottom: 0; + border-bottom: none; +} + +.context { + color: var(--ui-text-muted); + font-size: 0.8rem; +} + +.heading { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--ui-space-2); + font-weight: 600; +} + +.values { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: var(--ui-space-2); + font-size: 0.9rem; +} + +.value { + white-space: pre-wrap; +} + +.old { + color: var(--ui-text-muted); + text-decoration: line-through; +} + +.empty { + color: var(--ui-text-muted); + font-style: italic; +} + +.meta { + color: var(--ui-text-muted); + font-size: 0.8rem; +} diff --git a/plugin/src/components/QuestionnaireChangesModal.tsx b/plugin/src/components/QuestionnaireChangesModal.tsx new file mode 100644 index 0000000..d77c162 --- /dev/null +++ b/plugin/src/components/QuestionnaireChangesModal.tsx @@ -0,0 +1,192 @@ +import { Alert } from '@ds-wizard/plugin-sdk/ui/Alert' +import { AsyncBlock } from '@ds-wizard/plugin-sdk/ui/AsyncBlock' +import { Badge, type BadgeProps } from '@ds-wizard/plugin-sdk/ui/Badge' +import { Icon } from '@ds-wizard/plugin-sdk/ui/Icon' +import { Muted } from '@ds-wizard/plugin-sdk/ui/Text' +import { useEffect, useRef, useState } from 'react' + +import { getQuestionnaireChanges } from '@/client' +import { Modal } from '@/components/Modal' +import styles from '@/components/QuestionnaireChangesModal.module.css' +import type { QuestionnaireChange, QuestionnaireChangesResponse } from '@/types' + +type QuestionnaireChangesModalProps = { + runId: string + onClose: () => void +} + +type LoadState = + | { status: 'loading' } + | { status: 'failed'; message: string } + | { status: 'ready'; data: QuestionnaireChangesResponse } + +const KIND_LABELS: Record = { + added: 'Added', + changed: 'Changed', + removed: 'Removed', +} + +const KIND_TONES: Record> = { + added: 'success', + changed: 'info', + removed: 'danger', +} + +const OTHER_CHAPTER = 'Other' + +function groupByChapter(changes: QuestionnaireChange[]): Array<[string, QuestionnaireChange[]]> { + const groups = new Map() + for (const change of changes) { + const chapter = change.chapterTitle ?? OTHER_CHAPTER + groups.set(chapter, [...(groups.get(chapter) ?? []), change]) + } + return [...groups] +} + +function formatChangedAt(changedAt: string | null): string | null { + if (!changedAt) return null + const date = new Date(changedAt) + return Number.isNaN(date.getTime()) ? null : date.toLocaleString() +} + +function Value({ value, old = false }: { value: string | null; old?: boolean }) { + if (!value) { + return (empty) + } + return {value} +} + +function ChangeValues({ change }: { change: QuestionnaireChange }) { + if (change.kind === 'added') { + return ( +
+ +
+ ) + } + if (change.kind === 'removed') { + return ( +
+ +
+ ) + } + return ( +
+ + + +
+ ) +} + +function ChangeItem({ change }: { change: QuestionnaireChange }) { + const changedAt = formatChangedAt(change.changedAt) + const meta = [change.changedBy, changedAt].filter(Boolean).join(', ') + + return ( +
  • + {change.context.length > 0 && ( +
    {change.context.join(' › ')}
    + )} +
    + {KIND_LABELS[change.kind]} + {change.questionTitle ?? 'Unknown question'} +
    + + {meta &&
    {meta}
    } +
  • + ) +} + +function ChangesContent({ data }: { data: QuestionnaireChangesResponse }) { + if (!data.available) { + return ( + + This document was generated before the answers were stored, so what changed cannot + be shown. + + ) + } + if (data.changes.length === 0) { + return ( + + No answers differ from when this document was generated. Only other parts of the + questionnaire, such as its phase or labels, were edited. + + ) + } + + return ( +
    + {groupByChapter(data.changes).map(([chapter, changes]) => ( +
    +

    {chapter}

    +
      + {changes.map((change) => ( + + ))} +
    +
    + ))} +
    + ) +} + +/** Lists the answers that differ between a generation and the questionnaire as it is now. */ +export function QuestionnaireChangesModal({ runId, onClose }: QuestionnaireChangesModalProps) { + const [state, setState] = useState({ status: 'loading' }) + const closeRef = useRef(null) + + useEffect(() => { + let cancelled = false + setState({ status: 'loading' }) + void getQuestionnaireChanges(runId) + .then((data) => { + if (!cancelled) setState({ status: 'ready', data }) + }) + .catch((error: unknown) => { + if (!cancelled) { + setState({ + status: 'failed', + message: + error instanceof Error + ? error.message + : 'Failed to load the changes of the questionnaire.', + }) + } + }) + + return () => { + cancelled = true + } + }, [runId]) + + return ( + + Close + + } + > + + {state.status === 'ready' && } + + + ) +} diff --git a/plugin/src/types.ts b/plugin/src/types.ts index 49fba1e..d9c8914 100644 --- a/plugin/src/types.ts +++ b/plugin/src/types.ts @@ -112,4 +112,25 @@ export type PipelineSummaryItem = { sourceEventUuid: string | null } +/** One answer that differs between a generation and the questionnaire now. */ +export type QuestionnaireChange = { + path: string + kind: 'added' | 'changed' | 'removed' + chapterTitle: string | null + questionTitle: string | null + /** Titles of the list items the question sits in, outermost first. */ + context: string[] + oldValue: string | null + newValue: string | null + /** Who made the answer and when; only known for answers that exist now. */ + changedBy: string | null + changedAt: string | null +} + +export type QuestionnaireChangesResponse = { + /** False for runs that did not store their answers, so there is nothing to compare with. */ + available: boolean + changes: QuestionnaireChange[] +} + export type ResultRenderMode = 'formatted' | 'raw' diff --git a/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py b/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py index 7e60848..dcdcbeb 100644 --- a/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py +++ b/service/src/ai_document_plugin_service/ai/generation/dmp_generator_component.py @@ -18,6 +18,7 @@ GenerationLLM, ) from ai_document_plugin_service.ai.generation.parse_answers import parse_answer +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies from ai_document_plugin_service.cover_page.cover_page_renderer import CoverPageRenderer from ai_document_plugin_service.cover_page.cover_page_resolvers import CoverDataSources @@ -88,7 +89,7 @@ async def run_async( ) cover_page_assignments = document_assignments[:cover_page_section_count] document_assignments = document_assignments[cover_page_section_count:] - replies = self._filter_reachable_replies(replies, km) + replies = reachable_replies(km, replies) logger.info( 'Starting DMP generation', extra={ @@ -241,129 +242,6 @@ def run( msg, ) - @staticmethod - def _filter_reachable_replies( - replies: dict[str, Any], - km: dict[str, Any], - ) -> dict[str, Any]: - """Keep only replies that are reachable in the current questionnaire state. - - DSW can keep stale descendants in the raw questionnaire JSON when a user - changes an earlier answer (for example `YES -> NO`) or removes a list - item. Generation should ignore those historical branches and only use - replies that can be reached from the current KM roots via the currently - selected option answers and existing list-item UUIDs. - """ - chapter_uuids = km.get('chapterUuids') - entities = km.get('entities', {}) - chapters = entities.get('chapters', {}) - questions = entities.get('questions', {}) - answers = entities.get('answers', {}) - if not chapter_uuids or not chapters or not questions: - return replies - - reachable_paths: set[str] = set() - - for chapter_uuid in chapter_uuids: - chapter = chapters.get(chapter_uuid) - if chapter is None: - continue - for question_uuid in chapter.get('questionUuids', []): - DmpGeneratorComponent._walk_reachable_question( - question_uuid, - f'{chapter_uuid}.{question_uuid}', - replies, - questions, - answers, - reachable_paths, - ) - - return {key: value for key, value in replies.items() if key in reachable_paths} - - @staticmethod - def _walk_reachable_options_question( - path: str, - replies: dict[str, Any], - answers: dict[str, Any], - ) -> list[tuple[str, str]]: - selected_answer_uuid = replies.get(path, {}).get('value', {}).get('value') - if not selected_answer_uuid: - return [] - - answer = answers.get(selected_answer_uuid) - if answer is None: - return [] - - return [ - ( - follow_up_uuid, - f'{path}.{selected_answer_uuid}.{follow_up_uuid}', - ) - for follow_up_uuid in answer.get('followUpUuids', []) - ] - - @staticmethod - def _walk_reachable_list_question( - question: dict[str, Any], - path: str, - replies: dict[str, Any], - ) -> list[tuple[str, str]]: - list_items = replies.get(path, {}).get('value', {}).get('value', []) - if not isinstance(list_items, list): - logger.warning('Expected list items at %s, got %s', path, type(list_items).__name__) - return [] - - return [ - ( - nested_question_uuid, - f'{path}.{item_uuid}.{nested_question_uuid}', - ) - for item_uuid in list_items - for nested_question_uuid in question.get('itemTemplateQuestionUuids', []) - ] - - @staticmethod - def _walk_reachable_question( - question_uuid: str, - path: str, - replies: dict[str, Any], - questions: dict[str, Any], - answers: dict[str, Any], - reachable_paths: set[str], - ) -> None: - question = questions.get(question_uuid) - if question is None: - return - - if path in replies: - reachable_paths.add(path) - - question_type = question.get('questionType') - if question_type == 'OptionsQuestion': - child_questions = DmpGeneratorComponent._walk_reachable_options_question( - path, - replies, - answers, - ) - elif question_type == 'ListQuestion': - child_questions = DmpGeneratorComponent._walk_reachable_list_question( - question, - path, - replies, - ) - else: - child_questions = [] - - for child_question_uuid, child_path in child_questions: - DmpGeneratorComponent._walk_reachable_question( - child_question_uuid, - child_path, - replies, - questions, - answers, - reachable_paths, - ) - @staticmethod def _get_reply_keys_at_level(replies: dict[str, Any], prefix: str) -> list[str]: """Return reply keys that are prefix + exactly one more segment (neighbouring replies).""" diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py new file mode 100644 index 0000000..7666711 --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py @@ -0,0 +1,179 @@ +"""What changed between the replies stored with a generation and the replies of the questionnaire now.""" + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from enum import StrEnum +from typing import Any +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( + ReplyType, + StoredReply, + build_snapshot, +) +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies + +MAX_ITEM_TITLE_LENGTH = 80 +REMOVED_OPTION = '(removed option)' + + +class ChangeKind(StrEnum): + ADDED = 'added' + CHANGED = 'changed' + REMOVED = 'removed' + + +@dataclass(frozen=True) +class ReplyChange: + path: str + kind: ChangeKind + old: StoredReply | None + new: StoredReply | None + + +@dataclass(frozen=True) +class ChangeDescription: + """A change in words, as shown to the user.""" + + path: str + kind: ChangeKind + chapter_title: str | None + question_title: str | None + # The list items the question sits in, outermost first, e.g. the title of a dataset. + context: list[str] + old_value: str | None + new_value: str | None + # Who made the answer and when. Only known for answers that exist now. + changed_by: str | None + changed_at: str | None + + +def diff_replies(old: Iterable[StoredReply], new: Iterable[StoredReply]) -> list[ReplyChange]: + """The replies added, changed and removed between two snapshots, ordered by path.""" + old_by_path = {reply.path: reply for reply in old} + new_by_path = {reply.path: reply for reply in new} + + changes: list[ReplyChange] = [] + for path in sorted(old_by_path.keys() | new_by_path.keys()): + before = old_by_path.get(path) + after = new_by_path.get(path) + if before is None: + changes.append(ReplyChange(path, ChangeKind.ADDED, None, after)) + elif after is None: + changes.append(ReplyChange(path, ChangeKind.REMOVED, before, None)) + elif not before.same_value_as(after): + changes.append(ReplyChange(path, ChangeKind.CHANGED, before, after)) + return changes + + +def describe_changes(stored: Iterable[StoredReply], current_detail: dict[str, Any]) -> list[ChangeDescription]: + """Describe what changed between ``stored`` and the questionnaire detail as DSW returns it now. + + Labels and titles come from the current knowledge model; answers and choices it no longer knows fall back to + the label stored with the reply. + """ + km = current_detail['knowledgeModel'] + current_replies = current_detail['replies'] + + stored_by_path = {reply.path: reply for reply in stored} + current = build_snapshot(km, current_replies) + current_by_path = {reply.path: reply for reply in current} + reachable = reachable_replies(km, current_replies) + + descriptions: list[ChangeDescription] = [] + for change in diff_replies(stored_by_path.values(), current): + side = current_by_path if change.new is not None else stored_by_path + current_reply = reachable.get(change.path) if change.new is not None else None + descriptions.append( + ChangeDescription( + path=change.path, + kind=change.kind, + chapter_title=_chapter_title(km, change.path), + question_title=_question_title(km, change.path), + context=_item_context(km, change.path, side), + old_value=_describe_value(change.old, km, stored_by_path) if change.old else None, + new_value=_describe_value(change.new, km, current_by_path) if change.new else None, + changed_by=_user_name((current_reply or {}).get('createdBy')), + changed_at=(current_reply or {}).get('createdAt'), + ), + ) + return descriptions + + +def _questions(km: dict[str, Any]) -> dict[str, Any]: + return km['entities']['questions'] + + +def _chapter_title(km: dict[str, Any], path: str) -> str | None: + return km['entities']['chapters'].get(path.split('.', 1)[0], {}).get('title') + + +def _question_title(km: dict[str, Any], path: str) -> str | None: + return _questions(km).get(path.rsplit('.', 1)[-1], {}).get('title') + + +def _user_name(user: dict[str, Any] | None) -> str | None: + if not user: + return None + name = f'{user.get("firstName", "")} {user.get("lastName", "")}'.strip() + return name or None + + +def _item_title(km: dict[str, Any], list_path: str, item_uuid: UUID | str, side: Mapping[str, StoredReply]) -> str: + """An item has no title of its own: it is the answer to the first question of the list's item template.""" + list_question = _questions(km).get(list_path.rsplit('.', 1)[-1], {}) + templates = list_question.get('itemTemplateQuestionUuids', []) + if templates: + first = side.get(f'{list_path}.{item_uuid}.{templates[0]}') + if first is not None and first.text_value: + title = first.text_value.strip().splitlines()[0] + if len(title) > MAX_ITEM_TITLE_LENGTH: + return title[: MAX_ITEM_TITLE_LENGTH - 1] + '…' + return title + return 'Untitled item' + + +def _item_context(km: dict[str, Any], path: str, side: Mapping[str, StoredReply]) -> list[str]: + """The titles of the list items a path runs through, outermost first.""" + segments = path.split('.') + questions = _questions(km) + context: list[str] = [] + # The last segment is the question itself; the first is the chapter. + for index in range(2, len(segments) - 1): + if questions.get(segments[index - 1], {}).get('questionType') == 'ListQuestion': + context.append(_item_title(km, '.'.join(segments[:index]), segments[index], side)) + return context + + +def _label(km: dict[str, Any], kind: str, uuid: UUID) -> str | None: + label = km['entities'].get(kind, {}).get(str(uuid), {}).get('label') + return label if isinstance(label, str) else None + + +def _describe_value(reply: StoredReply, km: dict[str, Any], side: Mapping[str, StoredReply]) -> str: + if reply.reply_type == ReplyType.ANSWER: + return _label(km, 'answers', reply.uuid_value) or reply.display_text or REMOVED_OPTION + if reply.reply_type == ReplyType.MULTI_CHOICE: + return _describe_choices(reply, km) + if reply.reply_type == ReplyType.ITEM_SELECT: + return _describe_selected_item(reply, km, side) + if reply.reply_type == ReplyType.ITEM_LIST: + return ', '.join(_item_title(km, reply.path, item_uuid, side) for item_uuid in reply.uuid_values or ()) + return reply.text_value or '' + + +def _describe_choices(reply: StoredReply, km: dict[str, Any]) -> str: + labels = [_label(km, 'choices', choice) for choice in reply.uuid_values or ()] + if all(labels): + return ', '.join(label for label in labels if label) + return reply.display_text or REMOVED_OPTION + + +def _describe_selected_item(reply: StoredReply, km: dict[str, Any], side: Mapping[str, StoredReply]) -> str: + """An item-select reply names an item of another list; its title is looked up there.""" + question = _questions(km).get(reply.path.rsplit('.', 1)[-1], {}) + list_question_uuid = question.get('listQuestionUuid') + if not list_question_uuid or reply.uuid_value is None: + return 'Untitled item' + list_path = f'{reply.path.rsplit(".", 1)[0]}.{list_question_uuid}' + return _item_title(km, list_path, reply.uuid_value, side) diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py new file mode 100644 index 0000000..5481ef5 --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py @@ -0,0 +1,130 @@ +"""The replies of a questionnaire in the form they are stored with a generation. + +Only replies that apply to the questionnaire as it stands are kept (see ``reachable_replies``), as typed values: +what DSW sends as ``{type, value}`` becomes one of the fields of ``StoredReply``. Replies that are empty, and +replies of types that never reach a document (files), are left out, so that an empty reply and a missing one are +the same thing when two snapshots are compared. +""" + +import logging +from dataclasses import dataclass +from enum import StrEnum +from typing import Any +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies + +logger = logging.getLogger(__name__) + + +class ReplyType(StrEnum): + """Stored in the database; changing a value requires a migration.""" + + STRING = 'string' + INTEGRATION = 'integration' + ANSWER = 'answer' + ITEM_SELECT = 'item_select' + MULTI_CHOICE = 'multi_choice' + ITEM_LIST = 'item_list' + + +@dataclass(frozen=True) +class StoredReply: + """One reply. Exactly one of the three value fields is set, which one depends on the type: + + - ``text_value``: string and integration replies. + - ``uuid_value``: answer replies (the selected answer) and item-select replies (the selected item). + - ``uuid_values``: multi-choice replies (the selected choices) and item-list replies (the items, in order). + """ + + path: str + reply_type: ReplyType + text_value: str | None = None + uuid_value: UUID | None = None + uuid_values: tuple[UUID, ...] | None = None + # What the value was called when it was stored, for answers and choices whose label can no longer be looked + # up later, e.g. after the knowledge model changed. Not part of the value. + display_text: str | None = None + + def same_value_as(self, other: 'StoredReply') -> bool: + return (self.reply_type, self.text_value, self.uuid_value, self.uuid_values) == ( + other.reply_type, + other.text_value, + other.uuid_value, + other.uuid_values, + ) + + +def build_snapshot(km: dict[str, Any], replies: dict[str, Any]) -> list[StoredReply]: + """The reachable replies of a questionnaire, typed, ordered by path. + + ``km`` is the ``knowledgeModel`` of the questionnaire detail and ``replies`` its ``replies``. A reply that + cannot be read is skipped with a warning instead of failing the caller. + """ + snapshot: list[StoredReply] = [] + for path, reply in sorted(reachable_replies(km, replies).items()): + try: + stored = _to_stored_reply(path, reply.get('value', {}), km['entities']) + except (KeyError, TypeError, ValueError, AttributeError): + logger.warning('Skipping a reply that cannot be stored', exc_info=True, extra={'reply_path': path}) + continue + if stored is not None and not _is_empty(stored): + snapshot.append(stored) + return snapshot + + +def _to_stored_reply(path: str, value: dict[str, Any], entities: dict[str, Any]) -> StoredReply | None: + reply_type = value.get('type') + raw = value.get('value') + + if reply_type == 'StringReply': + return StoredReply(path, ReplyType.STRING, text_value=_as_text(raw)) + if reply_type == 'IntegrationReply': + return StoredReply(path, ReplyType.INTEGRATION, text_value=_as_text(raw['value'])) + if reply_type in {'AnswerReply', 'ItemSelectReply'}: + return _single_uuid_reply(path, reply_type, raw, entities) + if reply_type in {'MultiChoiceReply', 'ItemListReply'}: + return _multiple_uuids_reply(path, reply_type, raw, entities) + + if reply_type != 'FileReply': + logger.warning('Skipping a reply of an unknown type', extra={'reply_path': path, 'reply_type': reply_type}) + return None + + +def _single_uuid_reply(path: str, reply_type: str, raw: str, entities: dict[str, Any]) -> StoredReply: + if reply_type == 'AnswerReply': + return StoredReply(path, ReplyType.ANSWER, uuid_value=UUID(raw), display_text=_label(entities, 'answers', raw)) + return StoredReply(path, ReplyType.ITEM_SELECT, uuid_value=UUID(raw)) + + +def _multiple_uuids_reply(path: str, reply_type: str, raw: list[str], entities: dict[str, Any]) -> StoredReply: + uuids = tuple(UUID(value) for value in raw) + if reply_type == 'ItemListReply': + return StoredReply(path, ReplyType.ITEM_LIST, uuid_values=uuids) + labels = [_label(entities, 'choices', value) for value in raw] + return StoredReply( + path, + ReplyType.MULTI_CHOICE, + uuid_values=uuids, + display_text=', '.join(label for label in labels if label) or None, + ) + + +def _as_text(value: object) -> str: + if not isinstance(value, str): + msg = 'Expected a text reply value' + raise TypeError(msg) + return value + + +def _label(entities: dict[str, Any], kind: str, uuid: str) -> str | None: + label = entities.get(kind, {}).get(uuid, {}).get('label') + return label if isinstance(label, str) else None + + +def _is_empty(reply: StoredReply) -> bool: + if reply.text_value is not None: + return not reply.text_value.strip() + if reply.uuid_values is not None: + return not reply.uuid_values + return False diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py new file mode 100644 index 0000000..5cd742a --- /dev/null +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/reachable_replies.py @@ -0,0 +1,67 @@ +""" +Filter questionnaire replies down to those that apply to the questionnaire as it stands. + +DSW keeps replies that no longer apply: after an options question is switched to another answer, the replies to +the follow-up questions of the previous answer stay in the data. This walks the knowledge model from the +chapters and keeps only the replies on a path that the other replies lead to. +""" + +from typing import Any + + +def reachable_replies(km: dict[str, Any], replies: dict[str, Any]) -> dict[str, Any]: + """Return the replies that apply to the questionnaire, keyed by their path and otherwise untouched. + + ``km`` is the ``knowledgeModel`` of the questionnaire detail and ``replies`` its ``replies``. A reply is kept + when its question exists in the knowledge model and every option answer and list item on its path is the one + currently selected. An item-select reply whose item has since been deleted is kept as it is; it is a reply of + a reachable question. + + The replies keep the order of ``replies``: document generation takes the order of list items from it. + """ + entities = km['entities'] + reachable: set[str] = set() + + stack: list[tuple[str, str]] = [] + for chapter_uuid in km['chapterUuids']: + chapter = entities['chapters'].get(chapter_uuid, {}) + stack.extend( + (question_uuid, f'{chapter_uuid}.{question_uuid}') for question_uuid in chapter.get('questionUuids', []) + ) + + while stack: + question_uuid, path = stack.pop() + question = entities['questions'].get(question_uuid) + if question is None: + continue + reply = replies.get(path) + if reply is not None: + reachable.add(path) + stack.extend(_child_questions(entities, question, path, reply)) + + return {path: reply for path, reply in replies.items() if path in reachable} + + +def _child_questions( + entities: dict[str, Any], + question: dict[str, Any], + path: str, + reply: dict[str, Any] | None, +) -> list[tuple[str, str]]: + """The questions below a question as ``(question uuid, path)``, given the reply to it.""" + value = reply.get('value', {}) if reply is not None else {} + question_type = question.get('questionType') + + if question_type == 'OptionsQuestion' and value.get('type') == 'AnswerReply': + answer_uuid = value['value'] + answer = entities['answers'].get(answer_uuid, {}) + return [(follow_up, f'{path}.{answer_uuid}.{follow_up}') for follow_up in answer.get('followUpUuids', [])] + + if question_type == 'ListQuestion' and value.get('type') == 'ItemListReply': + return [ + (template_question, f'{path}.{item_uuid}.{template_question}') + for item_uuid in value['value'] + for template_question in question.get('itemTemplateQuestionUuids', []) + ] + + return [] diff --git a/service/src/ai_document_plugin_service/ai/persistence/database.py b/service/src/ai_document_plugin_service/ai/persistence/database.py index 1f04689..3bcd262 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/database.py +++ b/service/src/ai_document_plugin_service/ai/persistence/database.py @@ -18,6 +18,7 @@ from ai_document_plugin_service.ai.assignment.types import SectionQuestionPaths from ai_document_plugin_service.ai.common.config import DatabaseConfig, LLMConfig from ai_document_plugin_service.ai.common.types import TemplateContent +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ReplyType, StoredReply from ai_document_plugin_service.ai.persistence.errors import TemplateTitleConflictError from ai_document_plugin_service.ai.persistence.schema import create_persistence_schema from ai_document_plugin_service.ai.persistence.secret_cipher import SecretCipher @@ -271,6 +272,14 @@ async def create_generation_stats( ) -> None: """Create the stats row of a finished generation.""" + @abstractmethod + async def save_generation_replies(self, run_id: UUID, replies: Sequence[StoredReply]) -> None: + """Store the replies a generation was made from.""" + + @abstractmethod + async def get_generation_replies(self, run_id: UUID) -> list[StoredReply]: + """Get the replies stored with a generation, ordered by path. The caller checks ownership of the run.""" + @abstractmethod async def get_generation( self, @@ -322,6 +331,7 @@ def __init__( self.template_table = schema.template_table self.generation_table = schema.generation_table self.generation_stats_table = schema.generation_stats_table + self.generation_reply_table = schema.generation_reply_table self.llm_settings_table = schema.llm_settings_table self._database_verified = False logger.info( @@ -393,6 +403,7 @@ async def _ensure_schema(self) -> None: 'assignment_section', 'generation', 'generation_stats', + 'generation_reply', 'llm_settings', } missing_tables = sorted(required_tables - existing_tables) @@ -803,6 +814,47 @@ async def create_generation_stats( async with self._connect() as connection: await connection.execute(statement) + async def save_generation_replies(self, run_id: UUID, replies: Sequence[StoredReply]) -> None: + if not replies: + return + await self._ensure_schema() + rows = [ + { + 'run_id': run_id, + 'path': reply.path, + 'reply_type': reply.reply_type.value, + 'text_value': reply.text_value, + 'uuid_value': reply.uuid_value, + 'uuid_values': list(reply.uuid_values) if reply.uuid_values is not None else None, + 'display_text': reply.display_text, + } + for reply in replies + ] + + async with self._connect() as connection: + await connection.execute(self.generation_reply_table.insert(), rows) + + async def get_generation_replies(self, run_id: UUID) -> list[StoredReply]: + await self._ensure_schema() + table = self.generation_reply_table + statement = select(table).where(table.c.run_id == run_id).order_by(table.c.path) + + async with self._connect() as connection: + result = await connection.execute(statement) + rows = result.fetchall() + + return [ + StoredReply( + path=row.path, + reply_type=ReplyType(row.reply_type), + text_value=row.text_value, + uuid_value=row.uuid_value, + uuid_values=tuple(row.uuid_values) if row.uuid_values is not None else None, + display_text=row.display_text, + ) + for row in rows + ] + async def get_generation( self, run_id: UUID, diff --git a/service/src/ai_document_plugin_service/ai/persistence/schema.py b/service/src/ai_document_plugin_service/ai/persistence/schema.py index e770e8a..1b15bfc 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/schema.py +++ b/service/src/ai_document_plugin_service/ai/persistence/schema.py @@ -2,6 +2,7 @@ from sqlalchemy import ( JSON, + CheckConstraint, Column, DateTime, ForeignKey, @@ -25,6 +26,7 @@ class PersistenceSchema: template_table: Table generation_table: Table generation_stats_table: Table + generation_reply_table: Table llm_settings_table: Table @@ -165,6 +167,35 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: ), ) + # The replies a generation was made from, one row per reply (see questionnaire_snapshot). Written together with + # the generation succeeding; a generation without rows predates this table or had no replies, and the former + # is told by generation.source_event_uuid being NULL. + generation_reply_table = Table( + 'generation_reply', + metadata, + Column('run_id', UUID(as_uuid=True), ForeignKey('generation.run_id', ondelete='CASCADE'), primary_key=True), + Column('path', Text, primary_key=True), + Column('reply_type', Text, nullable=False), + # Which one is set depends on the reply type, see StoredReply. + Column('text_value', Text, nullable=True), + Column('uuid_value', UUID(as_uuid=True), nullable=True), + Column('uuid_values', ARRAY(UUID(as_uuid=True)), nullable=True), + Column('display_text', Text, nullable=True), + CheckConstraint( + "reply_type IN ('string', 'integration', 'answer', 'item_select', 'multi_choice', 'item_list')", + name='ck_generation_reply_type', + ), + CheckConstraint( + "(reply_type IN ('string', 'integration')" + ' AND text_value IS NOT NULL AND uuid_value IS NULL AND uuid_values IS NULL)' + " OR (reply_type IN ('answer', 'item_select')" + ' AND uuid_value IS NOT NULL AND text_value IS NULL AND uuid_values IS NULL)' + " OR (reply_type IN ('multi_choice', 'item_list')" + ' AND uuid_values IS NOT NULL AND text_value IS NULL AND uuid_value IS NULL)', + name='ck_generation_reply_value', + ), + ) + # LLM connection settings, one row per tenant. Managed by tenant administrators. llm_settings_table = Table( 'llm_settings', @@ -192,5 +223,6 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: template_table=template_table, generation_table=generation_table, generation_stats_table=generation_stats_table, + generation_reply_table=generation_reply_table, llm_settings_table=llm_settings_table, ) diff --git a/service/src/ai_document_plugin_service/ai/run_pipeline.py b/service/src/ai_document_plugin_service/ai/run_pipeline.py index 2ec10d2..d24ee27 100644 --- a/service/src/ai_document_plugin_service/ai/run_pipeline.py +++ b/service/src/ai_document_plugin_service/ai/run_pipeline.py @@ -25,6 +25,7 @@ from ai_document_plugin_service.ai.generation.dmp_generator_component import DmpGeneratorComponent from ai_document_plugin_service.ai.generation.llm import SectionGenerationLLM from ai_document_plugin_service.ai.knowledgemodel.parser_component import ParserComponent +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot from ai_document_plugin_service.ai.persistence.assignment_loader_component import AssignmentLoaderComponent from ai_document_plugin_service.ai.persistence.assignment_saver_component import ( AssignmentSaverComponent, @@ -56,6 +57,8 @@ class PipelineOutput: # Generator output before polishing (the text fed into the polisher). dmp_pre_polished: str stats: PipelineStats + # The replies the document was generated from, kept to tell later what changed in the questionnaire. + reply_snapshot: tuple[StoredReply, ...] = () @dataclass(frozen=True) @@ -252,6 +255,7 @@ async def run_pipeline( markdown=result_markdown, dmp_pre_polished=dmp_pre_polished, stats=pipeline_stats, + reply_snapshot=tuple(build_snapshot(km, replies)), ) diff --git a/service/src/ai_document_plugin_service/api/pipeline_routes.py b/service/src/ai_document_plugin_service/api/pipeline_routes.py index f8b6340..17555b5 100644 --- a/service/src/ai_document_plugin_service/api/pipeline_routes.py +++ b/service/src/ai_document_plugin_service/api/pipeline_routes.py @@ -12,6 +12,7 @@ PipelineSaveRequest, PipelineStatusResponse, PipelineSummaryResponse, + QuestionnaireChangesResponse, ) from ai_document_plugin_service.di import ( AuthenticatedDI, @@ -72,6 +73,15 @@ async def get_pipeline_status( return status +@pipeline_router.get('/pipelines/status/{run_id}/changes') +async def get_questionnaire_changes( + run_id: UUID, + pipeline: PipelineServiceDI, + auth: AuthenticatedDI, +) -> QuestionnaireChangesResponse: + return await pipeline.get_questionnaire_changes(run_id, auth) + + @pipeline_router.patch('/pipelines/status/{run_id}/title') async def rename_pipeline_title( run_id: UUID, payload: PipelineRenameRequest, pipeline: PipelineServiceDI, auth: AuthenticatedDI diff --git a/service/src/ai_document_plugin_service/api/types.py b/service/src/ai_document_plugin_service/api/types.py index 0a9e899..2c60498 100644 --- a/service/src/ai_document_plugin_service/api/types.py +++ b/service/src/ai_document_plugin_service/api/types.py @@ -1,5 +1,5 @@ from enum import StrEnum -from typing import TYPE_CHECKING, Annotated, Self +from typing import TYPE_CHECKING, Annotated, Literal, Self from uuid import UUID from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -268,6 +268,28 @@ class PipelineErrorResponse(ApiModel): message: str +class QuestionnaireChangeResponse(ApiModel): + """One answer that differs between the generation and the questionnaire now.""" + + path: str + kind: Literal['added', 'changed', 'removed'] + chapter_title: str | None = None + question_title: str | None = None + # Titles of the list items the question sits in, outermost first. + context: list[str] + old_value: str | None = None + new_value: str | None = None + # Who made the answer and when; only known for answers that exist now. + changed_by: str | None = None + changed_at: str | None = None + + +class QuestionnaireChangesResponse(ApiModel): + # False for generations that did not store their replies, so there is nothing to compare with. + available: bool + changes: list[QuestionnaireChangeResponse] + + class PipelineSummaryResponse(ApiModel): run_id: UUID template_uuid: UUID diff --git a/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py b/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py new file mode 100644 index 0000000..637d649 --- /dev/null +++ b/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py @@ -0,0 +1,60 @@ +"""Store the replies a run was generated from. + +One row per reply, typed by reply type (see questionnaire_snapshot), so that what changed in the questionnaire +since the run can be told. Existing runs have no rows; generation.source_event_uuid being NULL marks them. + +Revision ID: 20261120_02 +Revises: 20261120_01 +Create Date: 2026-11-20 00:00:00 +""" + +import sqlalchemy as sa +from alembic import context, op +from sqlalchemy.dialects import postgresql + +revision = '20261120_02' +down_revision = '20261120_01' +branch_labels = None +depends_on = None + + +def _qualified_column_reference(schema: str | None, table: str, column: str) -> str: + if schema: + return f'{schema}.{table}.{column}' + return f'{table}.{column}' + + +def upgrade() -> None: + schema = context.get_context().version_table_schema + + op.create_table( + 'generation_reply', + sa.Column('run_id', postgresql.UUID(as_uuid=True), nullable=False), + sa.Column('path', sa.Text(), nullable=False), + sa.Column('reply_type', sa.Text(), nullable=False), + sa.Column('text_value', sa.Text(), nullable=True), + sa.Column('uuid_value', postgresql.UUID(as_uuid=True), nullable=True), + sa.Column('uuid_values', postgresql.ARRAY(postgresql.UUID(as_uuid=True)), nullable=True), + sa.Column('display_text', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('run_id', 'path', name='pk_generation_reply'), + sa.ForeignKeyConstraint( + ['run_id'], + [_qualified_column_reference(schema, 'generation', 'run_id')], + name='fk_generation_reply_run_id', + ondelete='CASCADE', + ), + sa.CheckConstraint( + "reply_type IN ('string', 'integration', 'answer', 'item_select', 'multi_choice', 'item_list')", + name='ck_generation_reply_type', + ), + sa.CheckConstraint( + "(reply_type IN ('string', 'integration')" + ' AND text_value IS NOT NULL AND uuid_value IS NULL AND uuid_values IS NULL)' + " OR (reply_type IN ('answer', 'item_select')" + ' AND uuid_value IS NOT NULL AND text_value IS NULL AND uuid_values IS NULL)' + " OR (reply_type IN ('multi_choice', 'item_list')" + ' AND uuid_values IS NOT NULL AND text_value IS NULL AND uuid_value IS NULL)', + name='ck_generation_reply_value', + ), + schema=schema, + ) diff --git a/service/src/ai_document_plugin_service/service/pipeline_service.py b/service/src/ai_document_plugin_service/service/pipeline_service.py index 04b14f9..f61c09a 100644 --- a/service/src/ai_document_plugin_service/service/pipeline_service.py +++ b/service/src/ai_document_plugin_service/service/pipeline_service.py @@ -30,6 +30,8 @@ PipelineStatus, PipelineStatusResponse, PipelineSummaryResponse, + QuestionnaireChangeResponse, + QuestionnaireChangesResponse, TemplateDetail, ) from ai_document_plugin_service.service.errors import ConflictError, NotConfiguredError, NotFoundError @@ -177,6 +179,38 @@ def __init__( self.questionnaire_state_service = questionnaire_state_service self._llm_clients = LlmClientTenantStore() + async def get_questionnaire_changes(self, run_id: UUID, auth: AuthenticatedUser) -> QuestionnaireChangesResponse: + """What changed in the questionnaire's answers since the run was generated. + + Not available for runs that did not store their replies; those have no event baseline either. + """ + record = await self.database.get_generation(run_id, auth.tenant_uuid, auth.user_uuid) + if record is None: + raise NotFoundError(NotFoundError.PIPELINE_RUN_MESSAGE) + if record.status != PipelineStatus.SUCCEEDED or record.source_event_uuid is None: + return QuestionnaireChangesResponse(available=False, changes=[]) + + stored = await self.database.get_generation_replies(run_id) + current_detail = await DSWClient(auth.token, auth.api_url).get_questionnaire_detail(record.questionnaire_uuid) + descriptions = self.questionnaire_state_service.changes(stored, current_detail) + return QuestionnaireChangesResponse( + available=True, + changes=[ + QuestionnaireChangeResponse( + path=description.path, + kind=description.kind.value, + chapter_title=description.chapter_title, + question_title=description.question_title, + context=description.context, + old_value=description.old_value, + new_value=description.new_value, + changed_by=description.changed_by, + changed_at=description.changed_at, + ) + for description in descriptions + ], + ) + async def get_pipeline_status(self, run_id: UUID, auth: AuthenticatedUser) -> PipelineStatusResponse | None: record = await self.database.get_generation(run_id, auth.tenant_uuid, auth.user_uuid) if record is None: @@ -510,6 +544,7 @@ def on_progress(message: str) -> None: # Cancellation won the atomic status transition. Discard the output # and skip success stats instead of reviving the cancelled run. return + await self.database.save_generation_replies(run_id, output.reply_snapshot) await self.database.create_generation_stats(run_id, get_trace_uuid(), **_succeeded_stats(output)) logger.info( 'Pipeline run status updated to succeeded', diff --git a/service/src/ai_document_plugin_service/service/questionnaire_state_service.py b/service/src/ai_document_plugin_service/service/questionnaire_state_service.py index d078a8b..175c96c 100644 --- a/service/src/ai_document_plugin_service/service/questionnaire_state_service.py +++ b/service/src/ai_document_plugin_service/service/questionnaire_state_service.py @@ -1,9 +1,18 @@ -"""The state of a questionnaire at the time a document was generated.""" +"""The state of a questionnaire at the time a document was generated. +The pipeline only asks for a state and stores it with the generation; what the state consists of is decided here. +Today it is the UUID of the newest event in the questionnaire's DSW event log, a cheap check that something changed +since, and the replies themselves (see ``build_snapshot``), which say what changed. +""" + +from collections.abc import Iterable from dataclasses import dataclass +from typing import Any from uuid import UUID from ai_document_plugin_service.ai.knowledgemodel.dsw_client import DSWClient +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_diff import ChangeDescription, describe_changes +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply @dataclass(frozen=True) @@ -16,3 +25,8 @@ class QuestionnaireStateService: async def capture(dsw_client: DSWClient, questionnaire_uuid: UUID) -> QuestionnaireState: """Read the current state id of the questionnaire.""" return QuestionnaireState(event_uuid=await dsw_client.get_latest_event_uuid(questionnaire_uuid)) + + @staticmethod + def changes(stored: Iterable[StoredReply], current_detail: dict[str, Any]) -> list[ChangeDescription]: + """What changed between the stored replies and the questionnaire detail as DSW returns it now.""" + return describe_changes(stored, current_detail) diff --git a/service/tests/generation/test_dmp_generator.py b/service/tests/generation/test_dmp_generator.py index 1383c7d..05b8098 100644 --- a/service/tests/generation/test_dmp_generator.py +++ b/service/tests/generation/test_dmp_generator.py @@ -61,51 +61,6 @@ def _km_fixture() -> dict: } -def _reachable_km_fixture() -> dict: - return { - 'chapterUuids': ['chapter'], - 'entities': { - 'chapters': { - 'chapter': { - 'uuid': 'chapter', - 'title': 'Chapter', - 'questionUuids': ['rootQ', 'datasetsQ'], - }, - }, - 'phases': {}, - 'questions': { - 'rootQ': { - 'questionType': 'OptionsQuestion', - 'title': 'Root', - 'text': 'Root text', - 'answerUuids': ['yes', 'no'], - }, - 'childQ': { - 'questionType': 'ValueQuestion', - 'title': 'Child', - 'text': 'Child text', - }, - 'datasetsQ': { - 'questionType': 'ListQuestion', - 'title': 'Datasets', - 'text': 'Datasets text', - 'itemTemplateQuestionUuids': ['datasetNameQ'], - }, - 'datasetNameQ': { - 'questionType': 'ValueQuestion', - 'title': 'Dataset name', - 'text': 'Dataset name text', - }, - }, - 'answers': { - 'yes': {'label': 'Yes', 'advice': None, 'followUpUuids': ['childQ']}, - 'no': {'label': 'No', 'advice': None, 'followUpUuids': []}, - }, - 'choices': {}, - }, - } - - def _questionnaire_detail_fixture() -> dict: return { 'name': 'Potato project', @@ -350,68 +305,6 @@ def test_handle_single_reply_adds_synthetic_neighbour_answers_from_depth_two() - assert synthetic['debug-info'] -def test_filter_reachable_replies_drops_stale_option_branch() -> None: - component = _component() - km = _reachable_km_fixture() - replies = { - 'chapter.rootQ': {'value': {'type': 'AnswerReply', 'value': 'no'}}, - 'chapter.rootQ.yes.childQ': { - 'value': { - 'type': 'StringReply', - 'value': 'stale child', - }, - }, - } - - filtered = component._filter_reachable_replies(replies, km) - - assert filtered == { - 'chapter.rootQ': {'value': {'type': 'AnswerReply', 'value': 'no'}}, - } - - -def test_filter_reachable_replies_drops_removed_list_item_branch() -> None: - component = _component() - km = _reachable_km_fixture() - replies = { - 'chapter.datasetsQ': { - 'value': { - 'type': 'ItemListReply', - 'value': ['active-item'], - }, - }, - 'chapter.datasetsQ.active-item.datasetNameQ': { - 'value': { - 'type': 'StringReply', - 'value': 'active', - }, - }, - 'chapter.datasetsQ.removed-item.datasetNameQ': { - 'value': { - 'type': 'StringReply', - 'value': 'stale', - }, - }, - } - - filtered = component._filter_reachable_replies(replies, km) - - assert filtered == { - 'chapter.datasetsQ': { - 'value': { - 'type': 'ItemListReply', - 'value': ['active-item'], - }, - }, - 'chapter.datasetsQ.active-item.datasetNameQ': { - 'value': { - 'type': 'StringReply', - 'value': 'active', - }, - }, - } - - def test_match_replies_selection_returns_empty_for_no_questions() -> None: result, has_answer = _component().match_replies_selection({}, {}, _km_fixture()) assert result == [] diff --git a/service/tests/knowledgemodel/test_questionnaire_diff.py b/service/tests/knowledgemodel/test_questionnaire_diff.py new file mode 100644 index 0000000..cecfbc2 --- /dev/null +++ b/service/tests/knowledgemodel/test_questionnaire_diff.py @@ -0,0 +1,173 @@ +import copy +from typing import Any +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_diff import ( + ChangeKind, + describe_changes, + diff_replies, +) +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( + ReplyType, + StoredReply, + build_snapshot, +) + + +def u(number: int) -> str: + return str(UUID(int=number)) + + +YES, NO = u(1), u(2) +ITEM_1, ITEM_2 = u(5), u(6) +USER = {'firstName': 'Ada', 'lastName': 'Lovelace'} + +KM = { + 'chapterUuids': ['c1'], + 'entities': { + 'chapters': {'c1': {'title': 'Data', 'questionUuids': ['opt', 'items', 'pick', 'plain']}}, + 'questions': { + 'opt': {'questionType': 'OptionsQuestion', 'title': 'Reuse?'}, + 'items': {'questionType': 'ListQuestion', 'title': 'Datasets', 'itemTemplateQuestionUuids': ['name', 'fmt']}, + 'name': {'questionType': 'ValueQuestion', 'title': 'Name'}, + 'fmt': {'questionType': 'ValueQuestion', 'title': 'Format'}, + 'pick': {'questionType': 'ItemSelectQuestion', 'title': 'Main dataset', 'listQuestionUuid': 'items'}, + 'plain': {'questionType': 'ValueQuestion', 'title': 'Notes'}, + }, + 'answers': {YES: {'label': 'Yes', 'followUpUuids': []}, NO: {'label': 'No', 'followUpUuids': []}}, + 'choices': {}, + }, +} + + +def reply(reply_type: str, value: Any, by: dict[str, str] | None = None) -> dict[str, Any]: + return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': by} + + +def text(path: str, value: str) -> StoredReply: + return StoredReply(path, ReplyType.STRING, text_value=value) + + +def describe(old_replies: dict[str, Any], new_replies: dict[str, Any], km: dict[str, Any] | None = None) -> list: + stored = build_snapshot(KM, old_replies) + return describe_changes(stored, {'knowledgeModel': km or KM, 'replies': new_replies}) + + +def test_diff_reports_added_changed_and_removed_replies_ordered_by_path() -> None: + old = [text('a', 'same'), text('b', 'before'), text('c', 'gone')] + new = [text('a', 'same'), text('b', 'after'), text('d', 'new')] + + changes = diff_replies(old, new) + + assert [(change.path, change.kind) for change in changes] == [ + ('b', ChangeKind.CHANGED), + ('c', ChangeKind.REMOVED), + ('d', ChangeKind.ADDED), + ] + + +def test_diff_of_identical_snapshots_is_empty() -> None: + assert diff_replies([text('a', 'same')], [text('a', 'same')]) == [] + + +def test_diff_ignores_the_stored_label_since_it_is_not_part_of_the_value() -> None: + old = StoredReply('a', ReplyType.ANSWER, uuid_value=UUID(YES), display_text='Yes') + new = StoredReply('a', ReplyType.ANSWER, uuid_value=UUID(YES), display_text='Ano') + + assert diff_replies([old], [new]) == [] + + +def test_diff_sees_a_reordered_item_list_as_a_change() -> None: + old = StoredReply('l', ReplyType.ITEM_LIST, uuid_values=(UUID(ITEM_1), UUID(ITEM_2))) + new = StoredReply('l', ReplyType.ITEM_LIST, uuid_values=(UUID(ITEM_2), UUID(ITEM_1))) + + assert [change.kind for change in diff_replies([old], [new])] == [ChangeKind.CHANGED] + + +def test_describes_a_changed_text_with_titles_values_and_who_changed_it() -> None: + old = {'c1.plain': reply('StringReply', 'before')} + new = {'c1.plain': reply('StringReply', 'after', by=USER)} + + [change] = describe(old, new) + + assert (change.kind, change.chapter_title, change.question_title) == (ChangeKind.CHANGED, 'Data', 'Notes') + assert (change.old_value, change.new_value) == ('before', 'after') + assert (change.changed_by, change.changed_at) == ('Ada Lovelace', '2026-11-20T10:00:00Z') + + +def test_describes_answers_by_their_labels() -> None: + [change] = describe({'c1.opt': reply('AnswerReply', YES)}, {'c1.opt': reply('AnswerReply', NO)}) + + assert (change.old_value, change.new_value) == ('Yes', 'No') + + +def test_a_removed_answer_has_no_new_value_and_no_author() -> None: + [change] = describe({'c1.plain': reply('StringReply', 'before')}, {}) + + assert (change.kind, change.old_value, change.new_value) == (ChangeKind.REMOVED, 'before', None) + assert (change.changed_by, change.changed_at) == (None, None) + + +def test_an_answer_the_knowledge_model_no_longer_has_falls_back_to_the_stored_label() -> None: + km_without_yes = copy.deepcopy(KM) + del km_without_yes['entities']['answers'][YES] + + [change] = describe({'c1.opt': reply('AnswerReply', YES)}, {'c1.opt': reply('AnswerReply', NO)}, km_without_yes) + + assert change.old_value == 'Yes' + + +def test_a_question_inside_a_list_item_is_described_with_the_title_of_the_item() -> None: + old = {'c1.items': reply('ItemListReply', [ITEM_1]), f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey')} + new = { + **old, + f'c1.items.{ITEM_1}.fmt': reply('StringReply', 'csv'), + } + + [change] = describe(old, new) + + assert (change.kind, change.question_title, change.context) == (ChangeKind.ADDED, 'Format', ['Survey']) + + +def test_an_added_item_is_described_by_the_titles_of_the_items() -> None: + old = {'c1.items': reply('ItemListReply', [ITEM_1]), f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey')} + new = { + 'c1.items': reply('ItemListReply', [ITEM_1, ITEM_2]), + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey'), + f'c1.items.{ITEM_2}.name': reply('StringReply', 'Interviews'), + } + + changes = {change.path: change for change in describe(old, new)} + + assert changes['c1.items'].old_value == 'Survey' + assert changes['c1.items'].new_value == 'Survey, Interviews' + assert changes[f'c1.items.{ITEM_2}.name'].kind == ChangeKind.ADDED + + +def test_an_item_without_a_title_answer_is_called_untitled() -> None: + new = {'c1.items': reply('ItemListReply', [ITEM_1])} + + [change] = describe({}, new) + + assert change.new_value == 'Untitled item' + + +def test_an_item_select_is_described_by_the_title_of_the_selected_item() -> None: + items = {'c1.items': reply('ItemListReply', [ITEM_1, ITEM_2])} + titles = { + f'c1.items.{ITEM_1}.name': reply('StringReply', 'Survey'), + f'c1.items.{ITEM_2}.name': reply('StringReply', 'Interviews'), + } + old = {**items, **titles, 'c1.pick': reply('ItemSelectReply', ITEM_1)} + new = {**items, **titles, 'c1.pick': reply('ItemSelectReply', ITEM_2)} + + [change] = describe(old, new) + + assert (change.old_value, change.new_value) == ('Survey', 'Interviews') + + +def test_nothing_is_reported_when_only_unreachable_replies_differ() -> None: + old = {'c1.opt': reply('AnswerReply', NO)} + new = {'c1.opt': reply('AnswerReply', NO), f'c1.opt.{YES}.why': reply('StringReply', 'left over')} + + assert describe(old, new) == [] diff --git a/service/tests/knowledgemodel/test_questionnaire_snapshot.py b/service/tests/knowledgemodel/test_questionnaire_snapshot.py new file mode 100644 index 0000000..31c1928 --- /dev/null +++ b/service/tests/knowledgemodel/test_questionnaire_snapshot.py @@ -0,0 +1,114 @@ +from typing import Any +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( + ReplyType, + StoredReply, + build_snapshot, +) + + +def u(number: int) -> str: + return str(UUID(int=number)) + + +YES, NO = u(1), u(2) +CSV, JSON = u(3), u(4) +ITEM_1, ITEM_2 = u(5), u(6) + +KM = { + 'chapterUuids': ['c1'], + 'entities': { + 'chapters': {'c1': {'title': 'Data', 'questionUuids': ['opt', 'multi', 'items', 'plain', 'integ', 'file']}}, + 'questions': { + 'opt': {'questionType': 'OptionsQuestion', 'title': 'Reuse?'}, + 'why': {'questionType': 'ValueQuestion', 'title': 'Why'}, + 'multi': {'questionType': 'MultiChoiceQuestion', 'title': 'Formats'}, + 'items': {'questionType': 'ListQuestion', 'title': 'Datasets', 'itemTemplateQuestionUuids': ['name']}, + 'name': {'questionType': 'ValueQuestion', 'title': 'Name'}, + 'plain': {'questionType': 'ValueQuestion', 'title': 'Notes'}, + 'integ': {'questionType': 'IntegrationQuestion', 'title': 'Repository'}, + 'file': {'questionType': 'FileQuestion', 'title': 'Attachment'}, + }, + 'answers': { + YES: {'label': 'Yes', 'followUpUuids': ['why']}, + NO: {'label': 'No', 'followUpUuids': []}, + }, + 'choices': {CSV: {'label': 'CSV'}, JSON: {'label': 'JSON'}}, + }, +} + + +def reply(reply_type: str, value: Any) -> dict[str, Any]: + return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': None} + + +def test_stores_string_replies() -> None: + snapshot = build_snapshot(KM, {'c1.plain': reply('StringReply', 'Some notes')}) + + assert snapshot == [StoredReply('c1.plain', ReplyType.STRING, text_value='Some notes')] + + +def test_stores_the_display_value_of_integration_replies_without_the_raw_payload() -> None: + integration = reply('IntegrationReply', {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': 1}}) + + assert build_snapshot(KM, {'c1.integ': integration}) == [ + StoredReply('c1.integ', ReplyType.INTEGRATION, text_value='Zenodo'), + ] + + +def test_stores_the_selected_answer_with_its_label() -> None: + assert build_snapshot(KM, {'c1.opt': reply('AnswerReply', YES)}) == [ + StoredReply('c1.opt', ReplyType.ANSWER, uuid_value=UUID(YES), display_text='Yes'), + ] + + +def test_stores_selected_choices_in_order_with_their_labels() -> None: + assert build_snapshot(KM, {'c1.multi': reply('MultiChoiceReply', [JSON, CSV])}) == [ + StoredReply('c1.multi', ReplyType.MULTI_CHOICE, uuid_values=(UUID(JSON), UUID(CSV)), display_text='JSON, CSV'), + ] + + +def test_stores_list_items_in_order() -> None: + snapshot = build_snapshot(KM, {'c1.items': reply('ItemListReply', [ITEM_2, ITEM_1])}) + + assert snapshot == [StoredReply('c1.items', ReplyType.ITEM_LIST, uuid_values=(UUID(ITEM_2), UUID(ITEM_1)))] + + +def test_leaves_out_empty_replies() -> None: + replies = { + 'c1.plain': reply('StringReply', ' '), + 'c1.multi': reply('MultiChoiceReply', []), + 'c1.items': reply('ItemListReply', []), + } + + assert build_snapshot(KM, replies) == [] + + +def test_leaves_out_file_replies() -> None: + assert build_snapshot(KM, {'c1.file': reply('FileReply', u(9))}) == [] + + +def test_leaves_out_unreachable_replies() -> None: + replies = { + 'c1.opt': reply('AnswerReply', NO), + f'c1.opt.{YES}.why': reply('StringReply', 'left over from an earlier answer'), + f'c1.items.{ITEM_1}.name': reply('StringReply', 'item of a list without items'), + } + + assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.opt'] + + +def test_skips_a_reply_that_cannot_be_read_and_keeps_the_others() -> None: + replies = { + 'c1.opt': reply('AnswerReply', 'not-a-uuid'), + 'c1.plain': reply('StringReply', 'kept'), + } + + assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.plain'] + + +def test_orders_the_snapshot_by_path() -> None: + replies = {'c1.plain': reply('StringReply', 'b'), 'c1.opt': reply('AnswerReply', NO)} + + assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.opt', 'c1.plain'] diff --git a/service/tests/knowledgemodel/test_reachable_replies.py b/service/tests/knowledgemodel/test_reachable_replies.py new file mode 100644 index 0000000..0ab7650 --- /dev/null +++ b/service/tests/knowledgemodel/test_reachable_replies.py @@ -0,0 +1,125 @@ +from typing import Any + +from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies + +# c1 +# opt (options): a1 -> f1 (value), a2 -> f2 (value) +# items (list): item template t1 (value) and nested (list) with item template n1 (value) +# plain (value) +KM = { + 'chapterUuids': ['c1'], + 'entities': { + 'chapters': {'c1': {'questionUuids': ['opt', 'items', 'plain']}}, + 'questions': { + 'opt': {'questionType': 'OptionsQuestion', 'answerUuids': ['a1', 'a2']}, + 'f1': {'questionType': 'ValueQuestion'}, + 'f2': {'questionType': 'ValueQuestion'}, + 'items': {'questionType': 'ListQuestion', 'itemTemplateQuestionUuids': ['t1', 'nested']}, + 't1': {'questionType': 'ValueQuestion'}, + 'nested': {'questionType': 'ListQuestion', 'itemTemplateQuestionUuids': ['n1']}, + 'n1': {'questionType': 'ValueQuestion'}, + 'plain': {'questionType': 'ValueQuestion'}, + }, + 'answers': { + 'a1': {'followUpUuids': ['f1']}, + 'a2': {'followUpUuids': ['f2']}, + }, + }, +} + + +def _reply(reply_type: str, value: Any) -> dict[str, Any]: + return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': None} + + +def _text(value: str) -> dict[str, Any]: + return _reply('StringReply', value) + + +def test_keeps_a_reply_of_a_chapter_question() -> None: + replies = {'c1.plain': _text('kept')} + + assert reachable_replies(KM, replies) == replies + + +def test_keeps_the_order_of_the_replies() -> None: + replies = { + 'c1.items.i2.t1': _text('second item'), + 'c1.plain': _text('plain'), + 'c1.items': _reply('ItemListReply', ['i1', 'i2']), + 'c1.items.i1.t1': _text('first item'), + } + + assert list(reachable_replies(KM, replies)) == list(replies) + + +def test_keeps_the_reply_object_untouched() -> None: + replies = {'c1.plain': _text('kept')} + + assert reachable_replies(KM, replies)['c1.plain'] is replies['c1.plain'] + + +def test_keeps_follow_ups_of_the_selected_answer_only() -> None: + replies = { + 'c1.opt': _reply('AnswerReply', 'a1'), + 'c1.opt.a1.f1': _text('applies'), + 'c1.opt.a2.f2': _text('left over from an earlier answer'), + } + + assert set(reachable_replies(KM, replies)) == {'c1.opt', 'c1.opt.a1.f1'} + + +def test_follow_ups_of_an_unanswered_options_question_are_unreachable() -> None: + replies = {'c1.opt.a1.f1': _text('left over')} + + assert reachable_replies(KM, replies) == {} + + +def test_follow_ups_are_unreachable_when_the_options_reply_has_another_type() -> None: + replies = {'c1.opt': _text('not an answer'), 'c1.opt.a1.f1': _text('left over')} + + assert set(reachable_replies(KM, replies)) == {'c1.opt'} + + +def test_keeps_replies_of_listed_items_only() -> None: + replies = { + 'c1.items': _reply('ItemListReply', ['i1']), + 'c1.items.i1.t1': _text('listed'), + 'c1.items.i2.t1': _text('deleted item'), + } + + assert set(reachable_replies(KM, replies)) == {'c1.items', 'c1.items.i1.t1'} + + +def test_a_list_without_a_reply_has_no_reachable_items() -> None: + replies = {'c1.items.i1.t1': _text('left over')} + + assert reachable_replies(KM, replies) == {} + + +def test_follows_lists_nested_in_items() -> None: + replies = { + 'c1.items': _reply('ItemListReply', ['i1', 'i2']), + 'c1.items.i1.nested': _reply('ItemListReply', ['n']), + 'c1.items.i1.nested.n.n1': _text('listed'), + 'c1.items.i1.nested.gone.n1': _text('deleted nested item'), + 'c1.items.i2.nested.n.n1': _text('item i2 has no nested list reply'), + } + + assert set(reachable_replies(KM, replies)) == { + 'c1.items', + 'c1.items.i1.nested', + 'c1.items.i1.nested.n.n1', + } + + +def test_drops_a_reply_to_a_question_that_is_not_in_the_knowledge_model() -> None: + replies = {'c1.removed': _text('question no longer exists'), 'c1.plain': _text('kept')} + + assert set(reachable_replies(KM, replies)) == {'c1.plain'} + + +def test_drops_a_reply_under_the_wrong_chapter() -> None: + replies = {'other.plain': _text('wrong chapter')} + + assert reachable_replies(KM, replies) == {} From 403a29cc6c07913e70eaae63dcc131afd1a32e7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Frnka?= Date: Wed, 25 Nov 2026 11:51:57 +0100 Subject: [PATCH 02/10] TMP --- .../ai/knowledgemodel/questionnaire_diff.py | 55 ++++--- .../knowledgemodel/questionnaire_snapshot.py | 136 +++++++----------- .../ai/persistence/database.py | 16 +-- .../ai/persistence/schema.py | 23 +-- ...261120_02_create_generation_reply_table.py | 22 +-- .../knowledgemodel/test_questionnaire_diff.py | 35 +++-- .../test_questionnaire_snapshot.py | 37 ++--- 7 files changed, 135 insertions(+), 189 deletions(-) diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py index 7666711..6561dd8 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_diff.py @@ -4,13 +4,8 @@ from dataclasses import dataclass from enum import StrEnum from typing import Any -from uuid import UUID -from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( - ReplyType, - StoredReply, - build_snapshot, -) +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies MAX_ITEM_TITLE_LENGTH = 80 @@ -119,14 +114,15 @@ def _user_name(user: dict[str, Any] | None) -> str | None: return name or None -def _item_title(km: dict[str, Any], list_path: str, item_uuid: UUID | str, side: Mapping[str, StoredReply]) -> str: +def _item_title(km: dict[str, Any], list_path: str, item_uuid: str, side: Mapping[str, StoredReply]) -> str: """An item has no title of its own: it is the answer to the first question of the list's item template.""" list_question = _questions(km).get(list_path.rsplit('.', 1)[-1], {}) templates = list_question.get('itemTemplateQuestionUuids', []) if templates: first = side.get(f'{list_path}.{item_uuid}.{templates[0]}') - if first is not None and first.text_value: - title = first.text_value.strip().splitlines()[0] + text = _text(first) if first is not None else None + if text and text.strip(): + title = text.strip().splitlines()[0] if len(title) > MAX_ITEM_TITLE_LENGTH: return title[: MAX_ITEM_TITLE_LENGTH - 1] + '…' return title @@ -145,26 +141,41 @@ def _item_context(km: dict[str, Any], path: str, side: Mapping[str, StoredReply] return context -def _label(km: dict[str, Any], kind: str, uuid: UUID) -> str | None: - label = km['entities'].get(kind, {}).get(str(uuid), {}).get('label') +def _label(km: dict[str, Any], kind: str, uuid: object) -> str | None: + if not isinstance(uuid, str): + return None + label = km['entities'].get(kind, {}).get(uuid, {}).get('label') return label if isinstance(label, str) else None +def _strings(raw: object) -> list[str]: + """The UUIDs of a multi-choice or item-list reply.""" + return [value for value in raw if isinstance(value, str)] if isinstance(raw, list) else [] + + +def _text(reply: StoredReply) -> str | None: + """The text of a string reply, or the text an integration reply shows.""" + raw = reply.raw + if reply.reply_type == 'IntegrationReply' and isinstance(raw, dict): + raw = raw.get('value') + return raw if isinstance(raw, str) else None + + def _describe_value(reply: StoredReply, km: dict[str, Any], side: Mapping[str, StoredReply]) -> str: - if reply.reply_type == ReplyType.ANSWER: - return _label(km, 'answers', reply.uuid_value) or reply.display_text or REMOVED_OPTION - if reply.reply_type == ReplyType.MULTI_CHOICE: + if reply.reply_type == 'AnswerReply': + return _label(km, 'answers', reply.raw) or reply.display_text or REMOVED_OPTION + if reply.reply_type == 'MultiChoiceReply': return _describe_choices(reply, km) - if reply.reply_type == ReplyType.ITEM_SELECT: + if reply.reply_type == 'ItemSelectReply': return _describe_selected_item(reply, km, side) - if reply.reply_type == ReplyType.ITEM_LIST: - return ', '.join(_item_title(km, reply.path, item_uuid, side) for item_uuid in reply.uuid_values or ()) - return reply.text_value or '' + if reply.reply_type == 'ItemListReply': + return ', '.join(_item_title(km, reply.path, item_uuid, side) for item_uuid in _strings(reply.raw)) + return _text(reply) or '' def _describe_choices(reply: StoredReply, km: dict[str, Any]) -> str: - labels = [_label(km, 'choices', choice) for choice in reply.uuid_values or ()] - if all(labels): + labels = [_label(km, 'choices', choice) for choice in _strings(reply.raw)] + if labels and all(labels): return ', '.join(label for label in labels if label) return reply.display_text or REMOVED_OPTION @@ -173,7 +184,7 @@ def _describe_selected_item(reply: StoredReply, km: dict[str, Any], side: Mappin """An item-select reply names an item of another list; its title is looked up there.""" question = _questions(km).get(reply.path.rsplit('.', 1)[-1], {}) list_question_uuid = question.get('listQuestionUuid') - if not list_question_uuid or reply.uuid_value is None: + if not list_question_uuid or not isinstance(reply.raw, str): return 'Untitled item' list_path = f'{reply.path.rsplit(".", 1)[0]}.{list_question_uuid}' - return _item_title(km, list_path, reply.uuid_value, side) + return _item_title(km, list_path, reply.raw, side) diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py index 5481ef5..44f45b1 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/questionnaire_snapshot.py @@ -1,130 +1,90 @@ """The replies of a questionnaire in the form they are stored with a generation. -Only replies that apply to the questionnaire as it stands are kept (see ``reachable_replies``), as typed values: -what DSW sends as ``{type, value}`` becomes one of the fields of ``StoredReply``. Replies that are empty, and -replies of types that never reach a document (files), are left out, so that an empty reply and a missing one are -the same thing when two snapshots are compared. +Only replies that apply to the questionnaire as it stands are kept (see ``reachable_replies``), each with its value +exactly as DSW sends it (``{type, value}``), so that anything in a reply that can reach the document is compared. +Replies that are empty, and replies of types that never reach a document (files), are left out, so that an empty +reply and a missing one are the same thing when two snapshots are compared. """ import logging from dataclasses import dataclass -from enum import StrEnum from typing import Any -from uuid import UUID from ai_document_plugin_service.ai.knowledgemodel.reachable_replies import reachable_replies logger = logging.getLogger(__name__) - -class ReplyType(StrEnum): - """Stored in the database; changing a value requires a migration.""" - - STRING = 'string' - INTEGRATION = 'integration' - ANSWER = 'answer' - ITEM_SELECT = 'item_select' - MULTI_CHOICE = 'multi_choice' - ITEM_LIST = 'item_list' +# Reply types whose value never reaches a document. +_LEFT_OUT_REPLY_TYPES = frozenset({'FileReply'}) @dataclass(frozen=True) class StoredReply: - """One reply. Exactly one of the three value fields is set, which one depends on the type: - - - ``text_value``: string and integration replies. - - ``uuid_value``: answer replies (the selected answer) and item-select replies (the selected item). - - ``uuid_values``: multi-choice replies (the selected choices) and item-list replies (the items, in order). - """ + """One reply.""" path: str - reply_type: ReplyType - text_value: str | None = None - uuid_value: UUID | None = None - uuid_values: tuple[UUID, ...] | None = None + # The value of the reply as DSW sends it, e.g. ``{'type': 'AnswerReply', 'value': ''}``. + value: dict[str, Any] # What the value was called when it was stored, for answers and choices whose label can no longer be looked # up later, e.g. after the knowledge model changed. Not part of the value. display_text: str | None = None + @property + def reply_type(self) -> str | None: + reply_type = self.value.get('type') + return reply_type if isinstance(reply_type, str) else None + + @property + def raw(self) -> object: + """The ``value`` inside the value: text, a UUID, a list of UUIDs or, for integrations, a mapping.""" + return self.value.get('value') + def same_value_as(self, other: 'StoredReply') -> bool: - return (self.reply_type, self.text_value, self.uuid_value, self.uuid_values) == ( - other.reply_type, - other.text_value, - other.uuid_value, - other.uuid_values, - ) + return self.value == other.value def build_snapshot(km: dict[str, Any], replies: dict[str, Any]) -> list[StoredReply]: - """The reachable replies of a questionnaire, typed, ordered by path. + """The reachable replies of a questionnaire, ordered by path. - ``km`` is the ``knowledgeModel`` of the questionnaire detail and ``replies`` its ``replies``. A reply that - cannot be read is skipped with a warning instead of failing the caller. + ``km`` is the ``knowledgeModel`` of the questionnaire detail and ``replies`` its ``replies``. A reply without + a typed value is skipped with a warning instead of failing the caller. """ + entities = km['entities'] snapshot: list[StoredReply] = [] for path, reply in sorted(reachable_replies(km, replies).items()): - try: - stored = _to_stored_reply(path, reply.get('value', {}), km['entities']) - except (KeyError, TypeError, ValueError, AttributeError): - logger.warning('Skipping a reply that cannot be stored', exc_info=True, extra={'reply_path': path}) + value = reply.get('value') + if not isinstance(value, dict) or not isinstance(value.get('type'), str): + logger.warning('Skipping a reply without a typed value', extra={'reply_path': path}) + continue + if value['type'] in _LEFT_OUT_REPLY_TYPES or _is_empty(value.get('value')): continue - if stored is not None and not _is_empty(stored): - snapshot.append(stored) + snapshot.append(StoredReply(path, value, _display_text(value, entities))) return snapshot -def _to_stored_reply(path: str, value: dict[str, Any], entities: dict[str, Any]) -> StoredReply | None: - reply_type = value.get('type') - raw = value.get('value') +def _is_empty(raw: object) -> bool: + if raw is None: + return True + if isinstance(raw, str): + return not raw.strip() + if isinstance(raw, list): + return not raw + if isinstance(raw, dict): + # An integration reply: ``{type, value, raw?}``, empty when it has neither text nor a record. + return _is_empty(raw.get('value')) and not raw.get('raw') + return False - if reply_type == 'StringReply': - return StoredReply(path, ReplyType.STRING, text_value=_as_text(raw)) - if reply_type == 'IntegrationReply': - return StoredReply(path, ReplyType.INTEGRATION, text_value=_as_text(raw['value'])) - if reply_type in {'AnswerReply', 'ItemSelectReply'}: - return _single_uuid_reply(path, reply_type, raw, entities) - if reply_type in {'MultiChoiceReply', 'ItemListReply'}: - return _multiple_uuids_reply(path, reply_type, raw, entities) - if reply_type != 'FileReply': - logger.warning('Skipping a reply of an unknown type', extra={'reply_path': path, 'reply_type': reply_type}) +def _display_text(value: dict[str, Any], entities: dict[str, Any]) -> str | None: + reply_type, raw = value['type'], value.get('value') + if reply_type == 'AnswerReply' and isinstance(raw, str): + return _label(entities, 'answers', raw) + if reply_type == 'MultiChoiceReply' and isinstance(raw, list): + labels = [_label(entities, 'choices', choice) for choice in raw if isinstance(choice, str)] + return ', '.join(label for label in labels if label) or None return None -def _single_uuid_reply(path: str, reply_type: str, raw: str, entities: dict[str, Any]) -> StoredReply: - if reply_type == 'AnswerReply': - return StoredReply(path, ReplyType.ANSWER, uuid_value=UUID(raw), display_text=_label(entities, 'answers', raw)) - return StoredReply(path, ReplyType.ITEM_SELECT, uuid_value=UUID(raw)) - - -def _multiple_uuids_reply(path: str, reply_type: str, raw: list[str], entities: dict[str, Any]) -> StoredReply: - uuids = tuple(UUID(value) for value in raw) - if reply_type == 'ItemListReply': - return StoredReply(path, ReplyType.ITEM_LIST, uuid_values=uuids) - labels = [_label(entities, 'choices', value) for value in raw] - return StoredReply( - path, - ReplyType.MULTI_CHOICE, - uuid_values=uuids, - display_text=', '.join(label for label in labels if label) or None, - ) - - -def _as_text(value: object) -> str: - if not isinstance(value, str): - msg = 'Expected a text reply value' - raise TypeError(msg) - return value - - def _label(entities: dict[str, Any], kind: str, uuid: str) -> str | None: label = entities.get(kind, {}).get(uuid, {}).get('label') return label if isinstance(label, str) else None - - -def _is_empty(reply: StoredReply) -> bool: - if reply.text_value is not None: - return not reply.text_value.strip() - if reply.uuid_values is not None: - return not reply.uuid_values - return False diff --git a/service/src/ai_document_plugin_service/ai/persistence/database.py b/service/src/ai_document_plugin_service/ai/persistence/database.py index 3bcd262..e335cac 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/database.py +++ b/service/src/ai_document_plugin_service/ai/persistence/database.py @@ -18,7 +18,7 @@ from ai_document_plugin_service.ai.assignment.types import SectionQuestionPaths from ai_document_plugin_service.ai.common.config import DatabaseConfig, LLMConfig from ai_document_plugin_service.ai.common.types import TemplateContent -from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ReplyType, StoredReply +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply from ai_document_plugin_service.ai.persistence.errors import TemplateTitleConflictError from ai_document_plugin_service.ai.persistence.schema import create_persistence_schema from ai_document_plugin_service.ai.persistence.secret_cipher import SecretCipher @@ -822,10 +822,7 @@ async def save_generation_replies(self, run_id: UUID, replies: Sequence[StoredRe { 'run_id': run_id, 'path': reply.path, - 'reply_type': reply.reply_type.value, - 'text_value': reply.text_value, - 'uuid_value': reply.uuid_value, - 'uuid_values': list(reply.uuid_values) if reply.uuid_values is not None else None, + 'value': reply.value, 'display_text': reply.display_text, } for reply in replies @@ -844,14 +841,7 @@ async def get_generation_replies(self, run_id: UUID) -> list[StoredReply]: rows = result.fetchall() return [ - StoredReply( - path=row.path, - reply_type=ReplyType(row.reply_type), - text_value=row.text_value, - uuid_value=row.uuid_value, - uuid_values=tuple(row.uuid_values) if row.uuid_values is not None else None, - display_text=row.display_text, - ) + StoredReply(path=row.path, value=row.value, display_text=row.display_text) for row in rows ] diff --git a/service/src/ai_document_plugin_service/ai/persistence/schema.py b/service/src/ai_document_plugin_service/ai/persistence/schema.py index 1b15bfc..d7d1a16 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/schema.py +++ b/service/src/ai_document_plugin_service/ai/persistence/schema.py @@ -2,7 +2,6 @@ from sqlalchemy import ( JSON, - CheckConstraint, Column, DateTime, ForeignKey, @@ -15,7 +14,7 @@ func, text, ) -from sqlalchemy.dialects.postgresql import ARRAY, UUID +from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID @dataclass(frozen=True) @@ -175,25 +174,9 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: metadata, Column('run_id', UUID(as_uuid=True), ForeignKey('generation.run_id', ondelete='CASCADE'), primary_key=True), Column('path', Text, primary_key=True), - Column('reply_type', Text, nullable=False), - # Which one is set depends on the reply type, see StoredReply. - Column('text_value', Text, nullable=True), - Column('uuid_value', UUID(as_uuid=True), nullable=True), - Column('uuid_values', ARRAY(UUID(as_uuid=True)), nullable=True), + # The value of the reply as DSW sends it (``{type, value}``), see StoredReply. + Column('value', JSONB, nullable=False), Column('display_text', Text, nullable=True), - CheckConstraint( - "reply_type IN ('string', 'integration', 'answer', 'item_select', 'multi_choice', 'item_list')", - name='ck_generation_reply_type', - ), - CheckConstraint( - "(reply_type IN ('string', 'integration')" - ' AND text_value IS NOT NULL AND uuid_value IS NULL AND uuid_values IS NULL)' - " OR (reply_type IN ('answer', 'item_select')" - ' AND uuid_value IS NOT NULL AND text_value IS NULL AND uuid_values IS NULL)' - " OR (reply_type IN ('multi_choice', 'item_list')" - ' AND uuid_values IS NOT NULL AND text_value IS NULL AND uuid_value IS NULL)', - name='ck_generation_reply_value', - ), ) # LLM connection settings, one row per tenant. Managed by tenant administrators. diff --git a/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py b/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py index 637d649..5528bd1 100644 --- a/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py +++ b/service/src/ai_document_plugin_service/migrations/versions/20261120_02_create_generation_reply_table.py @@ -1,7 +1,7 @@ """Store the replies a run was generated from. -One row per reply, typed by reply type (see questionnaire_snapshot), so that what changed in the questionnaire -since the run can be told. Existing runs have no rows; generation.source_event_uuid being NULL marks them. +One row per reply with its value as DSW sends it (see questionnaire_snapshot), so that what changed in the +questionnaire since the run can be told. Existing runs have no rows; generation.source_event_uuid being NULL marks them. Revision ID: 20261120_02 Revises: 20261120_01 @@ -31,10 +31,7 @@ def upgrade() -> None: 'generation_reply', sa.Column('run_id', postgresql.UUID(as_uuid=True), nullable=False), sa.Column('path', sa.Text(), nullable=False), - sa.Column('reply_type', sa.Text(), nullable=False), - sa.Column('text_value', sa.Text(), nullable=True), - sa.Column('uuid_value', postgresql.UUID(as_uuid=True), nullable=True), - sa.Column('uuid_values', postgresql.ARRAY(postgresql.UUID(as_uuid=True)), nullable=True), + sa.Column('value', postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.Column('display_text', sa.Text(), nullable=True), sa.PrimaryKeyConstraint('run_id', 'path', name='pk_generation_reply'), sa.ForeignKeyConstraint( @@ -43,18 +40,5 @@ def upgrade() -> None: name='fk_generation_reply_run_id', ondelete='CASCADE', ), - sa.CheckConstraint( - "reply_type IN ('string', 'integration', 'answer', 'item_select', 'multi_choice', 'item_list')", - name='ck_generation_reply_type', - ), - sa.CheckConstraint( - "(reply_type IN ('string', 'integration')" - ' AND text_value IS NOT NULL AND uuid_value IS NULL AND uuid_values IS NULL)' - " OR (reply_type IN ('answer', 'item_select')" - ' AND uuid_value IS NOT NULL AND text_value IS NULL AND uuid_values IS NULL)' - " OR (reply_type IN ('multi_choice', 'item_list')" - ' AND uuid_values IS NOT NULL AND text_value IS NULL AND uuid_value IS NULL)', - name='ck_generation_reply_value', - ), schema=schema, ) diff --git a/service/tests/knowledgemodel/test_questionnaire_diff.py b/service/tests/knowledgemodel/test_questionnaire_diff.py index cecfbc2..a829529 100644 --- a/service/tests/knowledgemodel/test_questionnaire_diff.py +++ b/service/tests/knowledgemodel/test_questionnaire_diff.py @@ -7,11 +7,7 @@ describe_changes, diff_replies, ) -from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( - ReplyType, - StoredReply, - build_snapshot, -) +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot def u(number: int) -> str: @@ -45,7 +41,7 @@ def reply(reply_type: str, value: Any, by: dict[str, str] | None = None) -> dict def text(path: str, value: str) -> StoredReply: - return StoredReply(path, ReplyType.STRING, text_value=value) + return StoredReply(path, {'type': 'StringReply', 'value': value}) def describe(old_replies: dict[str, Any], new_replies: dict[str, Any], km: dict[str, Any] | None = None) -> list: @@ -71,15 +67,25 @@ def test_diff_of_identical_snapshots_is_empty() -> None: def test_diff_ignores_the_stored_label_since_it_is_not_part_of_the_value() -> None: - old = StoredReply('a', ReplyType.ANSWER, uuid_value=UUID(YES), display_text='Yes') - new = StoredReply('a', ReplyType.ANSWER, uuid_value=UUID(YES), display_text='Ano') + old = StoredReply('a', {'type': 'AnswerReply', 'value': YES}, display_text='Yes') + new = StoredReply('a', {'type': 'AnswerReply', 'value': YES}, display_text='Ano') assert diff_replies([old], [new]) == [] def test_diff_sees_a_reordered_item_list_as_a_change() -> None: - old = StoredReply('l', ReplyType.ITEM_LIST, uuid_values=(UUID(ITEM_1), UUID(ITEM_2))) - new = StoredReply('l', ReplyType.ITEM_LIST, uuid_values=(UUID(ITEM_2), UUID(ITEM_1))) + old = StoredReply('l', {'type': 'ItemListReply', 'value': [ITEM_1, ITEM_2]}) + new = StoredReply('l', {'type': 'ItemListReply', 'value': [ITEM_2, ITEM_1]}) + + assert [change.kind for change in diff_replies([old], [new])] == [ChangeKind.CHANGED] + + +def test_diff_sees_a_changed_integration_record_with_the_same_text_as_a_change() -> None: + def zenodo(record_id: int) -> StoredReply: + value = {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': record_id}} + return StoredReply('i', {'type': 'IntegrationReply', 'value': value}) + + old, new = zenodo(1), zenodo(2) assert [change.kind for change in diff_replies([old], [new])] == [ChangeKind.CHANGED] @@ -95,6 +101,15 @@ def test_describes_a_changed_text_with_titles_values_and_who_changed_it() -> Non assert (change.changed_by, change.changed_at) == ('Ada Lovelace', '2026-11-20T10:00:00Z') +def test_describes_integration_replies_by_their_text() -> None: + old = {'c1.plain': reply('IntegrationReply', {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': 1}})} + new = {'c1.plain': reply('IntegrationReply', {'type': 'PlainType', 'value': 'Dryad'})} + + [change] = describe(old, new) + + assert (change.old_value, change.new_value) == ('Zenodo', 'Dryad') + + def test_describes_answers_by_their_labels() -> None: [change] = describe({'c1.opt': reply('AnswerReply', YES)}, {'c1.opt': reply('AnswerReply', NO)}) diff --git a/service/tests/knowledgemodel/test_questionnaire_snapshot.py b/service/tests/knowledgemodel/test_questionnaire_snapshot.py index 31c1928..f733f1a 100644 --- a/service/tests/knowledgemodel/test_questionnaire_snapshot.py +++ b/service/tests/knowledgemodel/test_questionnaire_snapshot.py @@ -1,11 +1,7 @@ from typing import Any from uuid import UUID -from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import ( - ReplyType, - StoredReply, - build_snapshot, -) +from ai_document_plugin_service.ai.knowledgemodel.questionnaire_snapshot import StoredReply, build_snapshot def u(number: int) -> str: @@ -43,36 +39,42 @@ def reply(reply_type: str, value: Any) -> dict[str, Any]: return {'value': {'type': reply_type, 'value': value}, 'createdAt': '2026-11-20T10:00:00Z', 'createdBy': None} -def test_stores_string_replies() -> None: +def test_stores_the_value_as_dsw_sends_it_without_who_made_it_and_when() -> None: snapshot = build_snapshot(KM, {'c1.plain': reply('StringReply', 'Some notes')}) - assert snapshot == [StoredReply('c1.plain', ReplyType.STRING, text_value='Some notes')] + assert snapshot == [StoredReply('c1.plain', {'type': 'StringReply', 'value': 'Some notes'})] -def test_stores_the_display_value_of_integration_replies_without_the_raw_payload() -> None: - integration = reply('IntegrationReply', {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': 1}}) +def test_stores_integration_replies_with_the_raw_payload() -> None: + value = {'type': 'IntegrationType', 'value': 'Zenodo', 'raw': {'id': 1}} - assert build_snapshot(KM, {'c1.integ': integration}) == [ - StoredReply('c1.integ', ReplyType.INTEGRATION, text_value='Zenodo'), + assert build_snapshot(KM, {'c1.integ': reply('IntegrationReply', value)}) == [ + StoredReply('c1.integ', {'type': 'IntegrationReply', 'value': value}), ] def test_stores_the_selected_answer_with_its_label() -> None: assert build_snapshot(KM, {'c1.opt': reply('AnswerReply', YES)}) == [ - StoredReply('c1.opt', ReplyType.ANSWER, uuid_value=UUID(YES), display_text='Yes'), + StoredReply('c1.opt', {'type': 'AnswerReply', 'value': YES}, display_text='Yes'), ] -def test_stores_selected_choices_in_order_with_their_labels() -> None: +def test_stores_selected_choices_with_their_labels() -> None: assert build_snapshot(KM, {'c1.multi': reply('MultiChoiceReply', [JSON, CSV])}) == [ - StoredReply('c1.multi', ReplyType.MULTI_CHOICE, uuid_values=(UUID(JSON), UUID(CSV)), display_text='JSON, CSV'), + StoredReply('c1.multi', {'type': 'MultiChoiceReply', 'value': [JSON, CSV]}, display_text='JSON, CSV'), ] def test_stores_list_items_in_order() -> None: snapshot = build_snapshot(KM, {'c1.items': reply('ItemListReply', [ITEM_2, ITEM_1])}) - assert snapshot == [StoredReply('c1.items', ReplyType.ITEM_LIST, uuid_values=(UUID(ITEM_2), UUID(ITEM_1)))] + assert snapshot == [StoredReply('c1.items', {'type': 'ItemListReply', 'value': [ITEM_2, ITEM_1]})] + + +def test_stores_replies_of_types_it_does_not_know() -> None: + snapshot = build_snapshot(KM, {'c1.plain': reply('FutureReply', {'anything': 1})}) + + assert snapshot == [StoredReply('c1.plain', {'type': 'FutureReply', 'value': {'anything': 1}})] def test_leaves_out_empty_replies() -> None: @@ -80,6 +82,7 @@ def test_leaves_out_empty_replies() -> None: 'c1.plain': reply('StringReply', ' '), 'c1.multi': reply('MultiChoiceReply', []), 'c1.items': reply('ItemListReply', []), + 'c1.integ': reply('IntegrationReply', {'type': 'PlainType', 'value': ''}), } assert build_snapshot(KM, replies) == [] @@ -99,9 +102,9 @@ def test_leaves_out_unreachable_replies() -> None: assert [stored.path for stored in build_snapshot(KM, replies)] == ['c1.opt'] -def test_skips_a_reply_that_cannot_be_read_and_keeps_the_others() -> None: +def test_skips_a_reply_without_a_type_and_keeps_the_others() -> None: replies = { - 'c1.opt': reply('AnswerReply', 'not-a-uuid'), + 'c1.multi': {'value': {'value': [CSV]}}, 'c1.plain': reply('StringReply', 'kept'), } From 82244770e13f341227577178b6be276dc0b0a543 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Frnka?= Date: Wed, 25 Nov 2026 14:30:04 +0100 Subject: [PATCH 03/10] Nest changes into a tree --- plugin/src/client.ts | 2 +- plugin/src/components/Modal.module.css | 9 + plugin/src/components/Modal.tsx | 7 +- .../components/QuestionnaireChangeBadge.tsx | 48 ----- .../QuestionnaireChangeNote.module.css | 38 ++++ .../components/QuestionnaireChangeNote.tsx | 43 ++++ .../QuestionnaireChangesModal.module.css | 117 +++++++---- .../components/QuestionnaireChangesModal.tsx | 151 +++++++------- plugin/src/components/RunDetailPanel.tsx | 4 +- plugin/src/types.ts | 26 ++- .../ai/knowledgemodel/questionnaire_diff.py | 190 ++++++++++++------ .../ai/knowledgemodel/reachable_replies.py | 13 +- .../ai_document_plugin_service/api/types.py | 27 ++- .../service/pipeline_service.py | 44 ++-- .../service/questionnaire_state_service.py | 15 +- .../knowledgemodel/test_questionnaire_diff.py | 187 +++++++++++++---- 16 files changed, 588 insertions(+), 333 deletions(-) delete mode 100644 plugin/src/components/QuestionnaireChangeBadge.tsx create mode 100644 plugin/src/components/QuestionnaireChangeNote.module.css create mode 100644 plugin/src/components/QuestionnaireChangeNote.tsx diff --git a/plugin/src/client.ts b/plugin/src/client.ts index 47f5aa5..6bae207 100644 --- a/plugin/src/client.ts +++ b/plugin/src/client.ts @@ -262,7 +262,7 @@ export const getQuestionnaireChanges = async ( ) } - if (!('changes' in data) || !Array.isArray(data.changes)) { + if (!('tree' in data) || !Array.isArray(data.tree)) { throw new Error('Invalid questionnaire changes returned.') } diff --git a/plugin/src/components/Modal.module.css b/plugin/src/components/Modal.module.css index cc1ffea..9bb5cf6 100644 --- a/plugin/src/components/Modal.module.css +++ b/plugin/src/components/Modal.module.css @@ -26,6 +26,15 @@ color: var(--ui-text); } +/* The body takes the height the header and footer leave, so the dialog does not resize with its content. */ +.fullHeight { + height: calc(100vh - 3.5rem); +} + +.fullHeight .body { + flex: 1; +} + .content:focus { outline: none; } diff --git a/plugin/src/components/Modal.tsx b/plugin/src/components/Modal.tsx index 834ffe2..6668d94 100644 --- a/plugin/src/components/Modal.tsx +++ b/plugin/src/components/Modal.tsx @@ -16,6 +16,8 @@ type ModalProps = { initialFocusRef?: RefObject /** Blocks closing, e.g. while the content is being saved. */ closeDisabled?: boolean + /** As tall as the window allows the whole time, so content that grows or shrinks does not resize it. */ + fullHeight?: boolean } /** @@ -38,6 +40,7 @@ export function Modal({ busy, initialFocusRef, closeDisabled = false, + fullHeight = false, }: ModalProps) { return ( { diff --git a/plugin/src/components/QuestionnaireChangeBadge.tsx b/plugin/src/components/QuestionnaireChangeBadge.tsx deleted file mode 100644 index 9d78694..0000000 --- a/plugin/src/components/QuestionnaireChangeBadge.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { Badge } from '@ds-wizard/plugin-sdk/ui/Badge' -import { Spinner } from '@ds-wizard/plugin-sdk/ui/Icon' -import { useState } from 'react' - -import { QuestionnaireChangesModal } from '@/components/QuestionnaireChangesModal' -import type { RunRecord } from '@/hooks/useGenerationHistory' -import { - isQuestionnaireChanged, - type LatestQuestionnaireEvent, -} from '@/hooks/useLatestQuestionnaireEvent' - -type QuestionnaireChangeBadgeProps = { - run: Pick - latestEvent: LatestQuestionnaireEvent -} - -/** - * A small badge saying whether the questionnaire answers may have changed since the document was generated. - * Clicking it lists what changed. - */ -export function QuestionnaireChangeBadge({ run, latestEvent }: QuestionnaireChangeBadgeProps) { - const [isOpen, setIsOpen] = useState(false) - - if (run.status !== 'succeeded') return null - - if (latestEvent.status === 'loading') { - return - } - - // Unchanged, or not verifiable (older run, DSW unreachable): nothing to show. - if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null - - return ( - <> - setIsOpen(true)} - > - Questionnaire changed after the DMP was generated - - {isOpen && ( - setIsOpen(false)} /> - )} - - ) -} diff --git a/plugin/src/components/QuestionnaireChangeNote.module.css b/plugin/src/components/QuestionnaireChangeNote.module.css new file mode 100644 index 0000000..cc1dd8c --- /dev/null +++ b/plugin/src/components/QuestionnaireChangeNote.module.css @@ -0,0 +1,38 @@ +/* A warning, like the wizard's warning badge, that is a button opening the list of changes. */ +.note { + display: flex; + align-items: center; + gap: var(--ui-space-2); + width: 100%; + padding: var(--ui-space-2) var(--ui-space-3); + border: 1px solid var(--ui-warning-border); + border-radius: var(--ui-radius-control); + background: var(--ui-warning-subtle); + color: var(--ui-warning-on-subtle); + font: inherit; + font-weight: 600; + text-align: start; + cursor: pointer; +} + +.note:hover { + filter: brightness(0.97); +} + +.note:focus-visible { + outline: var(--ui-focus-ring-width, 2px) solid var(--ui-focus-ring, currentColor); + outline-offset: var(--ui-focus-ring-offset, 2px); +} + +.text { + flex: 1; +} + +.action { + display: inline-flex; + align-items: center; + gap: 0.4rem; + font-size: 0.875rem; + text-decoration: underline; + white-space: nowrap; +} diff --git a/plugin/src/components/QuestionnaireChangeNote.tsx b/plugin/src/components/QuestionnaireChangeNote.tsx new file mode 100644 index 0000000..11df42c --- /dev/null +++ b/plugin/src/components/QuestionnaireChangeNote.tsx @@ -0,0 +1,43 @@ +import { useState } from 'react' + +import styles from '@/components/QuestionnaireChangeNote.module.css' +import { QuestionnaireChangesModal } from '@/components/QuestionnaireChangesModal' +import type { RunRecord } from '@/hooks/useGenerationHistory' +import { + isQuestionnaireChanged, + type LatestQuestionnaireEvent, +} from '@/hooks/useLatestQuestionnaireEvent' + +type QuestionnaireChangeNoteProps = { + run: Pick + latestEvent: LatestQuestionnaireEvent +} + +/** + * A note, shown when the questionnaire answers may have changed since the document was generated, that lists + * what changed when clicked. + */ +export function QuestionnaireChangeNote({ run, latestEvent }: QuestionnaireChangeNoteProps) { + const [isOpen, setIsOpen] = useState(false) + + if (run.status !== 'succeeded') return null + + // Still checking, unchanged, or not verifiable (older run, DSW unreachable): nothing to show. + if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null + + return ( + <> +