Skip to content
Merged
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
3 changes: 3 additions & 0 deletions backend-contract/generated/job-history-detail.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
"type": "string"
},
"additionalProperties": {}
},
"referenceImageParameter": {
"type": "string"
}
},
"required": [
Expand Down
3 changes: 3 additions & 0 deletions backend-contract/generated/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,9 @@
"type": "string"
},
"additionalProperties": {}
},
"referenceImageParameter": {
"type": "string"
}
},
"required": [
Expand Down
1 change: 1 addition & 0 deletions backend-contract/processing/wire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ export const jobHistoryDetailSchema = z.object({
jobId: pathSegmentIdSchema,
log: z.array(z.string()),
parameters: z.record(z.string(), z.unknown()),
referenceImageParameter: z.string().optional(),
});

export type JobHistoryDetail = z.infer<typeof jobHistoryDetailSchema>;
Expand Down
159 changes: 159 additions & 0 deletions src/processing/__tests__/job-adoption.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createPinia, setActivePinia } from 'pinia';

import {
appApplyDependencies,
autoLoadProcessingResults,
} from '@/src/processing/applyResults';
import { useProcessingJobsStore } from '@/src/processing/store';
import type { ProcessingResult } from '@/src/processing/types';
import {
seatDataSource,
seatVolume,
} from '@/src/store/__tests__/datasetFixtures';
import { seatImage } from '@/src/segmentation/__tests__/segmentMaskFixtures';
import { serializeAnnotations } from './serializedScene';

const jobRef = { providerId: 'analysis', jobId: 'saved-job' };
const baseUris = ['/ct/2.dcm', '/ct/1.dcm'];
const layerUris = ['/pet/1.dcm', '/pet/2.dcm'];

const rulerFile = {
schemaVersion: 1,
space: 'LPS',
labels: {
rulers: { Tumor: { color: '#ff0000', strokeWidth: 3 } },
rectangles: {},
polygons: {},
},
tools: {
rulers: [
{
name: 'Long axis',
labelName: 'Tumor',
firstPoint: [1, 1, 2],
secondPoint: [4, 1, 2],
frameOfReference: {
planeNormal: [0, 0, 1],
planeOrigin: [0, 0, 2],
},
},
],
rectangles: [],
polygons: [],
},
};

const result: ProcessingResult = {
intent: 'add-annotations',
id: 'rulers',
name: 'measurements.annotations.json',
url: '/measurements.annotations.json',
source: { ...jobRef, outputId: 'outputAnnotations' },
};

const loadVolume = async (id: string, uris: string[]) => {
await seatImage(id, { dimensions: [8, 8, 8] });
seatVolume(id);
seatDataSource(id, {
type: 'collection',
sources: uris.map((uri) => ({ type: 'uri', uri, name: uri })),
});
};

beforeEach(() => {
setActivePinia(createPinia());
});

afterEach(() => {
vi.unstubAllGlobals();
});

describe('adopting jobs with base and layer inputs', () => {
it.each([
{ baseLoaded: true, baseSubmitted: true, expectedCount: 1 },
{ baseLoaded: false, baseSubmitted: true, expectedCount: 0 },
{ baseLoaded: true, baseSubmitted: false, expectedCount: 0 },
])(
'restores only the named base with loaded=$baseLoaded, submitted=$baseSubmitted',
async ({ baseLoaded, baseSubmitted, expectedCount }) => {
if (baseLoaded) await loadVolume('base-ct', [...baseUris].reverse());
await loadVolume('pet-layer', layerUris);
const detail = {
jobId: jobRef.jobId,
log: [],
parameters: {
absentLayer: null,
inputPETVolume: { type: 'image', uris: layerUris },
inputTools: { type: 'annotations', uris: ['/tools.json'] },
...(baseSubmitted
? { inputVolume: { type: 'image', uris: baseUris } }
: {}),
},
referenceImageParameter: 'inputVolume',
};
const history = {
jobs: [
{
jobId: jobRef.jobId,
taskId: 'measure',
taskTitle: 'Measure segments',
createdBy: { id: 'reader', name: 'Reader' },
createdAt: '2026-10-21T12:00:00Z',
state: 'success',
resultState: 'ready',
outputSummary: { recorded: 1, missing: 0 },
},
],
nextCursor: null,
};
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const path = new URL(String(input), window.location.origin).pathname;
let payload: unknown;
if (path.endsWith('/detail')) payload = detail;
else if (path.endsWith('/results'))
payload = { resultState: 'ready', intents: [result], missing: 0 };
else if (path === '/analysis/jobs') payload = history;
else throw new Error(`Unexpected request: ${path}`);
return new Response(JSON.stringify(payload), {
headers: { 'Content-Type': 'application/json' },
});
})
);
const jobs = useProcessingJobsStore();
jobs.registerProviderConfig({
id: jobRef.providerId,
label: 'Analysis',
baseUrl: '/analysis',
jobsBaseUrl: '/analysis',
});

await jobs.adoptJobHistory();
await jobs.loadJobResults(jobRef);
await jobs.applyJobResults(jobRef, (pending, submitted) =>
autoLoadProcessingResults(pending, submitted, {
...appApplyDependencies(),
fetchResult: async () =>
new File([JSON.stringify(rulerFile)], result.name),
})
);

const savedRulers = serializeAnnotations().tools?.rulers?.tools ?? [];
if (expectedCount) {
expect(savedRulers).toMatchObject([
{
imageID: 'base-ct',
name: 'Long axis',
firstPoint: [1, 1, 2],
secondPoint: [4, 1, 2],
},
]);
expect(savedRulers).toHaveLength(1);
} else {
expect(savedRulers).toEqual([]);
}
}
);
});
31 changes: 31 additions & 0 deletions src/processing/__tests__/store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,37 @@ describe('Providers store — re-discovered job history: slim observability adop
expect(store.jobResultsApplied.size).toBe(0);
});

