From 078368c63961a007ddb527edb78725df6c41a5dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Frnka?= Date: Fri, 20 Nov 2026 18:57:53 +0100 Subject: [PATCH 1/3] Added information about the questionnaire changing --- CHANGELOG.md | 2 + plugin/src/client.ts | 48 +++++++++++++++ plugin/src/components/ProjectTab.tsx | 8 ++- .../components/QuestionnaireChangeBadge.tsx | 39 +++++++++++++ plugin/src/components/RunDetailPanel.tsx | 6 +- plugin/src/hooks/useGenerationHistory.ts | 3 + .../src/hooks/useLatestQuestionnaireEvent.ts | 58 +++++++++++++++++++ plugin/src/types.ts | 3 + .../ai/knowledgemodel/dsw_client.py | 49 ++++++++++++++++ .../ai/persistence/database.py | 3 + .../ai/persistence/schema.py | 3 + .../ai_document_plugin_service/api/types.py | 3 + service/src/ai_document_plugin_service/di.py | 7 ++- ...61120_01_add_source_event_to_generation.py | 27 +++++++++ .../service/pipeline_service.py | 25 ++++++-- .../service/questionnaire_state_service.py | 18 ++++++ .../tests/service/test_pipeline_admission.py | 6 +- service/tests/service/test_pipeline_rename.py | 6 +- 18 files changed, 301 insertions(+), 13 deletions(-) create mode 100644 plugin/src/components/QuestionnaireChangeBadge.tsx create mode 100644 plugin/src/hooks/useLatestQuestionnaireEvent.ts create mode 100644 service/src/ai_document_plugin_service/migrations/versions/20261120_01_add_source_event_to_generation.py create mode 100644 service/src/ai_document_plugin_service/service/questionnaire_state_service.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b9b950c..3f1c9a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Added a note on a generated document when the questionnaire answers may have changed since it was generated + ## [0.5.1] - 2026-11-10 - Fixed the admin permission check to use the DSW 5.0 `settings.manage` permission (#221) diff --git a/plugin/src/client.ts b/plugin/src/client.ts index 417a15a..062287b 100644 --- a/plugin/src/client.ts +++ b/plugin/src/client.ts @@ -190,6 +190,54 @@ export const getPipelineStatus = async (runId: string): Promise => { + const { apiUrl, token } = getApiUrlAndToken() + if (!token) { + throw new Error("Failed to retrieve the current user's authentication token.") + } + if (!apiUrl) { + throw new Error('Failed to retrieve the DSW API URL.') + } + + const url = `${apiUrl.replace(/\/+$/, '')}/projects/${encodeURIComponent(questionnaireUuid)}/events?size=1&sort=createdAt,desc` + const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } }) + if (!response.ok) { + throw new Error(`Failed to load the latest questionnaire event (${response.status}).`) + } + + const data: unknown = await response.json() + if (!data || typeof data !== 'object') { + throw new Error('Invalid questionnaire events returned.') + } + + const embedded = '_embedded' in data ? data._embedded : undefined + const events = + embedded && typeof embedded === 'object' && 'projectEvents' in embedded + ? embedded.projectEvents + : undefined + if (!Array.isArray(events)) { + throw new Error('Invalid questionnaire events returned.') + } + if (events.length === 0) { + return NO_EVENTS_UUID + } + + const latest: unknown = events[0] + if (!latest || typeof latest !== 'object' || !('uuid' in latest) || typeof latest.uuid !== 'string') { + throw new Error('Invalid questionnaire event returned.') + } + return latest.uuid +} + 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/ProjectTab.tsx b/plugin/src/components/ProjectTab.tsx index e132b79..2252cb9 100644 --- a/plugin/src/components/ProjectTab.tsx +++ b/plugin/src/components/ProjectTab.tsx @@ -14,6 +14,7 @@ import { buildLanguageOptions, getLanguageOption, type LanguageOption } from '@/ import { SettingsData } from '@/data/settings-data' import { UserSettingsData } from '@/data/user-settings-data' import { useGenerationHistory } from '@/hooks/useGenerationHistory' +import { useLatestQuestionnaireEvent } from '@/hooks/useLatestQuestionnaireEvent' import { useTemplates } from '@/hooks/useTemplates' const DEFAULT_LANGUAGE = 'en' @@ -29,6 +30,7 @@ export default function ProjectTab({ }) const history = useGenerationHistory(project) const projectUuid = project?.uuid + const latestEvent = useLatestQuestionnaireEvent(projectUuid) const [selectedUuid, setSelectedUuid] = useState('') const [selectedRunId, setSelectedRunId] = useState(null) @@ -171,7 +173,11 @@ export default function ProjectTab({
{selectedRunId ? ( - + ) : ( + latestEvent: LatestQuestionnaireEvent +} + +/** A small badge saying whether the questionnaire answers may have changed since the document was generated. */ +export function QuestionnaireChangeBadge({ run, latestEvent }: QuestionnaireChangeBadgeProps) { + if (run.status !== 'succeeded') return null + + if (latestEvent.status === 'loading') { + return + } + + const change = getQuestionnaireChange(run, latestEvent) + + if (change === 'changed') { + return ( + + Questionnaire changed after the DMP was generated + + ) + } + + // Unchanged, or not verifiable (older run, DSW unreachable): nothing to show. + return null +} diff --git a/plugin/src/components/RunDetailPanel.tsx b/plugin/src/components/RunDetailPanel.tsx index 8880664..1a40e74 100644 --- a/plugin/src/components/RunDetailPanel.tsx +++ b/plugin/src/components/RunDetailPanel.tsx @@ -7,6 +7,7 @@ import { Muted, Title } from '@ds-wizard/plugin-sdk/ui/Text' import { useEffect, useState } from 'react' import { PipelineResultPanel } from '@/components/PipelineResultPanel' +import { QuestionnaireChangeBadge } from '@/components/QuestionnaireChangeBadge' import styles from '@/components/RunDetailPanel.module.css' import { getRunTimeLabel, @@ -15,11 +16,13 @@ import { RunRecord, type UseGenerationHistoryResult, } from '@/hooks/useGenerationHistory' +import type { LatestQuestionnaireEvent } from '@/hooks/useLatestQuestionnaireEvent' import type { PipelineStatusResponse } from '@/types.ts' type RunDetailPanelProps = { runId: string history: UseGenerationHistoryResult + latestEvent: LatestQuestionnaireEvent } function RunNameEditor({ @@ -135,7 +138,7 @@ function RunDetailPanelBody({ ) } -export function RunDetailPanel({ runId, history }: RunDetailPanelProps) { +export function RunDetailPanel({ runId, history, latestEvent }: RunDetailPanelProps) { const run = history.getRun(runId) const { ensureDetailLoaded, applyStatus } = history @@ -160,6 +163,7 @@ export function RunDetailPanel({ runId, history }: RunDetailPanelProps) { {getRunVersionLabel(run)} {getRunTimeLabel(run)} + diff --git a/plugin/src/hooks/useGenerationHistory.ts b/plugin/src/hooks/useGenerationHistory.ts index 402fec7..c1f15eb 100644 --- a/plugin/src/hooks/useGenerationHistory.ts +++ b/plugin/src/hooks/useGenerationHistory.ts @@ -31,6 +31,7 @@ export type RunRecord = { createdAt: string updatedAt: string namedVersion: string | null + sourceEventUuid: string | null resultMarkdown: string | null /** false = came only from the summary list, never polled/backfilled with full detail. */ hasDetail: boolean @@ -79,6 +80,7 @@ const summaryToRunRecord = (item: PipelineSummaryItem): RunRecord => ({ createdAt: item.createdAt, updatedAt: item.updatedAt, namedVersion: item.namedVersion, + sourceEventUuid: item.sourceEventUuid, resultMarkdown: null, hasDetail: false, }) @@ -127,6 +129,7 @@ export function useGenerationHistory(project: PipelineProject): UseGenerationHis error: status.error, createdAt: status.createdAt, namedVersion: status.namedVersion, + sourceEventUuid: status.sourceEventUuid, updatedAt: status.updatedAt, progressMessage: status.progressMessage, resultMarkdown: status.resultMarkdown, diff --git a/plugin/src/hooks/useLatestQuestionnaireEvent.ts b/plugin/src/hooks/useLatestQuestionnaireEvent.ts new file mode 100644 index 0000000..811270f --- /dev/null +++ b/plugin/src/hooks/useLatestQuestionnaireEvent.ts @@ -0,0 +1,58 @@ +import { useEffect, useState } from 'react' + +import { getLatestQuestionnaireEventUuid } from '@/client' +import type { RunRecord } from '@/hooks/useGenerationHistory' + +export type LatestQuestionnaireEvent = + | { status: 'loading' } + | { status: 'failed' } + | { status: 'ready'; eventUuid: string } + +/** + * The newest DSW event of the questionnaire, read once when the project tab opens. Runs are compared against + * it, so opening several runs costs a single request to DSW. + */ +export function useLatestQuestionnaireEvent( + questionnaireUuid: string | undefined, +): LatestQuestionnaireEvent { + const [latest, setLatest] = useState({ status: 'loading' }) + + useEffect(() => { + setLatest({ status: 'loading' }) + if (!questionnaireUuid) return + + let cancelled = false + void getLatestQuestionnaireEventUuid(questionnaireUuid) + .then((eventUuid) => { + if (!cancelled) setLatest({ status: 'ready', eventUuid }) + }) + .catch(() => { + if (!cancelled) setLatest({ status: 'failed' }) + }) + + return () => { + cancelled = true + } + }, [questionnaireUuid]) + + return latest +} + +/** + * Whether the answers changed since the run read them: `changed`, `unknown` when that cannot be told (older + * run, or DSW could not be asked), or `null` when there is nothing to show (unchanged, or the run has not + * succeeded). Throws when called while the latest event is still loading, so callers must wait for it. + * + * The check is conservative: phase and label edits, and re-saving the same value, also count as a change. + */ +export function getQuestionnaireChange( + run: Pick, + latest: LatestQuestionnaireEvent, +): 'changed' | 'unknown' | null { + if (latest.status === 'loading') { + throw new Error('The latest questionnaire event is not loaded yet.') + } + if (run.status !== 'succeeded') return null + if (latest.status === 'failed' || !run.sourceEventUuid) return 'unknown' + return latest.eventUuid.toLowerCase() === run.sourceEventUuid.toLowerCase() ? null : 'changed' +} diff --git a/plugin/src/types.ts b/plugin/src/types.ts index 051a5a9..49fba1e 100644 --- a/plugin/src/types.ts +++ b/plugin/src/types.ts @@ -95,6 +95,8 @@ export type PipelineStatusResponse = { progressMessage: string | null updatedAt: string namedVersion: string | null + /** Newest DSW questionnaire event when the run read the answers; null for older runs. */ + sourceEventUuid: string | null } export type PipelineSummaryItem = { @@ -107,6 +109,7 @@ export type PipelineSummaryItem = { createdAt: string updatedAt: string namedVersion: string | null + sourceEventUuid: string | null } export type ResultRenderMode = 'formatted' | 'raw' diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py index c4f47c2..4b201c3 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py @@ -9,6 +9,30 @@ logger = logging.getLogger(__name__) +# Stands for "event 0" of a questionnaire without any events. +NO_EVENTS_UUID = UUID(int=0) + + +def parse_latest_event_uuid(payload: object) -> UUID: + """Read the newest event UUID from a ``/projects/{uuid}/events?size=1&sort=createdAt,desc`` response. + + A questionnaire without events gives ``NO_EVENTS_UUID``. Raises ValueError, TypeError or KeyError for an + unexpected shape, so that a changed DSW response is never mistaken for an empty questionnaire. + """ + if not isinstance(payload, dict): + msg = 'Unexpected events response: not an object' + raise TypeError(msg) + + embedded = payload.get('_embedded') + events = embedded.get('projectEvents') if isinstance(embedded, dict) else None + if not isinstance(events, list): + msg = 'Unexpected events response: no projectEvents list' + raise TypeError(msg) + if not events: + return NO_EVENTS_UUID + return UUID(events[0]['uuid']) + + class DSWClient: def __init__(self, token: str, api_url: str) -> None: self.token = token @@ -54,6 +78,31 @@ async def get_questionnaire_detail(self, questionnaire_uuid: UUID) -> dict: ) return payload + async def get_latest_event_uuid(self, project_uuid: str | UUID) -> UUID: + # One event, newest first. DSW applies no default order, so the sort is required. + url = f'{self.api_url}/projects/{project_uuid}/events' + logger.info( + 'Fetching latest questionnaire event from DSW', + extra={'url.full': url, 'project_uuid': str(project_uuid)}, + ) + + headers: dict[str, str] = {} + if self.token: + headers['Authorization'] = f'Bearer {self.token}' + + try: + async with httpx.AsyncClient() as client: + response = await client.get(url, headers=headers, params={'size': 1, 'sort': 'createdAt,desc'}) + response.raise_for_status() + except httpx.HTTPError: + logger.exception( + 'Failed to fetch latest questionnaire event from DSW', + extra={'url.full': url, 'project_uuid': str(project_uuid)}, + ) + raise + + return parse_latest_event_uuid(response.json()) + async def get_project_versions(self, project_uuid: str | UUID) -> list[dict]: # Fetch versions once and return them newest first for all consumers. url = f'{self.api_url}/projects/{project_uuid}/versions' 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 af9ba38..1f04689 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/database.py +++ b/service/src/ai_document_plugin_service/ai/persistence/database.py @@ -88,6 +88,7 @@ class GenerationUpdate(TypedDict, total=False): result_markdown: str | None progress_message: str | None named_version: str | None + source_event_uuid: UUID | None class GenerationStats(TypedDict, total=False): @@ -115,6 +116,7 @@ class GenerationRecord: created_at: datetime updated_at: datetime named_version: str | None = None + source_event_uuid: UUID | None = None @classmethod def from_row(cls, row: Row) -> 'GenerationRecord': @@ -135,6 +137,7 @@ def from_row(cls, row: Row) -> 'GenerationRecord': created_at=row.created_at, updated_at=row.updated_at, named_version=row.named_version, + source_event_uuid=row.source_event_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 7e70c12..e770e8a 100644 --- a/service/src/ai_document_plugin_service/ai/persistence/schema.py +++ b/service/src/ai_document_plugin_service/ai/persistence/schema.py @@ -117,6 +117,9 @@ def create_persistence_schema(schema_name: str) -> PersistenceSchema: Column('result_markdown', Text, nullable=True), Column('progress_message', Text, nullable=True), Column('named_version', Text, nullable=True), + # Newest DSW event of the questionnaire when the run read it (see QuestionnaireStateService). + # The nil UUID for a questionnaire without events; NULL for runs from before this column existed. + Column('source_event_uuid', UUID(as_uuid=True), nullable=True), Column( 'created_at', DateTime(timezone=True), diff --git a/service/src/ai_document_plugin_service/api/types.py b/service/src/ai_document_plugin_service/api/types.py index d5046ba..0a9e899 100644 --- a/service/src/ai_document_plugin_service/api/types.py +++ b/service/src/ai_document_plugin_service/api/types.py @@ -278,6 +278,8 @@ class PipelineSummaryResponse(ApiModel): created_at: str updated_at: str named_version: str | None = None + # Newest DSW questionnaire event when the run read the answers; None for older runs. + source_event_uuid: UUID | None = None class PipelineStatusResponse(ApiModel): @@ -294,3 +296,4 @@ class PipelineStatusResponse(ApiModel): progress_message: str | None = None updated_at: str named_version: str | None = None + source_event_uuid: UUID | None = None diff --git a/service/src/ai_document_plugin_service/di.py b/service/src/ai_document_plugin_service/di.py index 76d64b6..60f1794 100644 --- a/service/src/ai_document_plugin_service/di.py +++ b/service/src/ai_document_plugin_service/di.py @@ -10,6 +10,7 @@ from ai_document_plugin_service.service.llm_settings_service import LlmSettingsService from ai_document_plugin_service.service.pipeline_queue_manager import PipelineQueueManager from ai_document_plugin_service.service.pipeline_service import PipelineService +from ai_document_plugin_service.service.questionnaire_state_service import QuestionnaireStateService from ai_document_plugin_service.service.template_service import TemplateService @@ -19,7 +20,11 @@ def setup_app_state(app: fastapi.FastAPI, config: Config) -> None: app.state.template_service = TemplateService(app.state.database, config.cover_definition) app.state.llm_settings_service = LlmSettingsService(app.state.database) app.state.pipeline_queue_manager = PipelineQueueManager(config.max_parallel_executions) - app.state.pipeline_service = PipelineService(app.state.pipeline_queue_manager, app.state.database) + app.state.pipeline_service = PipelineService( + app.state.pipeline_queue_manager, + app.state.database, + QuestionnaireStateService(), + ) app.state.export_service = ExportService(app.state.database) diff --git a/service/src/ai_document_plugin_service/migrations/versions/20261120_01_add_source_event_to_generation.py b/service/src/ai_document_plugin_service/migrations/versions/20261120_01_add_source_event_to_generation.py new file mode 100644 index 0000000..4d9680b --- /dev/null +++ b/service/src/ai_document_plugin_service/migrations/versions/20261120_01_add_source_event_to_generation.py @@ -0,0 +1,27 @@ +"""Record the newest DSW questionnaire event a run was generated from. + +Lets the plugin tell whether the questionnaire answers changed since the run. Existing runs have no value (NULL) +and are reported as unknown. + +Revision ID: 20261120_01 +Revises: 20261113_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_01' +down_revision = '20261113_01' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + schema = context.get_context().version_table_schema + op.add_column( + 'generation', + sa.Column('source_event_uuid', postgresql.UUID(as_uuid=True), nullable=True), + 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 d9fdffc..859d362 100644 --- a/service/src/ai_document_plugin_service/service/pipeline_service.py +++ b/service/src/ai_document_plugin_service/service/pipeline_service.py @@ -34,6 +34,10 @@ ) from ai_document_plugin_service.service.errors import ConflictError, NotConfiguredError, NotFoundError from ai_document_plugin_service.service.pipeline_queue_manager import PipelineQueueManager +from ai_document_plugin_service.service.questionnaire_state_service import ( + QuestionnaireState, + QuestionnaireStateService, +) logger = logging.getLogger(__name__) @@ -77,6 +81,7 @@ def _generation_record_to_status_response(record: GenerationRecord) -> PipelineS progress_message=record.progress_message, updated_at=record.updated_at.isoformat(), named_version=record.named_version, + source_event_uuid=record.source_event_uuid, ) @@ -91,16 +96,18 @@ def _generation_record_to_summary_response(record: GenerationRecord) -> Pipeline created_at=record.created_at.isoformat(), updated_at=record.updated_at.isoformat(), named_version=record.named_version, + source_event_uuid=record.source_event_uuid, ) -def _succeeded_update(output: PipelineOutput) -> GenerationUpdate: +def _succeeded_update(output: PipelineOutput, questionnaire_state: QuestionnaireState) -> GenerationUpdate: """The generation fields a finished run writes.""" return { 'status': PipelineStatus.SUCCEEDED, 'knowledge_model_uuid': output.knowledge_model_uuid, 'result_markdown': output.markdown, 'progress_message': None, + 'source_event_uuid': questionnaire_state.event_uuid, } @@ -159,9 +166,15 @@ def _log_background_update_failure(task: Task[object]) -> None: class PipelineService: - def __init__(self, pipeline_queue_manager: PipelineQueueManager, database: Database) -> None: + def __init__( + self, + pipeline_queue_manager: PipelineQueueManager, + database: Database, + questionnaire_state_service: QuestionnaireStateService, + ) -> None: self.pipeline_queue_manager = pipeline_queue_manager self.database = database + self.questionnaire_state_service = questionnaire_state_service self._llm_clients = LlmClientTenantStore() async def get_pipeline_status(self, run_id: UUID, auth: AuthenticatedUser) -> PipelineStatusResponse | None: @@ -464,6 +477,10 @@ def on_progress(message: str) -> None: tenant_uuid=auth.tenant_uuid, ) with run_log_context(log_context): + dsw_client = DSWClient(auth.token, auth.api_url) + # Taken right before run_pipeline reads the answers, so an edit in between only makes the run look + # changed, never unchanged. A failure here fails the run: it would otherwise lose the change check. + questionnaire_state = await self.questionnaire_state_service.capture(dsw_client, questionnaire_uuid) output = await run_pipeline( questionnaire_uuid=questionnaire_uuid, template_uuid=template_uuid, @@ -471,7 +488,7 @@ def on_progress(message: str) -> None: tenant_uuid=auth.tenant_uuid, pipeline=pipeline, on_progress=on_progress, - dsw_client=DSWClient(auth.token, auth.api_url), + dsw_client=dsw_client, created_at=record.created_at.astimezone(ZoneInfo(time_zone)), project_versions=project_versions, include_cover_page=include_cover_page, @@ -484,7 +501,7 @@ def on_progress(message: str) -> None: # Everything the run produced is written in one transaction, so it lands atomically. async with self.database.transaction(): record = await self.database.update_generation( - run_id, auth.tenant_uuid, expected_statuses=(PipelineStatus.RUNNING,), **_succeeded_update(output) + run_id, auth.tenant_uuid, expected_statuses=(PipelineStatus.RUNNING,), **_succeeded_update(output, questionnaire_state) ) if record is None: # Cancellation won the atomic status transition. Discard the output 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 new file mode 100644 index 0000000..50fb764 --- /dev/null +++ b/service/src/ai_document_plugin_service/service/questionnaire_state_service.py @@ -0,0 +1,18 @@ +"""The state of a questionnaire at the time a document was generated. +""" + +from dataclasses import dataclass +from uuid import UUID + +from ai_document_plugin_service.ai.knowledgemodel.dsw_client import DSWClient + + +@dataclass(frozen=True) +class QuestionnaireState: + event_uuid: UUID + + +class QuestionnaireStateService: + async def capture(self, 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)) diff --git a/service/tests/service/test_pipeline_admission.py b/service/tests/service/test_pipeline_admission.py index c716f4f..123a2ba 100644 --- a/service/tests/service/test_pipeline_admission.py +++ b/service/tests/service/test_pipeline_admission.py @@ -28,7 +28,7 @@ async def test_admission_uses_cancellable_states_in_owned_project_history(admiss database.list_generations.return_value = [ Mock(template_uuid=payload.template_uuid if same_template else uuid4(), status=status), ] - service = PipelineService(queue, database) + service = PipelineService(queue, database, Mock()) with patch('ai_document_plugin_service.service.pipeline_service.DSWClient') as client: client.return_value.get_project_versions = AsyncMock(return_value=[]) if same_template and status in {PipelineStatus.QUEUED, PipelineStatus.RUNNING}: @@ -51,7 +51,7 @@ async def test_admission_rejects_deleted_template(admission): with patch('ai_document_plugin_service.service.pipeline_service.DSWClient') as client: client.return_value.get_project_versions = AsyncMock(return_value=[]) with pytest.raises(NotFoundError): - await PipelineService(queue, database).enqueue_pipeline_job(payload, Mock(), auth, Mock(), None) + await PipelineService(queue, database, Mock()).enqueue_pipeline_job(payload, Mock(), auth, Mock(), None) database.create_generation.assert_not_awaited() queue.enqueue.assert_not_called() @@ -92,7 +92,7 @@ async def create_generation(**kwargs): database.get_template.side_effect = get_template database.list_generations.side_effect = list_generations database.create_generation.side_effect = create_generation - services = [PipelineService(queue, database), PipelineService(queue, database)] + services = [PipelineService(queue, database, Mock()), PipelineService(queue, database, Mock())] with patch('ai_document_plugin_service.service.pipeline_service.DSWClient') as client: client.return_value.get_project_versions = AsyncMock(return_value=[]) results = await asyncio.gather( diff --git a/service/tests/service/test_pipeline_rename.py b/service/tests/service/test_pipeline_rename.py index a15ef9c..07cb584 100644 --- a/service/tests/service/test_pipeline_rename.py +++ b/service/tests/service/test_pipeline_rename.py @@ -42,7 +42,7 @@ async def test_rename_persists_title_for_every_run_status(auth, status): database = AsyncMock() database.get_generation.return_value = record database.update_generation.return_value = replace(record, title='New title') - service = PipelineService(Mock(), database) + service = PipelineService(Mock(), database, Mock()) result = await service.rename_pipeline(record.run_id, PipelineRenameRequest(title=' New title '), auth) @@ -56,7 +56,7 @@ async def test_rename_persists_title_for_every_run_status(auth, status): async def test_rename_does_not_update_a_run_outside_the_users_scope(auth): database = AsyncMock() database.get_generation.return_value = None - service = PipelineService(Mock(), database) + service = PipelineService(Mock(), database, Mock()) run_id = uuid4() with pytest.raises(NotFoundError): @@ -69,7 +69,7 @@ async def test_rename_does_not_update_a_run_outside_the_users_scope(auth): async def test_rename_handles_a_run_removed_before_update(auth): database = AsyncMock() database.update_generation.return_value = None - service = PipelineService(Mock(), database) + service = PipelineService(Mock(), database, Mock()) with pytest.raises(NotFoundError): await service.rename_pipeline(uuid4(), PipelineRenameRequest(title='New title'), auth) From 2e4a26f5c55589a851059b895a15627a9c16906a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Frnka?= Date: Fri, 20 Nov 2026 18:59:45 +0100 Subject: [PATCH 2/3] Fix formatting --- .../ai/knowledgemodel/dsw_client.py | 7 +++++-- .../ai_document_plugin_service/service/pipeline_service.py | 5 ++++- .../service/questionnaire_state_service.py | 6 +++--- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py b/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py index 4b201c3..cde1f61 100644 --- a/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py +++ b/service/src/ai_document_plugin_service/ai/knowledgemodel/dsw_client.py @@ -16,8 +16,11 @@ def parse_latest_event_uuid(payload: object) -> UUID: """Read the newest event UUID from a ``/projects/{uuid}/events?size=1&sort=createdAt,desc`` response. - A questionnaire without events gives ``NO_EVENTS_UUID``. Raises ValueError, TypeError or KeyError for an - unexpected shape, so that a changed DSW response is never mistaken for an empty questionnaire. + A questionnaire without events gives ``NO_EVENTS_UUID``. + + Raises: + TypeError: If the payload is not the expected page of events. A malformed event also raises KeyError or + ValueError. """ if not isinstance(payload, dict): msg = 'Unexpected events response: not an object' 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 859d362..04b14f9 100644 --- a/service/src/ai_document_plugin_service/service/pipeline_service.py +++ b/service/src/ai_document_plugin_service/service/pipeline_service.py @@ -501,7 +501,10 @@ def on_progress(message: str) -> None: # Everything the run produced is written in one transaction, so it lands atomically. async with self.database.transaction(): record = await self.database.update_generation( - run_id, auth.tenant_uuid, expected_statuses=(PipelineStatus.RUNNING,), **_succeeded_update(output, questionnaire_state) + run_id, + auth.tenant_uuid, + expected_statuses=(PipelineStatus.RUNNING,), + **_succeeded_update(output, questionnaire_state), ) if record is None: # Cancellation won the atomic status transition. Discard the output 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 50fb764..d078a8b 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,5 +1,4 @@ -"""The state of a questionnaire at the time a document was generated. -""" +"""The state of a questionnaire at the time a document was generated.""" from dataclasses import dataclass from uuid import UUID @@ -13,6 +12,7 @@ class QuestionnaireState: class QuestionnaireStateService: - async def capture(self, dsw_client: DSWClient, questionnaire_uuid: UUID) -> QuestionnaireState: + @staticmethod + 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)) From 1e3525da9f177682234656b41f8887df051f08da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Frnka?= Date: Wed, 25 Nov 2026 17:53:05 +0100 Subject: [PATCH 3/3] Fix CI --- plugin/src/client.ts | 7 ++++- .../components/QuestionnaireChangeBadge.tsx | 28 ++++++++----------- .../src/hooks/useLatestQuestionnaireEvent.ts | 27 ++++++++---------- 3 files changed, 29 insertions(+), 33 deletions(-) diff --git a/plugin/src/client.ts b/plugin/src/client.ts index 062287b..9161d52 100644 --- a/plugin/src/client.ts +++ b/plugin/src/client.ts @@ -232,7 +232,12 @@ export const getLatestQuestionnaireEventUuid = async ( } const latest: unknown = events[0] - if (!latest || typeof latest !== 'object' || !('uuid' in latest) || typeof latest.uuid !== 'string') { + if ( + !latest || + typeof latest !== 'object' || + !('uuid' in latest) || + typeof latest.uuid !== 'string' + ) { throw new Error('Invalid questionnaire event returned.') } return latest.uuid diff --git a/plugin/src/components/QuestionnaireChangeBadge.tsx b/plugin/src/components/QuestionnaireChangeBadge.tsx index b026c06..0b67e77 100644 --- a/plugin/src/components/QuestionnaireChangeBadge.tsx +++ b/plugin/src/components/QuestionnaireChangeBadge.tsx @@ -3,7 +3,7 @@ import { Spinner } from '@ds-wizard/plugin-sdk/ui/Icon' import type { RunRecord } from '@/hooks/useGenerationHistory' import { - getQuestionnaireChange, + isQuestionnaireChanged, type LatestQuestionnaireEvent, } from '@/hooks/useLatestQuestionnaireEvent' @@ -20,20 +20,16 @@ export function QuestionnaireChangeBadge({ run, latestEvent }: QuestionnaireChan return } - const change = getQuestionnaireChange(run, latestEvent) - - if (change === 'changed') { - return ( - - Questionnaire changed after the DMP was generated - - ) - } - // Unchanged, or not verifiable (older run, DSW unreachable): nothing to show. - return null + if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null + + return ( + + Questionnaire changed after the DMP was generated + + ) } diff --git a/plugin/src/hooks/useLatestQuestionnaireEvent.ts b/plugin/src/hooks/useLatestQuestionnaireEvent.ts index 811270f..3a588af 100644 --- a/plugin/src/hooks/useLatestQuestionnaireEvent.ts +++ b/plugin/src/hooks/useLatestQuestionnaireEvent.ts @@ -1,12 +1,9 @@ import { useEffect, useState } from 'react' import { getLatestQuestionnaireEventUuid } from '@/client' -import type { RunRecord } from '@/hooks/useGenerationHistory' export type LatestQuestionnaireEvent = - | { status: 'loading' } - | { status: 'failed' } - | { status: 'ready'; eventUuid: string } + { status: 'loading' } | { status: 'failed' } | { status: 'ready'; eventUuid: string } /** * The newest DSW event of the questionnaire, read once when the project tab opens. Runs are compared against @@ -39,20 +36,18 @@ export function useLatestQuestionnaireEvent( } /** - * Whether the answers changed since the run read them: `changed`, `unknown` when that cannot be told (older - * run, or DSW could not be asked), or `null` when there is nothing to show (unchanged, or the run has not - * succeeded). Throws when called while the latest event is still loading, so callers must wait for it. + * Whether the answers changed since the run read them. False when that cannot be told: the latest event is not + * loaded or could not be read, or the run is older and has no event of its own. * * The check is conservative: phase and label edits, and re-saving the same value, also count as a change. */ -export function getQuestionnaireChange( - run: Pick, +export function isQuestionnaireChanged( + sourceEventUuid: string | null, latest: LatestQuestionnaireEvent, -): 'changed' | 'unknown' | null { - if (latest.status === 'loading') { - throw new Error('The latest questionnaire event is not loaded yet.') - } - if (run.status !== 'succeeded') return null - if (latest.status === 'failed' || !run.sourceEventUuid) return 'unknown' - return latest.eventUuid.toLowerCase() === run.sourceEventUuid.toLowerCase() ? null : 'changed' +): boolean { + return ( + latest.status === 'ready' && + sourceEventUuid !== null && + latest.eventUuid.toLowerCase() !== sourceEventUuid.toLowerCase() + ) }