|
| 1 | +/** @vitest-environment jsdom */ |
| 2 | +import { act } from 'react' |
| 3 | +import { flushMicrotasks } from '@sim/testing/helpers/async' |
| 4 | +import { jsonResponse } from '@sim/testing/helpers/http' |
| 5 | +import { authClientMock, authClientMockFns } from '@sim/testing/mocks/auth-client.mock' |
| 6 | +import { nextNavigationMock } from '@sim/testing/mocks/next-navigation.mock' |
| 7 | +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' |
| 8 | +import { NuqsTestingAdapter } from 'nuqs/adapters/testing' |
| 9 | +import { createRoot, type Root } from 'react-dom/client' |
| 10 | +import { afterEach, beforeEach, expect, it, vi } from 'vitest' |
| 11 | +import { SettingsNavigationGuard } from '@/components/settings/settings-navigation-guard' |
| 12 | +import { type BenchmarkCase, updateBenchmarkContract } from '@/lib/api/contracts/benchmarks' |
| 13 | +import { BenchmarkConsole } from '@/app/benchmark/benchmark-console' |
| 14 | +import { useSettingsDirtyStore } from '@/stores/settings/dirty/store' |
| 15 | + |
| 16 | +vi.mock('@/lib/auth/auth-client', () => authClientMock) |
| 17 | +vi.mock('next/navigation', () => nextNavigationMock) |
| 18 | + |
| 19 | +let root: Root |
| 20 | +let container: HTMLDivElement |
| 21 | +let client: QueryClient |
| 22 | +let saved: BenchmarkCase |
| 23 | +let patches: unknown[] |
| 24 | +let failSave: boolean |
| 25 | + |
| 26 | +async function settle(action: () => void) { |
| 27 | + await act(async () => { |
| 28 | + action() |
| 29 | + await flushMicrotasks() |
| 30 | + }) |
| 31 | + await act(async () => { |
| 32 | + await vi.advanceTimersByTimeAsync(100) |
| 33 | + await flushMicrotasks() |
| 34 | + }) |
| 35 | +} |
| 36 | + |
| 37 | +function button(name: string) { |
| 38 | + const value = [...document.querySelectorAll<HTMLButtonElement>('button')].find( |
| 39 | + (node) => node.textContent?.trim() === name |
| 40 | + ) |
| 41 | + if (!value) throw new Error(`Missing button ${name}`) |
| 42 | + return value |
| 43 | +} |
| 44 | + |
| 45 | +function field(selector: string) { |
| 46 | + const value = document.querySelector<HTMLTextAreaElement>(selector) |
| 47 | + if (!value) throw new Error(`Missing field ${selector}`) |
| 48 | + return value |
| 49 | +} |
| 50 | + |
| 51 | +async function edit(selector: string, value: string) { |
| 52 | + const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set |
| 53 | + if (!setter) throw new Error('Missing textarea setter') |
| 54 | + await settle(() => { |
| 55 | + const target = field(selector) |
| 56 | + setter.call(target, value) |
| 57 | + target.dispatchEvent(new Event('input', { bubbles: true })) |
| 58 | + }) |
| 59 | +} |
| 60 | + |
| 61 | +beforeEach(async () => { |
| 62 | + vi.useFakeTimers() |
| 63 | + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) |
| 64 | + authClientMockFns.mockUseSession.mockReturnValue({ |
| 65 | + data: { user: { id: 'operator' } }, |
| 66 | + isPending: false, |
| 67 | + error: null, |
| 68 | + }) |
| 69 | + useSettingsDirtyStore.getState().reset() |
| 70 | + patches = [] |
| 71 | + failSave = false |
| 72 | + saved = { |
| 73 | + id: 'case', |
| 74 | + organizationId: 'org', |
| 75 | + userId: 'operator', |
| 76 | + runAsUserId: 'user', |
| 77 | + sourceWorkspaceId: 'workspace', |
| 78 | + name: 'Fixture benchmark', |
| 79 | + version: 1, |
| 80 | + runningStage: null, |
| 81 | + leaseExpiresAt: null, |
| 82 | + attemptId: null, |
| 83 | + plannerChatId: null, |
| 84 | + error: null, |
| 85 | + createdAt: '2026-01-01T00:00:00.000Z', |
| 86 | + updatedAt: '2026-01-01T00:00:00.000Z', |
| 87 | + artifacts: { |
| 88 | + taskBrief: 'Prepare a workflow', |
| 89 | + referenceSpec: 'Send the report to Operations.', |
| 90 | + redactedSpec: '', |
| 91 | + blanks: [], |
| 92 | + generatedSpec: null, |
| 93 | + reconstruction: null, |
| 94 | + grade: null, |
| 95 | + }, |
| 96 | + } |
| 97 | + vi.stubGlobal( |
| 98 | + 'fetch', |
| 99 | + vi.fn<typeof fetch>(async (input, init) => { |
| 100 | + const url = new URL(String(input), 'http://localhost') |
| 101 | + if (url.pathname === '/api/benchmarks/organizations') |
| 102 | + return jsonResponse({ |
| 103 | + organizations: [{ id: 'other-org', name: 'Other organization' }], |
| 104 | + selected: { id: 'org', name: 'Fixture organization' }, |
| 105 | + nextCursor: null, |
| 106 | + }) |
| 107 | + if (url.pathname.endsWith('/users')) |
| 108 | + return jsonResponse({ |
| 109 | + users: [{ id: 'other-user', name: 'Other user', email: 'other@example.test' }], |
| 110 | + selected: { id: 'user', name: 'Fixture user', email: 'fixture@example.test' }, |
| 111 | + nextCursor: null, |
| 112 | + }) |
| 113 | + if (url.pathname.endsWith('/workspaces')) |
| 114 | + return jsonResponse({ |
| 115 | + workspaces: [{ id: 'workspace', name: 'Fixture workspace' }], |
| 116 | + canPlan: true, |
| 117 | + nextCursor: null, |
| 118 | + }) |
| 119 | + if (url.pathname.endsWith('/runs')) return jsonResponse({ runs: [], nextCursor: null }) |
| 120 | + if (url.pathname.endsWith('/benchmarks')) |
| 121 | + return jsonResponse({ benchmarks: [saved], nextCursor: null }) |
| 122 | + if (url.pathname.endsWith('/benchmarks/case')) { |
| 123 | + if (init?.method === 'PATCH') { |
| 124 | + const schema = updateBenchmarkContract.body |
| 125 | + if (!schema) throw new Error('Missing benchmark update contract') |
| 126 | + const patch = schema.parse(JSON.parse(String(init.body))) |
| 127 | + patches.push(patch) |
| 128 | + if (failSave) return jsonResponse({ error: 'Save unavailable' }, 503) |
| 129 | + const { version, name, ...artifacts } = patch |
| 130 | + saved = { |
| 131 | + ...saved, |
| 132 | + name: name ?? saved.name, |
| 133 | + version: version + 1, |
| 134 | + artifacts: { ...saved.artifacts, ...artifacts }, |
| 135 | + } |
| 136 | + } |
| 137 | + return jsonResponse({ benchmark: saved }) |
| 138 | + } |
| 139 | + throw new Error(`Unexpected fixture request ${url.pathname}`) |
| 140 | + }) |
| 141 | + ) |
| 142 | + client = new QueryClient({ |
| 143 | + defaultOptions: { queries: { retry: false, gcTime: Number.POSITIVE_INFINITY } }, |
| 144 | + }) |
| 145 | + container = document.createElement('div') |
| 146 | + document.body.append(container) |
| 147 | + root = createRoot(container) |
| 148 | + await settle(() => |
| 149 | + root.render( |
| 150 | + <QueryClientProvider client={client}> |
| 151 | + <NuqsTestingAdapter searchParams='?organization=org&user=user&benchmark=case' hasMemory> |
| 152 | + <SettingsNavigationGuard /> |
| 153 | + <BenchmarkConsole /> |
| 154 | + </NuqsTestingAdapter> |
| 155 | + </QueryClientProvider> |
| 156 | + ) |
| 157 | + ) |
| 158 | + expect(field('#reference-spec').value).toBe(saved.artifacts.referenceSpec) |
| 159 | +}) |
| 160 | + |
| 161 | +afterEach(async () => { |
| 162 | + await act(async () => root.unmount()) |
| 163 | + client.clear() |
| 164 | + container.remove() |
| 165 | + useSettingsDirtyStore.getState().reset() |
| 166 | + vi.useRealTimers() |
| 167 | +}) |
| 168 | + |
| 169 | +async function navigate(destination: string) { |
| 170 | + if (destination === 'Organization' || destination === 'Run as user') { |
| 171 | + const combo = document.querySelector<HTMLElement>( |
| 172 | + `[role="combobox"][aria-label="${destination}"]` |
| 173 | + ) |
| 174 | + if (!combo) throw new Error(`Missing selection ${destination}`) |
| 175 | + await settle(() => combo.click()) |
| 176 | + const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((node) => |
| 177 | + node.textContent?.includes( |
| 178 | + destination === 'Organization' ? 'Other organization' : 'Other user' |
| 179 | + ) |
| 180 | + ) |
| 181 | + if (!option) throw new Error(`Missing option ${destination}`) |
| 182 | + await settle(() => option.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))) |
| 183 | + } else await settle(() => button(destination).click()) |
| 184 | +} |
| 185 | + |
| 186 | +it.each(['Run history', 'All benchmarks', 'New benchmark', 'Organization', 'Run as user'])( |
| 187 | + 'keeps the reference until navigation to %s is explicitly discarded', |
| 188 | + async (destination) => { |
| 189 | + await edit('#reference-spec', 'Unsaved reference') |
| 190 | + await navigate(destination) |
| 191 | + expect(field('#reference-spec').value).toBe('Unsaved reference') |
| 192 | + await settle(() => button('Keep editing').click()) |
| 193 | + expect(field('#reference-spec').value).toBe('Unsaved reference') |
| 194 | + expect(patches).toEqual([]) |
| 195 | + await navigate(destination) |
| 196 | + await settle(() => button('Discard changes').click()) |
| 197 | + expect(document.querySelector('#reference-spec')).toBeNull() |
| 198 | + expect(patches).toEqual([]) |
| 199 | + expect(useSettingsDirtyStore.getState().isDirty).toBe(false) |
| 200 | + } |
| 201 | +) |
| 202 | + |
| 203 | +it('keeps applied blanks through a cancelled navigation and failed save, then saves exact edits', async () => { |
| 204 | + await settle(() => button('Edit JSON').click()) |
| 205 | + const textareas = [...document.querySelectorAll<HTMLTextAreaElement>('[role="dialog"] textarea')] |
| 206 | + expect(textareas).toHaveLength(2) |
| 207 | + const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set |
| 208 | + if (!setter) throw new Error('Missing textarea setter') |
| 209 | + await settle(() => { |
| 210 | + for (const [index, value] of [ |
| 211 | + 'Send the report to [[BLANK:team]].', |
| 212 | + '{"team":"Operations"}', |
| 213 | + ].entries()) { |
| 214 | + setter.call(textareas[index], value) |
| 215 | + textareas[index].dispatchEvent(new Event('input', { bubbles: true })) |
| 216 | + } |
| 217 | + }) |
| 218 | + await settle(() => button('Apply mapping').click()) |
| 219 | + await navigate('Run history') |
| 220 | + await settle(() => button('Keep editing').click()) |
| 221 | + expect(field('[aria-label="Redacted reference spec"]').value).toBe( |
| 222 | + 'Send the report to [[BLANK:team]].' |
| 223 | + ) |
| 224 | + failSave = true |
| 225 | + await settle(() => button('Save changes').click()) |
| 226 | + await navigate('All benchmarks') |
| 227 | + await settle(() => button('Keep editing').click()) |
| 228 | + failSave = false |
| 229 | + await settle(() => button('Save changes').click()) |
| 230 | + expect(patches).toEqual([ |
| 231 | + { |
| 232 | + version: 1, |
| 233 | + redactedSpec: 'Send the report to [[BLANK:team]].', |
| 234 | + blanks: [{ id: 'team', answer: 'Operations' }], |
| 235 | + }, |
| 236 | + { |
| 237 | + version: 1, |
| 238 | + redactedSpec: 'Send the report to [[BLANK:team]].', |
| 239 | + blanks: [{ id: 'team', answer: 'Operations' }], |
| 240 | + }, |
| 241 | + ]) |
| 242 | + await navigate('Run history') |
| 243 | + await navigate('Current run') |
| 244 | + expect(field('[aria-label="Redacted reference spec"]').value).toBe( |
| 245 | + 'Send the report to [[BLANK:team]].' |
| 246 | + ) |
| 247 | + expect(useSettingsDirtyStore.getState().isDirty).toBe(false) |
| 248 | +}) |
0 commit comments