Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
53 changes: 53 additions & 0 deletions plugin/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,59 @@ export const getPipelineStatus = async (runId: string): Promise<PipelineStatusRe
return data
}

/** Stands for "event 0" of a questionnaire without any events; matches the service. */
const NO_EVENTS_UUID = '00000000-0000-0000-0000-000000000000'

/**
* UUID of the newest event of the questionnaire in DSW (the nil UUID when it has no events), read from the DSW
* API directly. DSW applies no default order, so the sort is required.
*/
export const getLatestQuestionnaireEventUuid = async (
questionnaireUuid: string,
): Promise<string> => {
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<void> => {
const url = `${getApiBaseUrl()}/pipelines/status/${encodeURIComponent(runId)}`
const response = await apiFetch(url, { method: 'DELETE' })
Expand Down
8 changes: 7 additions & 1 deletion plugin/src/components/ProjectTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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<string | null>(null)
Expand Down Expand Up @@ -171,7 +173,11 @@ export default function ProjectTab({
<div className={styles.main}>
<div className={styles.content}>
{selectedRunId ? (
<RunDetailPanel runId={selectedRunId} history={history} />
<RunDetailPanel
runId={selectedRunId}
history={history}
latestEvent={latestEvent}
/>
) : (
<Stack loose>
<ProjectTemplatePanel
Expand Down
35 changes: 35 additions & 0 deletions plugin/src/components/QuestionnaireChangeBadge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Badge } from '@ds-wizard/plugin-sdk/ui/Badge'
import { Spinner } from '@ds-wizard/plugin-sdk/ui/Icon'

import type { RunRecord } from '@/hooks/useGenerationHistory'
import {
isQuestionnaireChanged,
type LatestQuestionnaireEvent,
} from '@/hooks/useLatestQuestionnaireEvent'

type QuestionnaireChangeBadgeProps = {
run: Pick<RunRecord, 'status' | 'sourceEventUuid'>
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 <Spinner label="Checking the questionnaire for changes" />
}

// Unchanged, or not verifiable (older run, DSW unreachable): nothing to show.
if (!isQuestionnaireChanged(run.sourceEventUuid, latestEvent)) return null

return (
<Badge
tone="warning"
icon="fa-triangle-exclamation"
description="Some answers may have been edited since this document was generated."
>
Questionnaire changed after the DMP was generated
</Badge>
)
}
6 changes: 5 additions & 1 deletion plugin/src/components/RunDetailPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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({
Expand Down Expand Up @@ -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

Expand All @@ -160,6 +163,7 @@ export function RunDetailPanel({ runId, history }: RunDetailPanelProps) {
<Inline>
<Badge>{getRunVersionLabel(run)}</Badge>
<Muted>{getRunTimeLabel(run)}</Muted>
<QuestionnaireChangeBadge run={run} latestEvent={latestEvent} />
</Inline>
</Stack>
<RunDetailPanelBody run={run} applyStatus={applyStatus} />
Expand Down
3 changes: 3 additions & 0 deletions plugin/src/hooks/useGenerationHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
})
Expand Down Expand Up @@ -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,
Expand Down
53 changes: 53 additions & 0 deletions plugin/src/hooks/useLatestQuestionnaireEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { useEffect, useState } from 'react'

import { getLatestQuestionnaireEventUuid } from '@/client'

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<LatestQuestionnaireEvent>({ 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. 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 isQuestionnaireChanged(
sourceEventUuid: string | null,
latest: LatestQuestionnaireEvent,
): boolean {
return (
latest.status === 'ready' &&
sourceEventUuid !== null &&
latest.eventUuid.toLowerCase() !== sourceEventUuid.toLowerCase()
)
}
3 changes: 3 additions & 0 deletions plugin/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -107,6 +109,7 @@ export type PipelineSummaryItem = {
createdAt: string
updatedAt: string
namedVersion: string | null
sourceEventUuid: string | null
}

export type ResultRenderMode = 'formatted' | 'raw'
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,33 @@
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:
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'
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
Expand Down Expand Up @@ -54,6 +81,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'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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':
Expand All @@ -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,
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
3 changes: 3 additions & 0 deletions service/src/ai_document_plugin_service/api/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
Loading