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
52 changes: 52 additions & 0 deletions src/api/aiRuns.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { decideAiRunCandidates } from './aiRuns'

beforeEach(() => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
decision_batch_id: 'D-1',
ai_run_id: 'A-1',
case_id: 'CASE-1',
task_ids: ['T-1'],
decisions: [
{ candidate_id: 'C-1', action: 'ACCEPT' },
{ candidate_id: 'C-2', action: 'DISCARD' },
],
run_version: 4,
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
),
),
)
})

afterEach(() => vi.unstubAllGlobals())

describe('decideAiRunCandidates', () => {
it('sends the candidate decisions with the current run version and idempotency key', async () => {
await decideAiRunCandidates(
'A/1',
3,
[
{ candidate_id: 'C-1', action: 'ACCEPT' },
{ candidate_id: 'C-2', action: 'DISCARD' },
],
'decision-key',
)

const [url, init] = vi.mocked(fetch).mock.calls[0]
expect(url).toContain('/ai-runs/A%2F1/candidate-decisions')
expect(init?.method).toBe('POST')
expect(new Headers(init?.headers).get('Idempotency-Key')).toBe('decision-key')
expect(JSON.parse(String(init?.body))).toEqual({
expected_run_version: 3,
decisions: [
{ candidate_id: 'C-1', action: 'ACCEPT' },
{ candidate_id: 'C-2', action: 'DISCARD' },
],
})
})
})
35 changes: 35 additions & 0 deletions src/api/aiRuns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ export interface AiRunResponse {
updated_at: string
}

export type AiCandidateDecisionAction = 'ACCEPT' | 'DISCARD'

export interface AiCandidateDecisionItem {
candidate_id: string
action: AiCandidateDecisionAction
}

export interface AiCandidateDecisionResponse {
decision_batch_id: string
ai_run_id: string
case_id: string | null
task_ids: string[]
decisions: AiCandidateDecisionItem[]
run_version: number
}

export function createAiRun(instruction: string, idempotencyKey: string): Promise<AiRunResponse> {
return apiFetch<AiRunResponse>('/ai-runs', {
method: 'POST',
Expand All @@ -59,3 +75,22 @@ export function submitAiRunAnswers(
body: JSON.stringify({ expected_version: expectedVersion, answers }),
})
}

export function decideAiRunCandidates(
aiRunId: string,
expectedRunVersion: number,
decisions: AiCandidateDecisionItem[],
idempotencyKey: string,
): Promise<AiCandidateDecisionResponse> {
return apiFetch<AiCandidateDecisionResponse>(
`/ai-runs/${encodeURIComponent(aiRunId)}/candidate-decisions`,
{
method: 'POST',
headers: { 'Idempotency-Key': idempotencyKey },
body: JSON.stringify({
expected_run_version: expectedRunVersion,
decisions,
}),
},
)
}
20 changes: 19 additions & 1 deletion src/pages/ReviewWorkPage/AiRunReview.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@
color: var(--fowoco-white, #fff);
background: var(--surface-default);
border: 1px solid var(--border-default);
border-radius: var(--fowoco-radius-4);
border-radius: var(--fowoco-radius-999);
cursor: pointer;
}

Expand All @@ -398,6 +398,24 @@
border-color: var(--brand-primary);
}

.candidateCheck:disabled {
background: var(--surface-subtle);
cursor: not-allowed;
opacity: 0.65;
}

.candidateCheck:focus-visible,
.cardLink:focus-visible {
outline: 2px solid var(--brand-primary);
outline-offset: 2px;
}

.cardLink:disabled {
color: var(--text-secondary);
cursor: not-allowed;
opacity: 0.65;
}

.candidateDetails {
display: grid;
gap: 12px;
Expand Down
186 changes: 186 additions & 0 deletions src/pages/ReviewWorkPage/AiRunReview.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AiRunResponse } from '../../api/aiRuns'
import { AiRunReview } from './AiRunReview'

function jsonResponse(body: unknown, init: ResponseInit = {}) {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
...init,
})
}

const RUN: AiRunResponse = {
ai_run_id: 'A-1',
request_id: 'R-1',
instruction: '응웬반A 체류기간 연장과 급여 자료를 확인해 주세요',
status: 'SUCCEEDED',
analysis_outcome: 'REVIEW_REQUIRED',
detected_intent: 'EXPIRY_RENEWAL',
error_code: null,
attempt_count: 1,
version: 3,
questions: [],
candidates: [
{
candidate_id: 'C-1',
candidate_ref: 'candidate-1',
worker_id: 'W-1',
workflow_id: 'WF-STY-001',
extracted_slots: { due_at: '2026-08-31' },
missing_slots: [],
confidence: 0.92,
},
{
candidate_id: 'C-2',
candidate_ref: 'candidate-2',
worker_id: 'W-1',
workflow_id: 'WF-PAY-001',
extracted_slots: {},
missing_slots: [],
confidence: 0.72,
},
],
created_at: '2026-08-08T00:00:00Z',
updated_at: '2026-08-08T00:00:01Z',
}

