// ATDD (RED) для Story 3.9 — UI переноса Resource: export Draft, export точной Published // Version, импорт envelope как нового owned Draft, состояния RU/EN и stale-response. // // Источники: `epics.md`:2614–2645 (AC2/AC3), `docs/acceptance-test-plan.md`:1054–1065 // (AT-3.9-02/03), `_bmad-output/test-artifacts/test-design-epic-3.md`:116 (3.9-E2E-A/B), // принятый spec `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-resource-portability/spec.md` §5. // // Состояние на этой стадии: страница `/resources` умеет list/inspect/edit/publish/archive // (Story 3.6/3.7), но импорт/экспорт отсутствуют. Каждый тест доходит до конкретного // отсутствующего пользовательского действия и падает на реальном отсутствии UI, а не на setup; // seed/publish — существующие принятые контракты (позитивный контроль харнесса). // // Требуемый UI-контракт (data-testid — часть ATDD): // resource-export, resource-published-export, resource-import, resource-import-file, // resource-import-submit, resource-import-confirm(+ -confirm-accept/-cancel), // resource-import-status, resource-import-error, resource-portability-stale. // Импорт: структурная проверка файла до подтверждения, подтверждение с metadata и явным // «новый Draft, без публикации», затем реальный POST .../resources/import. // // Запуск: npm --prefix apps/ui run e2e -- tests/e2e/resources-story39.spec.js --workers=1 --retries=0 const fs = require('fs'); const { createHash } = require('crypto'); const { test, expect } = require('@playwright/test'); const { browserJson, createResourceDraft, getCurrentWorkspace, localized, login, readResourceDownload, readResourceVersionDownload, uniqueName, } = require('./helpers'); const EXPORT = '[data-testid="resource-export"]'; const PUBLISHED_EXPORT = '[data-testid="resource-published-export"]'; const IMPORT = '[data-testid="resource-import"]'; const IMPORT_FILE = '[data-testid="resource-import-file"]'; const IMPORT_SUBMIT = '[data-testid="resource-import-submit"]'; const IMPORT_CONFIRM = '[data-testid="resource-import-confirm"]'; const IMPORT_CONFIRM_ACCEPT = '[data-testid="resource-import-confirm-accept"]'; const IMPORT_CANCEL = '[data-testid="resource-import-cancel"]'; const IMPORT_STATUS = '[data-testid="resource-import-status"]'; const IMPORT_ERROR = '[data-testid="resource-import-error"]'; const STALE_ALERT = '[data-testid="resource-portability-stale"]'; const META_NAME = '[data-testid="resource-meta-name"]'; const META_DIGEST = '[data-testid="resource-meta-digest"]'; const STATUS = '[data-testid="resource-status"]'; const PUBLISHED = '[data-testid="resource-published"]'; const PUBLISHED_VERSION = '[data-testid="resource-published-version"]'; const LIST_ITEM = '[data-testid="resource-list-item"]'; const DRAFT_STATUS = /draft|черновик/i; const PUBLISHED_STATUS = /published|опубликован/i; const IMPORTED_NOTICE = /import|импорт/i; const OVERSIZE_ERROR = /too large|exceed|размер|превыш|limit/i; const EXPORT_LABEL = /export|экспорт/i; const IMPORT_LABEL = /import|импорт/i; const RU_EXPORT = /экспорт/i; const RU_IMPORT = /импорт/i; function sha256Hex(bytes) { return createHash('sha256').update(bytes).digest('hex'); } function textMetadata(name) { return { uri: `crank://e2e/${name}`, name, description: 'story39 ui export fixture', kind: 'text', mime_type: 'text/plain', sensitivity: 'internal', }; } function portableEnvelope(metadata, bytes, source = { kind: 'draft', version: 1 }) { return { format: 'crank-resource-portability', version: 1, resource: { uri: metadata.uri, name: metadata.name, description: metadata.description, kind: metadata.kind, mime_type: metadata.mime_type, sensitivity: metadata.sensitivity, }, source, content: { size_bytes: bytes.length, digest: sha256Hex(bytes), base64: Buffer.from(bytes).toString('base64'), }, }; } async function seedDraft(page, workspaceId, metadata, bytes, filename, mime) { const created = await createResourceDraft(page, workspaceId, metadata, bytes, filename, mime); expect( created.status, `seeding the Draft through the accepted create contract must succeed: ${created.text}`, ).toBe(201); return created.json.resource.resource_id || created.json.resource.id; } async function readCard(page, workspaceId, resourceId) { return browserJson(page, 'GET', `/api/admin/workspaces/${workspaceId}/resources/${resourceId}`); } async function listResources(page, workspaceId) { return browserJson(page, 'GET', `/api/admin/workspaces/${workspaceId}/resources`); } /// Счётчик реально отправленных POST на импорт: структурно неверный файл не должен /// доходить до сети. function countImportPosts(page) { const counter = { count: 0 }; page.on('request', (request) => { if (request.method() === 'POST' && /\/resources\/import$/.test(request.url())) { counter.count += 1; } }); return counter; } async function openResource(page, resourceId) { await page.goto(`/resources?resource_id=${encodeURIComponent(resourceId)}`); await expect(page.locator(META_NAME)).not.toBeEmpty(); } async function publishThroughApi(page, workspaceId, resourceId) { const card = await readCard(page, workspaceId, resourceId); return browserJson( page, 'POST', `/api/admin/workspaces/${workspaceId}/resources/${resourceId}/publish`, { expected_updated_at: card.resource.updated_at }, ); } async function setImportFile(page, content) { await page.locator(IMPORT_FILE).setInputFiles({ name: 'resource.crank-resource.json', mimeType: 'application/json', buffer: Buffer.from(typeof content === 'string' ? content : JSON.stringify(content)), }); } async function importThroughUi(page, envelope, { accept = true } = {}) { await setImportFile(page, envelope); await page.locator(IMPORT_SUBMIT).click(); await expect( page.locator(IMPORT_CONFIRM), 'a structurally valid envelope must ask for confirmation before creating a Draft', ).toBeVisible(); if (accept) { await page.locator(IMPORT_CONFIRM_ACCEPT).click(); } else { await page.locator(IMPORT_CANCEL).click(); } } async function downloadEnvelope(page, selector) { await expect( page.locator(selector), 'the portability export action must exist on the Resource screen', ).toBeVisible(); const [download] = await Promise.all([ page.waitForEvent('download'), page.locator(selector).click(), ]); const path = await download.path(); const raw = fs.readFileSync(path, 'utf8'); return { download, raw, envelope: JSON.parse(raw) }; } function expectAllowlistedEnvelope(envelope, { metadata, bytes, source }) { expect(envelope.format).toBe('crank-resource-portability'); expect(envelope.version).toBe(1); expect(Object.keys(envelope).sort()).toEqual([ 'content', 'format', 'resource', 'source', 'version', ]); expect(Object.keys(envelope.resource).sort()).toEqual([ 'description', 'kind', 'mime_type', 'name', 'sensitivity', 'uri', ]); expect(Object.keys(envelope.content).sort()).toEqual(['base64', 'digest', 'size_bytes']); expect(envelope.resource).toEqual({ uri: metadata.uri, name: metadata.name, description: metadata.description, kind: metadata.kind, mime_type: metadata.mime_type, sensitivity: metadata.sensitivity, }); expect(envelope.source).toEqual(source); expect(envelope.content.size_bytes).toBe(bytes.length); expect(envelope.content.digest).toBe(sha256Hex(bytes)); expect(Buffer.from(envelope.content.base64, 'base64')).toEqual(Buffer.from(bytes)); // Манифест не содержит внутренних owning/хранилищных/ownership полей. const manifest = JSON.stringify({ ...envelope, content: { ...envelope.content, base64: '' }, }); expect(manifest).not.toMatch( /artifact|owner|workspace|resource_id|storage|credential|"status"|published_at/i, ); expect(manifest).not.toMatch(/\/home\/|\.tmp\/|postgres:\/\//); } test('story39_at02_export_import_ui_creates_new_owned_draft_and_never_publishes', async ({ page, }) => { await login(page); const workspace = await getCurrentWorkspace(page); expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy(); await page.goto('/resources'); const name = uniqueName('story39_export'); const metadata = textMetadata(name); const bytes = Buffer.from('story39 ui export body\n', 'utf8'); const sourceId = await seedDraft( page, workspace.id, metadata, bytes, 'export.txt', 'text/plain', ); await openResource(page, sourceId); // AC2/AC3: экспорт Draft из UI — реальный скачанный envelope с digest и bytes. const draftExport = await downloadEnvelope(page, EXPORT); expectAllowlistedEnvelope(draftExport.envelope, { metadata, bytes, source: { kind: 'draft', version: 1 }, }); // AC1: импорт всегда создаёт новый Draft текущего владельца, без автопубликации. const targetName = uniqueName('story39_imported'); const importedEnvelope = portableEnvelope( { ...metadata, uri: `crank://e2e/${targetName}`, name: targetName }, bytes, ); const before = await listResources(page, workspace.id); const beforeCount = before.items.length; await setImportFile(page, importedEnvelope); await page.locator(IMPORT_SUBMIT).click(); await expect(page.locator(IMPORT_CONFIRM), 'import must be confirmed explicitly').toBeVisible(); await expect(page.locator(IMPORT_CONFIRM)).toContainText(targetName); await expect( page.locator(IMPORT_CONFIRM), 'the confirmation must state that a new Draft (not a publication) is created', ).toContainText(DRAFT_STATUS); const untouched = await listResources(page, workspace.id); expect( untouched.items.length, 'nothing may be created before the confirmation is accepted', ).toBe(beforeCount); await page.locator(IMPORT_CONFIRM_ACCEPT).click(); await expect(page.locator(IMPORT_STATUS)).toHaveText(IMPORTED_NOTICE); const after = await listResources(page, workspace.id); expect(after.items.length, 'the import must add exactly one Draft').toBe(beforeCount + 1); const importedCard = after.items.find((item) => item.resource.uri === `crank://e2e/${targetName}`); expect(importedCard, 'the imported Draft must appear in the list').toBeTruthy(); const importedId = importedCard.resource.resource_id; expect(importedId, 'import must create a new Resource identity').not.toBe(sourceId); expect(importedCard.resource.status).toBe('draft'); expect(importedCard.resource.latest_published_version).toBeNull(); // UI явно различает Draft и Published Version и показывает точный digest. await openResource(page, importedId); await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS); await expect(page.locator(PUBLISHED)).toHaveCount(0); await expect(page.locator(META_DIGEST)).toHaveText(sha256Hex(bytes)); const downloaded = await readResourceDownload(page, workspace.id, importedId); expect(downloaded.bodyBase64).toBe(bytes.toString('base64')); // Публикаций нет ни в карточке, ни по точному version-контракту. await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${importedId}/versions/1`, undefined, [404], ); // AC2: экспорт точной Published Version — после явной публикации того же Draft. await publishThroughApi(page, workspace.id, importedId); await openResource(page, importedId); await expect(page.locator(PUBLISHED)).toBeVisible(); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); const publishedExport = await downloadEnvelope(page, PUBLISHED_EXPORT); expectAllowlistedEnvelope(publishedExport.envelope, { metadata: { ...metadata, uri: `crank://e2e/${targetName}`, name: targetName }, bytes, source: { kind: 'published', version: 1 }, }); const versionDownload = await readResourceVersionDownload(page, workspace.id, importedId, 1); expect( versionDownload.bodyBase64, 'the published export must carry the exact version bytes', ).toBe(bytes.toString('base64')); }); test('story39_at02_ru_en_states_and_exact_version_distinction', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const name = uniqueName('story39_locale'); const metadata = textMetadata(name); const bytes = Buffer.from('story39 locale fixture\n', 'utf8'); const id = await seedDraft(page, workspace.id, metadata, bytes, 'locale.txt', 'text/plain'); const labels = {}; for (const locale of ['en', 'ru']) { await page.evaluate((language) => localStorage.setItem('crank_lang', language), locale); await openResource(page, id); await expect(page.locator(IMPORT), 'the import section must be localized').toBeVisible(); const exportLabel = (await page.locator(EXPORT).innerText()).trim(); const importLabel = (await page.locator(IMPORT).innerText()).trim(); labels[locale] = { exportLabel, importLabel }; expect(exportLabel, `${locale}: export action must be labelled`).toMatch(EXPORT_LABEL); expect(importLabel, `${locale}: import section must be labelled`).toMatch(IMPORT_LABEL); if (locale === 'ru') { expect(exportLabel).toMatch(RU_EXPORT); expect(importLabel).toMatch(RU_IMPORT); await expect(page.locator(STATUS)).toHaveText(localized('draft', 'черновик')); } else { expect(exportLabel).not.toMatch(RU_EXPORT); expect(importLabel).not.toMatch(RU_IMPORT); await expect(page.locator(STATUS)).toHaveText(/draft/i); } // Черновик без публикаций не показывает блок точной версии. await expect(page.locator(PUBLISHED)).toHaveCount(0); } expect( labels.en.exportLabel, 'RU and EN labels must be different translations, not one hardcoded string', ).not.toBe(labels.ru.exportLabel); // Точная Published Version отображается как отдельный снимок, отличимый от Draft. await publishThroughApi(page, workspace.id, id); await openResource(page, id); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); await expect(page.locator(PUBLISHED)).toBeVisible(); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISHED_EXPORT)).toBeVisible(); }); test('story39_at02_import_validation_and_oversize_errors_are_safe', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const name = uniqueName('story39_invalid'); const metadata = textMetadata(name); const bytes = Buffer.from('story39 invalid fixture\n', 'utf8'); const seedId = await seedDraft(page, workspace.id, metadata, bytes, 'invalid.txt', 'text/plain'); await openResource(page, seedId); await expect(page.locator(IMPORT)).toBeVisible(); const countDrafts = async () => (await listResources(page, workspace.id)).items.length; const before = await countDrafts(); // Malformed JSON — validation state до подтверждения, ничего не отправлено. await setImportFile(page, '{'); await page.locator(IMPORT_SUBMIT).click(); await expect(page.locator(IMPORT_ERROR), 'malformed envelope must be reported safely').toBeVisible(); await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0); const malformedText = await page.locator(IMPORT_ERROR).innerText(); expect(malformedText).not.toMatch(/\/home\/|\.tmp\/|artifact/); expect(await countDrafts(), 'malformed import must not create a Draft').toBe(before); // Структурно некорректные, но валидные JSON: дробный size_bytes, неизвестный ключ и // source.version вне серверного u32. Ошибка до подтверждения, POST не отправлен. const importPosts = countImportPosts(page); const structuralDefects = [ { label: 'fractional size_bytes', envelope: { ...portableEnvelope(metadata, bytes), content: { ...portableEnvelope(metadata, bytes).content, size_bytes: 1.5 } }, }, { label: 'unknown key', envelope: { ...portableEnvelope(metadata, bytes), content: { ...portableEnvelope(metadata, bytes).content, storage_path: '/home/leak' }, }, }, { label: 'source.version above u32', envelope: { ...portableEnvelope(metadata, bytes), source: { kind: 'draft', version: 4_294_967_296 }, }, }, ]; for (const defect of structuralDefects) { defect.envelope.resource.uri = `crank://e2e/${uniqueName('story39_structural')}`; await setImportFile(page, defect.envelope); await page.locator(IMPORT_SUBMIT).click(); await expect( page.locator(IMPORT_ERROR), `${defect.label} must be rejected before confirmation`, ).toBeVisible(); await expect( page.locator(IMPORT_CONFIRM), `${defect.label} must never reach the confirmation step`, ).toHaveCount(0); const text = await page.locator(IMPORT_ERROR).innerText(); expect(text, `${defect.label}: the error must stay safe`).not.toMatch( /\/home\/|\.tmp\/|artifact|leak/, ); } expect(importPosts.count, 'structurally invalid envelopes must not be POSTed').toBe(0); expect(await countDrafts(), 'structurally invalid imports must not create a Draft').toBe(before); // Digest mismatch — отказ сервера после подтверждения, без создания Draft. const digestEnvelope = portableEnvelope(metadata, bytes); digestEnvelope.resource.uri = `crank://e2e/${uniqueName('story39_bad_digest')}`; digestEnvelope.content.digest = sha256Hex(Buffer.from('different body')); await importThroughUi(page, digestEnvelope); await expect(page.locator(IMPORT_ERROR)).toBeVisible(); const digestText = await page.locator(IMPORT_ERROR).innerText(); expect(digestText).not.toMatch(/\/home\/|\.tmp\/|artifact|story39 invalid fixture/); expect(await countDrafts(), 'a digest mismatch must not create a Draft').toBe(before); // Oversized content — серверный 413, безопасное сообщение, без создания Draft. const oversizedBytes = Buffer.alloc(300 * 1024, 0x61); const oversizedEnvelope = portableEnvelope( { ...metadata, uri: `crank://e2e/${uniqueName('story39_oversized')}`, name: uniqueName('story39_oversized'), }, oversizedBytes, ); await importThroughUi(page, oversizedEnvelope); await expect(page.locator(IMPORT_ERROR)).toBeVisible(); await expect(page.locator(IMPORT_ERROR)).toHaveText(OVERSIZE_ERROR); expect(await countDrafts(), 'an oversized import must not create a Draft').toBe(before); }); test('story39_at03_stale_selection_never_applies_portability_response', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const firstName = uniqueName('story39_stale_a'); const secondName = uniqueName('story39_stale_b'); const firstId = await seedDraft( page, workspace.id, textMetadata(firstName), Buffer.from('story39 stale first\n', 'utf8'), 'a.txt', 'text/plain', ); const secondId = await seedDraft( page, workspace.id, textMetadata(secondName), Buffer.from('story39 stale second\n', 'utf8'), 'b.txt', 'text/plain', ); // Network barrier: задержка реального ответа, не подмена контракта. let releaseResponse; const responseDelivered = new Promise((resolve) => { releaseResponse = resolve; }); await page.route('**/resources/*/export*', async (route) => { await new Promise((resolve) => setTimeout(resolve, 1_500)); await route.continue().catch(() => {}); releaseResponse(); }); let downloads = 0; page.on('download', () => { downloads += 1; }); await openResource(page, firstId); await expect( page.locator(EXPORT), 'the portability export action must exist before the stale-response case', ).toBeVisible(); await page.locator(EXPORT).click(); // Пользователь меняет выбор до прихода ответа прежнего Resource. await page.locator(`${LIST_ITEM}[data-resource-id="${secondId}"]`).click(); await expect(page.locator(META_NAME)).toHaveText(secondName); // Барьер — фактическая обработка позднего ответа (stale-alert), а не фиксированный sleep. await expect( page.locator(STALE_ALERT), 'a stale-response state must be visible to the user', ).toBeVisible(); await responseDelivered; // Небольшая пауза нужна только чтобы асинхронное событие download успело проявиться // после уже случившейся обработки ответа; доказательством служит alert выше. await page.waitForTimeout(200); expect(downloads, 'a stale export response must not start a download').toBe(0); await expect(page.locator(META_NAME), 'the new selection must stay intact').toHaveText( secondName, ); await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS); }); // AC2/AC3: отмена подтверждения не создаёт Draft; поздний ответ импорта после смены // выбора не приписывается другой карточке и виден как stale. test('story39_at03_import_cancel_and_stale_response_are_safe', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const firstId = await seedDraft( page, workspace.id, textMetadata(uniqueName('story39_cancel_a')), Buffer.from('story39 cancel a\n', 'utf8'), 'a.txt', 'text/plain', ); const secondName = uniqueName('story39_import_stale_b'); const secondId = await seedDraft( page, workspace.id, textMetadata(secondName), Buffer.from('story39 import stale b\n', 'utf8'), 'b.txt', 'text/plain', ); await openResource(page, firstId); const countDrafts = async () => (await listResources(page, workspace.id)).items.length; const before = await countDrafts(); const bytes = Buffer.from('story39 cancelled import body\n', 'utf8'); // Отказ от подтверждения: структурно корректный файл, но Draft не создаётся. const cancelledName = uniqueName('story39_cancel_target'); await setImportFile(page, portableEnvelope({ ...textMetadata(cancelledName) }, bytes)); await page.locator(IMPORT_SUBMIT).click(); await expect(page.locator(IMPORT_CONFIRM), 'a valid file must ask for confirmation').toBeVisible(); await page.locator(IMPORT_CANCEL).click(); await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0); expect(await countDrafts(), 'a cancelled import must not create a Draft').toBe(before); // Задержанный ответ импорта приходит после смены выбора. await page.route('**/resources/import', async (route) => { if (route.request().method() === 'POST') { await new Promise((resolve) => setTimeout(resolve, 1_500)); } await route.continue().catch(() => {}); }); const staleName = uniqueName('story39_import_stale_target'); await setImportFile(page, portableEnvelope({ ...textMetadata(staleName) }, bytes)); const idleImportLabel = (await page.locator(IMPORT_SUBMIT).innerText()).trim(); await page.locator(IMPORT_SUBMIT).click(); await expect(page.locator(IMPORT_CONFIRM)).toBeVisible(); await page.locator(IMPORT_CONFIRM_ACCEPT).click(); // Пока POST в полёте, кнопка обязана быть disabled, aria-busy и с локализованной // pending-подписью — «в процессе» нельзя спутать с принятым результатом. await expect( page.locator(IMPORT_SUBMIT), 'the submit action must be disabled while the import is in flight', ).toBeDisabled(); await expect(page.locator(IMPORT_SUBMIT)).toHaveAttribute('aria-busy', 'true'); const pendingLabel = (await page.locator(IMPORT_SUBMIT).innerText()).trim(); expect( pendingLabel, 'the pending state must be localized and distinct from the idle label', ).not.toBe(idleImportLabel); expect(pendingLabel).toMatch(IMPORT_LABEL); await page.locator(`${LIST_ITEM}[data-resource-id="${secondId}"]`).click(); await expect(page.locator(META_NAME)).toHaveText(secondName); await expect( page.locator(STALE_ALERT), 'a late import response must be reported as stale, not attributed to another card', ).toBeVisible(); // После завершения запроса кнопка возвращается в исходное состояние. await expect( page.locator(IMPORT_SUBMIT), 'the submit action must be restored after the import response', ).toBeEnabled(); await expect(page.locator(IMPORT_SUBMIT)).toHaveAttribute('aria-busy', 'false'); await expect(page.locator(IMPORT_SUBMIT)).toHaveText(idleImportLabel); await expect( page.locator(IMPORT_STATUS), 'the success notice must not be attributed to the new selection', ).not.toHaveText(IMPORTED_NOTICE); await expect(page.locator(META_NAME), 'the new selection must stay intact').toHaveText( secondName, ); // Серверная правда: задержанный импорт создал ровно один новый Draft. expect(await countDrafts(), 'the delayed import still creates exactly one Draft').toBe( before + 1, ); const listed = await listResources(page, workspace.id); expect( listed.items.some((item) => item.resource.uri === `crank://e2e/${staleName}`), 'the imported Draft must exist in the target workspace', ).toBe(true); });