it.each([
[
'throws synchronously',
() => {
throw new Error('History unavailable');
},
],
['rejects', () => Promise.reject(new Error('History unavailable'))],
] as const)(
'loads adopted results when job detail %s',
async (_, readDetail) => {
const provider = makeProvider({
listJobHistory: vi.fn().mockResolvedValue({
jobs: [handle({ state: 'success' })],
nextCursor: null,
}),
getJobHistoryDetail: vi.fn(readDetail),
getResults: vi.fn().mockResolvedValue(resultsBundle(sampleResults)),
});
const store = arrange(provider);

await store.adoptJobHistory();
await store.loadJobResults(ref('jr'));

expect(store.jobResults.get(keyFor('jr'))).toEqual(sampleResults);
expect(
store.submittedContexts.get(keyFor('jr'))?.activeDatasetId
).toBeUndefined();
}
);

it('a job that settles between listing and the first poll completes once', async () => {
const provider = makeProvider({
listJobHistory: vi.fn().mockResolvedValue({
Expand Down
9 changes: 8 additions & 1 deletion src/processing/components/JobsModule.vue
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ import {
type TaskFormModel,
type FormValidationIssue,
} from '@/src/processing/engine/formModel';
import { type SourceRefBindingState } from '@/src/processing/engine/mintInput';
import {
mintInputValue,
type SourceRefBindingState,
} from '@/src/processing/engine/mintInput';
import {
bindSourceRefs,
type BoundSourceRefType,
Expand Down Expand Up @@ -510,6 +513,7 @@ function jobDisplayContext(bindings: SourceRefBindings): JobDisplayContext {
labelmapNames,
types: bindings.types,
imageName: activeImageName(),
imageNames: bindings.image.names ?? {},
annotationCount: finishedAnnotationCount.value,
};
}
Expand Down Expand Up @@ -583,6 +587,9 @@ watchDebounced(
// Placing the first (or removing the last) tool flips the annotations
// binding, so the form must revalidate.
annotationCount: finishedAnnotationCount.value,
imageLayers: sourceRefContext().imageLayers?.map(({ dataSource }) =>
mintInputValue(dataSource)
),
};
},
() => {
Expand Down
16 changes: 16 additions & 0 deletions src/processing/components/TaskForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
:binding="sourceRefStates?.[field.id]"
:bound-name="sourceRefNames?.[field.id]"
:bound-type="sourceRefTypes?.[field.id]"
:image-index="imageInputIndices[field.id]"
:warning="sourceRefWarnings?.[field.id]"
@update:model-value="(v: ProcessingValue) => update(field.id, v)"
/>
Expand Down Expand Up @@ -96,6 +97,7 @@ import {
} from '@/src/processing/engine/formModel';
import type { SourceRefBindingState } from '@/src/processing/engine/mintInput';
import type { BoundSourceRefType } from '@/src/processing/engine/sourceRefs';
import { TYPE_TAG_IMAGE } from '@/backend-contract';

import BooleanWidget from './widgets/BooleanWidget.vue';
import NumberWidget from './widgets/NumberWidget.vue';
Expand Down Expand Up @@ -166,6 +168,20 @@ const inputFields = computed(() =>
props.model.fields.filter((f) => f.kind === 'sourceRef')
);

const imageInputIndices = computed(() =>
Object.fromEntries(
inputFields.value
.filter(
(field) =>
props.sourceRefTypes?.[field.id] === TYPE_TAG_IMAGE ||
(!props.sourceRefTypes?.[field.id] &&
field.accepts.length === 1 &&
field.accepts[0] === TYPE_TAG_IMAGE)
)
.map((field, index) => [field.id, index])
)
);

function widgetFor(kind: FormField['kind']) {
switch (kind) {
case 'bool':
Expand Down
Loading
Loading