const CATALOG = {
bundle_id: 'bundle-1',
bundle_version: '1',
bundle_status: 'ACTIVE',
source_repository: 'fowoco/knowledge',
generated_at: '2026-08-08T00:00:00Z',
workflows: [
{
workflow_id: 'WF-STY-001',
name: '체류기간 연장 처리',
intent: 'EXPIRY_RENEWAL',
sensitivity: 'NORMAL',
supported_task_types: [],
required_slots: [],
checklist_items: [],
completion_evidence: [],
source_ids: [],
},
{
workflow_id: 'WF-PAY-001',
name: '급여 자료 확인',
intent: 'PAYROLL_EXPLANATION',
sensitivity: 'NORMAL',
supported_task_types: [],
required_slots: [],
checklist_items: [],
completion_evidence: [],
source_ids: [],
},
],
}

beforeEach(() => {
vi.stubGlobal('fetch', vi.fn())
})

afterEach(() => vi.unstubAllGlobals())

function renderReview() {
render(
<MemoryRouter initialEntries={['/tasks/new/review']}>
<Routes>
<Route path="/tasks/new/review" element={<AiRunReview initialRun={RUN} />} />
<Route path="/tasks/:taskId" element={<p>생성된 업무 상세</p>} />
<Route path="/tasks" element={<p>업무함</p>} />
</Routes>
</MemoryRouter>,
)
}

describe('AiRunReview candidate decision', () => {
it('accepts one candidate, discards the others, and opens the created task', async () => {
vi.mocked(fetch).mockImplementation((input) => {
const url = String(input)
if (url.includes('/workflow-catalogs')) return Promise.resolve(jsonResponse(CATALOG))
if (url.includes('/workers')) {
return Promise.resolve(
jsonResponse({
items: [{ worker_id: 'W-1', display_name: '응웬반A' }],
page: 0,
size: 100,
total_elements: 1,
}),
)
}
if (url.includes('/candidate-decisions')) {
return Promise.resolve(
jsonResponse({
decision_batch_id: 'BATCH-1',
ai_run_id: RUN.ai_run_id,
case_id: 'CASE-1',
task_ids: ['TASK-1'],
decisions: [
{ candidate_id: 'C-1', action: 'ACCEPT' },
{ candidate_id: 'C-2', action: 'DISCARD' },
],
run_version: 4,
}),
)
}
return Promise.reject(new Error(`Unexpected request: ${url}`))
})
const user = userEvent.setup()
renderReview()

expect(screen.getByText('선택 필요')).toBeInTheDocument()
const createButton = screen.getByRole('button', { name: '선택한 업무 생성' })
expect(createButton).toBeDisabled()

const candidateButton = await screen.findByRole('button', {
name: '체류기간 연장 처리 선택',
})
await user.click(candidateButton)
expect(screen.getByText('1개 선택')).toBeInTheDocument()
expect(createButton).toBeEnabled()

await user.click(createButton)

expect(await screen.findByText('생성된 업무 상세')).toBeInTheDocument()
const decisionCall = vi
.mocked(fetch)
.mock.calls.find(([url]) => String(url).includes('/candidate-decisions'))
expect(new Headers(decisionCall?.[1]?.headers).get('Idempotency-Key')).toBeTruthy()
expect(JSON.parse(String(decisionCall?.[1]?.body))).toEqual({
expected_run_version: 3,
decisions: [
{ candidate_id: 'C-1', action: 'ACCEPT' },
{ candidate_id: 'C-2', action: 'DISCARD' },
],
})
})

it('does not allow a candidate with missing slots to be selected', async () => {
vi.mocked(fetch).mockImplementation((input) => {
const url = String(input)
if (url.includes('/workflow-catalogs')) return Promise.resolve(jsonResponse(CATALOG))
if (url.includes('/workers')) {
return Promise.resolve(jsonResponse({ items: [], page: 0, size: 100, total_elements: 0 }))
}
return Promise.reject(new Error(`Unexpected request: ${url}`))
})
render(
<MemoryRouter>
<AiRunReview
initialRun={{
...RUN,
candidates: [{ ...RUN.candidates[0], missing_slots: ['due_at'] }],
}}
/>
</MemoryRouter>,
)

expect(await screen.findByRole('button', { name: '체류기간 연장 처리 선택' })).toBeDisabled()
expect(screen.getByRole('button', { name: '선택한 업무 생성' })).toBeDisabled()
})
})
Loading