// ATDD (RED) для оставшихся действий Story 3.7 в UI: AC01 (findings/preview без // публикации), AC05 (create/upload/preview/publish/bind/archive + loading/empty/ // validation/error/confirmation/stale/RU-EN + Draft vs exact Published Version) и // браузерная часть AC06 (archive, stale Agent revision). // // Источники: live Gitea #14 (`.tmp/t_8c38b75f/STORY37-SOURCE.md`, 6 AC), // `docs/acceptance-test-plan.md:1034-1037` (AT-3.7-01/05/06), test-design epic-3 // (3.7-INT-A/B, E3-R3), TL interface decisions (`.tmp/t_8c38b75f/STORY37-NEXT.md` §1-5), // binding review `.tmp/t_cfdcbc3b/TL-CODE-REVIEW-R3.md` и QA `.tmp/t_e42cf4cd/QA-REPORT.md`. // // Состояние на этой стадии: сервер уже публикует immutable версию и принимает typed // `resource_bindings`, но страница `/resources` остаётся экраном черновиков. Каждый // тест доходит до своего отсутствующего пользовательского действия (findings, статус, // публикация, published snapshot, привязка, архив) и падает на реальном отсутствии UI, // а не на setup. Публикация-фикстура для bind/archive/stale-тестов выполняется real // `POST .../publish`, чтобы RED относился именно к проверяемому действию. // // Требуемый UI контракт (его реализует BUILD; селекторы здесь — часть ATDD): // * `resource-status` — локализованный статус Draft/Published/Archived; // * `resource-preview-findings` (+ `resource-preview-findings-empty`) — findings // preview как стабильные коды/сообщения, без bytes содержимого; // * `resource-publish` -> `resource-publish-confirm` (+ `-confirm-accept`, // `resource-publish-cancel`), статус `resource-publish-status`; // * `resource-published` с точными `-version`, `-mime`, `-size`, `-sensitivity`, // `-digest` и ссылкой `-download`; блок не меняется при последующем edit Draft и // восстанавливается после reload (нужен точный указатель версии в карточке: // `latest_published_version`, см. отчёт ATDD); // * `resource-bind-form`, `resource-bind-agent` (select), `resource-bind-version` // (exact version), `resource-bind-submit`, `resource-bind-status`; stale Agent // revision показывается как `resource-bind-stale`; // * `resource-archive` -> `resource-archive-confirm` (+ `-confirm-accept`, // `resource-archive-cancel`), статус `resource-archive-status`; // * `resource-stale` + `resource-reload` — видимый stale precondition и reload. // // Наблюдаемые API-контракты не подменяются: публикация — реальный // `POST .../resources/{id}/publish` с `{expected_updated_at}`; версия — точный // `GET .../versions/{n}` и `/content`; привязка — существующий // `POST .../agents/{id}/bindings` с `resource_bindings`. `page.route` используется // только как network barrier (задержка реального ответа), не как подмена ответа. // // Запуск: npm --prefix apps/ui run e2e -- tests/e2e/resources-story37.spec.js --workers=1 --retries=0 const { createHash } = require('crypto'); const { test, expect } = require('@playwright/test'); const { browserJson, createAgent, createResourceDraft, getCurrentWorkspace, localized, login, readResourceDownload, readResourcePreview, readResourceVersionDownload, uniqueName, updateResourceDraft, } = require('./helpers'); // Существующий экран Draft (Story 3.6) — переиспользуется как положительный контроль. const PREVIEW = '[data-testid="resources-preview"]'; const PREVIEW_TEXT = '[data-testid="resource-preview-text"]'; const META_KIND = '[data-testid="resource-meta-kind"]'; const META_NAME = '[data-testid="resource-meta-name"]'; const META_MIME = '[data-testid="resource-meta-mime"]'; const META_SIZE = '[data-testid="resource-meta-size"]'; const META_DESCRIPTION = '[data-testid="resource-meta-description"]'; const EDIT_DESCRIPTION = '[data-testid="resource-edit-description"]'; const EDIT_CONTENT = '[data-testid="resource-edit-content"]'; const EDIT_SUBMIT = '[data-testid="resource-edit-submit"]'; const EDIT_STATUS = '#resource-edit-status'; // Story 3.7 UI contract. const STATUS = '[data-testid="resource-status"]'; const FINDINGS = '[data-testid="resource-preview-findings"]'; const FINDINGS_EMPTY = '[data-testid="resource-preview-findings-empty"]'; const PUBLISH = '[data-testid="resource-publish"]'; const PUBLISH_CONFIRM = '[data-testid="resource-publish-confirm"]'; const PUBLISH_CONFIRM_ACCEPT = '[data-testid="resource-publish-confirm-accept"]'; const PUBLISH_CANCEL = '[data-testid="resource-publish-cancel"]'; const PUBLISH_STATUS = '[data-testid="resource-publish-status"]'; const STALE = '[data-testid="resource-stale"]'; const RELOAD = '[data-testid="resource-reload"]'; const PUBLISHED = '[data-testid="resource-published"]'; const PUBLISHED_VERSION = '[data-testid="resource-published-version"]'; const PUBLISHED_MIME = '[data-testid="resource-published-mime"]'; const PUBLISHED_SIZE = '[data-testid="resource-published-size"]'; const PUBLISHED_SENSITIVITY = '[data-testid="resource-published-sensitivity"]'; const PUBLISHED_DIGEST = '[data-testid="resource-published-digest"]'; const BIND_FORM = '[data-testid="resource-bind-form"]'; const BIND_AGENT = '[data-testid="resource-bind-agent"]'; const BIND_VERSION = '[data-testid="resource-bind-version"]'; const BIND_SUBMIT = '[data-testid="resource-bind-submit"]'; const BIND_STATUS = '[data-testid="resource-bind-status"]'; const BIND_STALE = '[data-testid="resource-bind-stale"]'; const BIND_AGENT_VERSION = '[data-testid="resource-bind-agent-version"]'; const ARCHIVE = '[data-testid="resource-archive"]'; const ARCHIVE_CONFIRM = '[data-testid="resource-archive-confirm"]'; const ARCHIVE_CONFIRM_ACCEPT = '[data-testid="resource-archive-confirm-accept"]'; const ARCHIVE_CANCEL = '[data-testid="resource-archive-cancel"]'; const ARCHIVE_STATUS = '[data-testid="resource-archive-status"]'; // D1/D4 (TL review R1): видимая безопасная ошибка точного Published GET и явный // reload выбранного Agent после stale revision. const PUBLISHED_ERROR = '[data-testid="resource-published-error"]'; const BIND_RELOAD = '[data-testid="resource-bind-reload"]'; const FINDINGS_ITEM = '[data-testid="resource-preview-finding"]'; const DRAFT_STATUS = /draft|черновик/i; const PUBLISHED_STATUS = /published|опубликован/i; const PUBLISH_LABEL = /publish|публик/i; const ARCHIVE_LABEL = /archive|архив/i; const BIND_LABEL = /bind|привяз/i; const CONFIRM_LABEL = /confirm|подтверд/i; const NO_FINDINGS = /no findings|нарушени|замечан/i; const STALE_MESSAGE = /changed|stale|изменил|устар/i; function sha256Hex(bytes) { return createHash('sha256').update(bytes).digest('hex'); } function textMetadata(name) { return { uri: `crank://e2e/${name}`, name, description: 'story37 ui fixture', kind: 'text', mime_type: 'text/plain', sensitivity: 'internal', }; } function binaryMetadata(name, mime = 'application/octet-stream') { return { uri: `crank://e2e/${name}`, name, description: 'story37 ui binary fixture', kind: 'binary', mime_type: mime, sensitivity: 'internal', }; } /// Создаёт Draft реальным принятым контрактом Story 3.6 (позитивный контроль setup). 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 openResource(page, resourceId) { await page.goto(`/resources?resource_id=${encodeURIComponent(resourceId)}`); await expect(page.locator(PREVIEW)).toBeVisible(); // Положительный контроль: экран действительно загрузил выбранный Draft. await expect(page.locator(META_KIND)).toHaveText(/text|json|binary/); } async function readCard(page, workspaceId, resourceId) { return browserJson(page, 'GET', `/api/admin/workspaces/${workspaceId}/resources/${resourceId}`); } /// Публикация реальным серверным контрактом — фикстура для bind/archive/stale-тестов. 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 startPublish(page) { await expect(page.locator(PUBLISH), 'the screen must offer the publication action').toBeVisible(); await page.locator(PUBLISH).click(); await expect(page.locator(PUBLISH_CONFIRM)).toBeVisible(); await expect(page.locator(PUBLISH_CONFIRM)).toHaveText(CONFIRM_LABEL); } /// Публикация через UI: подтверждение обязательно, ответ — реальный POST. async function publishThroughUi(page) { await startPublish(page); await page.locator(PUBLISH_CONFIRM_ACCEPT).click(); } test('story37_at01_preview_shows_findings_and_never_publishes', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy(); // Существующий empty-state экрана (GREEN-контроль состояний AC05). await page.goto('/resources'); await expect(page.locator('#resources-status')).toHaveText( localized('No Resource selected.', 'Ресурс не выбран.'), ); const textBytes = Buffer.from('story37 preview body\n', 'utf8'); const textName = uniqueName('story37_preview'); const textId = await seedDraft( page, workspace.id, textMetadata(textName), textBytes, 'preview.txt', 'text/plain', ); await openResource(page, textId); await expect(page.locator(META_MIME), 'the exact content type is shown').toHaveText('text/plain'); await expect(page.locator(META_SIZE), 'the exact size is shown').toHaveText(String(textBytes.length)); await expect(page.locator(PREVIEW_TEXT)).toHaveText('story37 preview body\n'); // AC01: findings видны как стабильные коды/сообщения, а не как bytes содержимого. await expect(page.locator(FINDINGS), 'preview must expose a findings region').toBeVisible(); await expect(page.locator(FINDINGS_EMPTY)).toHaveText(NO_FINDINGS); const findingsHtml = await page.locator(FINDINGS).innerHTML(); expect(findingsHtml, 'findings must not embed Resource bytes').not.toContain('story37 preview body'); // AC01: preview не публикует Draft и не создаёт Published Version. await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${textId}/versions/1`, undefined, [404], ); const card = await readCard(page, workspace.id, textId); expect(card.resource.status, 'a preview must not publish the Draft').toBe('draft'); await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS); await expect(page.locator(PUBLISHED)).toHaveCount(0); // AC01: binary bytes не попадают ни в DOM, ни в исходящие запросы (telemetry). const canary = `STORY37_BINARY_CANARY_${Date.now()}`; const binaryBytes = Buffer.from(`\x00\x01${canary}\x02\xff`, 'latin1'); const binaryName = uniqueName('story37_binary'); const binaryId = await seedDraft( page, workspace.id, binaryMetadata(binaryName), binaryBytes, 'canary.bin', 'application/octet-stream', ); const observedRequests = []; page.on('request', (request) => { observedRequests.push(`${request.url()}\n${request.postData() || ''}`); }); await openResource(page, binaryId); await expect(page.locator(PREVIEW_TEXT), 'a binary preview must not render bytes').toHaveText(''); const previewHtml = await page.locator(PREVIEW).innerHTML(); expect(previewHtml, 'binary bytes must not enter the DOM').not.toContain(canary); const preview = await readResourcePreview(page, workspace.id, binaryId); expect(preview.status).toBe(200); expect(preview.json && preview.json.preview ? preview.json.preview.text : null).toBeNull(); expect(preview.json.findings, 'the preview must carry a findings array').toEqual(expect.any(Array)); for (const request of observedRequests) { expect(request, 'binary bytes must not be sent to any telemetry/outgoing request').not.toContain(canary); } // Положительный контроль детекторов: доказать, что та же проверка способна увидеть // утечку, если она есть (иначе «canary не найден» ничего не значит). const domDetectsCanary = await page.evaluate((value) => { const probe = document.createElement('div'); probe.textContent = value; document.body.appendChild(probe); const detected = (document.body.innerHTML || '').includes(value); probe.remove(); return detected; }, canary); expect(domDetectsCanary, 'the DOM canary detector must detect a planted leak').toBe(true); await page.evaluate( (value) => fetch(`/health?canary=${encodeURIComponent(value)}`, { credentials: 'same-origin' }), canary, ); await expect .poll(() => observedRequests.some((request) => request.includes(canary)), { message: 'the outgoing-request canary detector must observe page-originated data', }) .toBe(true); }); test('story37_at05_publish_requires_confirmation_and_keeps_the_published_snapshot', async ({ page, }) => { await login(page); const workspace = await getCurrentWorkspace(page); const original = Buffer.from('story37 publish body\n', 'utf8'); const name = uniqueName('story37_publish'); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), original, 'publish.txt', 'text/plain', ); await openResource(page, resourceId); // Отмена подтверждения не публикует. await startPublish(page); await page.locator(PUBLISH_CANCEL).click(); await expect(page.locator(PUBLISH_CONFIRM)).toHaveCount(0); await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, undefined, [404], ); // Loading-состояние самого действия видно до ответа сервера (реальный запрос // задерживается network barrier и затем уходит на сервер без подмены ответа). let releasePublish; const publishReleased = new Promise((resolve) => { releasePublish = resolve; }); await page.route('**/resources/*/publish', async (route) => { if (route.request().method() === 'POST') { await publishReleased; } await route.continue(); }); await publishThroughUi(page); await expect(page.locator(PUBLISH_STATUS), 'the pending publication state must be visible').toHaveText( PUBLISH_LABEL, ); releasePublish(); // Барьер до unroute: обработчик сети завершается на реальном ответе, а не гонкой с // удалением route-обработчика. await expect(page.locator(PUBLISHED), 'the publication must complete').toBeVisible(); await page.unroute('**/resources/*/publish'); // Точная immutable Published Version: version/MIME/size/sensitivity/digest. await expect(page.locator(PUBLISHED), 'the exact Published Version must be shown').toBeVisible(); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISHED_MIME)).toHaveText('text/plain'); await expect(page.locator(PUBLISHED_SIZE)).toHaveText(String(original.length)); await expect(page.locator(PUBLISHED_SENSITIVITY)).toHaveText('internal'); await expect(page.locator(PUBLISHED_DIGEST)).toHaveText(sha256Hex(original)); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); // Реальный серверный snapshot совпадает с показанным (не UI-калькуляция). const version = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, ); expect(version.version).toBe(1); expect(version.size_bytes).toBe(original.length); expect(version.mime_type).toBe('text/plain'); expect(version.sensitivity).toBe('internal'); expect(version.digest).toBe(sha256Hex(original)); // Draft edit: экран различает новый Draft и прежнюю Published Version. const edited = Buffer.from('story37 publish body\nedited v2\n', 'utf8'); await page.locator(EDIT_DESCRIPTION).fill('edited draft description'); await page.locator(EDIT_CONTENT).fill(edited.toString('utf8')); await page.locator(EDIT_SUBMIT).click(); await expect(page.locator(EDIT_STATUS)).toHaveText(/saved|сохран/i); await expect(page.locator(META_SIZE), 'the Draft region must show the new Draft size').toHaveText( String(edited.length), ); await expect(page.locator(META_DESCRIPTION)).toHaveText('edited draft description'); await expect(page.locator(PUBLISHED_VERSION), 'the published snapshot must stay at version 1').toHaveText('1'); await expect(page.locator(PUBLISHED_SIZE), 'published size must not alias the mutable Draft').toHaveText( String(original.length), ); await expect(page.locator(PUBLISHED_DIGEST)).toHaveText(sha256Hex(original)); // Published bytes не изменились физически. const publishedDownload = await readResourceVersionDownload(page, workspace.id, resourceId, 1); expect(publishedDownload.status).toBe(200); expect(publishedDownload.bodyBase64).toBe(original.toString('base64')); // Точная Published Version остаётся различимой и после reload экрана. await page.reload(); await expect(page.locator(META_SIZE)).toHaveText(String(edited.length)); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISHED_SIZE)).toHaveText(String(original.length)); await expect(page.locator(PUBLISHED_DIGEST)).toHaveText(sha256Hex(original)); }); test('story37_at05_published_snapshot_is_shown_from_server_state', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const bytes = Buffer.from('story37 published state body\n', 'utf8'); const name = uniqueName('story37_published_state'); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), bytes, 'published-state.txt', 'text/plain', ); const published = await publishThroughApi(page, workspace.id, resourceId); expect(published.published_version.version).toBe(1); await openResource(page, resourceId); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); await expect(page.locator(PUBLISHED), 'a published Resource must show its exact version').toBeVisible(); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISHED_MIME)).toHaveText('text/plain'); await expect(page.locator(PUBLISHED_SIZE)).toHaveText(String(bytes.length)); await expect(page.locator(PUBLISHED_SENSITIVITY)).toHaveText('internal'); await expect(page.locator(PUBLISHED_DIGEST)).toHaveText(sha256Hex(bytes)); // Reload не теряет exact Published Version и не показывает latest-alias. await page.reload(); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISHED_DIGEST)).toHaveText(sha256Hex(bytes)); }); test('story37_at05_stale_publish_is_visible_and_recovers_after_reload', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const name = uniqueName('story37_stale'); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), Buffer.from('first body\n', 'utf8'), 'stale.txt', 'text/plain', ); await openResource(page, resourceId); // Внешняя правка после загрузки экрана: страница держит устаревший precondition. const currentCard = await readCard(page, workspace.id, resourceId); const newer = Buffer.from('newer body from another tab\n', 'utf8'); const updated = await updateResourceDraft( page, workspace.id, resourceId, { description: 'story37 stale fixture', mime_type: 'text/plain', sensitivity: 'internal', expected_updated_at: currentCard.resource.updated_at, }, newer, 'stale.txt', 'text/plain', ); expect(updated.status, `the external Draft edit must succeed: ${updated.text}`).toBe(200); await publishThroughUi(page); await expect(page.locator(STALE), 'a stale precondition must be a visible state').toBeVisible(); await expect(page.locator(STALE)).toHaveText(STALE_MESSAGE); await expect(page.locator(PUBLISHED)).toHaveCount(0); await expect(page.locator(RELOAD), 'the stale state must offer reload').toBeVisible(); // Отказ не создал publication. await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, undefined, [404], ); // Reload подхватывает актуальную карточку (новый Draft v2) и позволяет опубликовать её. await page.locator(RELOAD).click(); await expect(page.locator(STALE)).toHaveCount(0); await expect(page.locator(META_SIZE)).toHaveText(String(newer.length)); await expect(page.locator(PREVIEW_TEXT)).toHaveText(newer.toString('utf8')); await publishThroughUi(page); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('2'); await expect(page.locator(PUBLISHED_SIZE)).toHaveText(String(newer.length)); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); }); test('story37_at05_publication_refusal_is_a_safe_visible_error', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const name = uniqueName('story37_secret'); // Синтетическая канарейка raw credential: публикация обязана отказать (AC02 intake), // а экран — показать безопасную ошибку без публикации. const secret = 'password = story37-synthetic-canary-7f3a9c\n'; const resourceId = await seedDraft( page, workspace.id, textMetadata(name), Buffer.from(secret, 'utf8'), 'secret.txt', 'text/plain', ); await openResource(page, resourceId); await publishThroughUi(page); await expect(page.locator(PUBLISH_STATUS)).not.toHaveText(''); await expect(page.locator(PUBLISH_STATUS)).toHaveText(/secret|credential|publication|публикац|секрет/i); await expect(page.locator(PUBLISHED)).toHaveCount(0); await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS); const card = await readCard(page, workspace.id, resourceId); expect(card.resource.status, 'a refused publication must keep the Draft').toBe('draft'); await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, undefined, [404], ); }); test('story37_at05_bind_exact_published_version_to_an_agent', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const agentDisplay = uniqueName('Story37 Bind Agent'); const agent = await createAgent(page, workspace.id, { slug: uniqueName('story37_bind_agent'), display_name: agentDisplay, description: 'Agent for Story 3.7 exact Resource binding.', instructions: {}, tool_selection_policy: {}, }); const bytes = Buffer.from('story37 bind body\n', 'utf8'); const name = uniqueName('story37_bind'); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), bytes, 'bind.txt', 'text/plain', ); await publishThroughApi(page, workspace.id, resourceId); await openResource(page, resourceId); // Привязка exact Published Version к Agent через существующий API. await expect(page.locator(BIND_FORM), 'the screen must offer a Resource binding form').toBeVisible(); await expect(page.locator(BIND_VERSION), 'the binding targets the exact published version').toHaveText('1'); await page.locator(BIND_AGENT).selectOption({ label: agentDisplay }); await page.locator(BIND_SUBMIT).click(); await expect(page.locator(BIND_STATUS)).toHaveText(BIND_LABEL); // Барьер завершения: серверное состояние проверяется только после реального успеха. await expect(page.locator(BIND_STATUS)).toHaveText( localized('The binding was saved.', 'Привязка сохранена.'), ); const agentSummary = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}`, ); const agentVersion = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}/versions/${agentSummary.current_draft_version}`, ); expect(agentVersion.resource_bindings).toEqual([ { resource_id: resourceId, resource_version: 1 }, ]); }); test('story37_at05_archive_requires_confirmation_and_keeps_published_history', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const bytes = Buffer.from('story37 archive body\n', 'utf8'); const name = uniqueName('story37_archive'); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), bytes, 'archive.txt', 'text/plain', ); await publishThroughApi(page, workspace.id, resourceId); await openResource(page, resourceId); // Снимок опубликованной версии до архива — независимый oracle для инвариантности. const beforeArchive = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, ); const beforeContent = await readResourceVersionDownload(page, workspace.id, resourceId, 1); expect(beforeContent.status).toBe(200); // Архив требует подтверждения: отмена не меняет lifecycle. await expect(page.locator(ARCHIVE), 'the screen must offer the archive action').toBeVisible(); await page.locator(ARCHIVE).click(); await expect(page.locator(ARCHIVE_CONFIRM)).toBeVisible(); await expect(page.locator(ARCHIVE_CONFIRM)).toHaveText(CONFIRM_LABEL); await page.locator(ARCHIVE_CANCEL).click(); await expect(page.locator(ARCHIVE_CONFIRM)).toHaveCount(0); const stillPublished = await readCard(page, workspace.id, resourceId); expect(stillPublished.resource.status).toBe('published'); await page.locator(ARCHIVE).click(); await page.locator(ARCHIVE_CONFIRM_ACCEPT).click(); await expect(page.locator(ARCHIVE_STATUS)).toHaveText(ARCHIVE_LABEL); await expect(page.locator(STATUS)).toHaveText(/archived|архив/i); const archived = await readCard(page, workspace.id, resourceId); expect(archived.resource.status, 'the archive action must persist the archived lifecycle').toBe( 'archived', ); // Archived Resource не теряет immutable историю: metadata и bytes точной версии те же. const afterArchive = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, ); expect(afterArchive).toEqual(beforeArchive); const afterContent = await readResourceVersionDownload(page, workspace.id, resourceId, 1); expect(afterContent.status).toBe(200); expect(afterContent.bodyBase64).toBe(beforeContent.bodyBase64); expect(afterContent.bodyBase64).toBe(bytes.toString('base64')); // Archived lifecycle не предлагает повторную публикацию/архив/привязку и правку. await expect(page.locator(PUBLISH)).toBeDisabled(); await expect(page.locator(ARCHIVE)).toBeDisabled(); await expect(page.locator(BIND_SUBMIT)).toBeDisabled(); await expect(page.locator(EDIT_SUBMIT)).toBeDisabled(); }); test('story37_at06_stale_agent_revision_blocks_binding_without_touching_publication', async ({ page, }) => { await login(page); const workspace = await getCurrentWorkspace(page); const agentDisplay = uniqueName('Story37 Stale Agent'); const agent = await createAgent(page, workspace.id, { slug: uniqueName('story37_stale_agent'), display_name: agentDisplay, description: 'Agent for Story 3.7 stale revision regression.', instructions: {}, tool_selection_policy: {}, }); const bytes = Buffer.from('story37 stale agent body\n', 'utf8'); const name = uniqueName('story37_stale_agent_res'); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), bytes, 'stale-agent.txt', 'text/plain', ); await publishThroughApi(page, workspace.id, resourceId); await openResource(page, resourceId); // Экран открывает форму привязки и фиксирует состояние Agent (If-Match). await expect(page.locator(BIND_FORM)).toBeVisible(); await page.locator(BIND_AGENT).selectOption({ label: agentDisplay }); // Детерминированно дожидаемся, что форма загрузила именно текущий draft Agent: // иначе параллельная правка могла бы попасть между load и submit, и stale-guard // проверялся бы не на зафиксированном снимке. const agentBefore = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}`, ); await expect(page.locator(BIND_AGENT_VERSION)).toHaveText( String(agentBefore.current_draft_version), ); // Параллельный администратор меняет Agent: состояние выбранной формы становится stale. const bumped = await page.evaluate( async ({ workspaceId, agentId }) => { const base = `/api/admin/workspaces/${workspaceId}/agents/${agentId}`; const current = await fetch(base, { credentials: 'same-origin' }); const etag = current.headers.get('etag'); const body = await current.json(); let csrfToken = window.CrankAuth && window.CrankAuth.getCsrfToken(); if (!csrfToken && window.CrankApi && window.CrankApi.refreshSessionCsrf) { const csrf = await window.CrankApi.refreshSessionCsrf(); csrfToken = csrf && csrf.csrf_token; } const response = await fetch(`${base}/bindings`, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', ...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}), ...(etag ? { 'If-Match': etag } : {}), }, body: JSON.stringify({ bindings: [], tool_selection_policy: body.tool_selection_policy || {}, }), }); const text = await response.text(); return { status: response.status, text: text.slice(0, 400) }; }, { workspaceId: workspace.id, agentId: agent.agent_id }, ); expect(bumped.status, `the concurrent Agent save must succeed: ${bumped.text}`).toBe(200); const publishedBefore = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, ); const contentBefore = await readResourceVersionDownload(page, workspace.id, resourceId, 1); await page.locator(BIND_SUBMIT).click(); await expect( page.locator(BIND_STALE), 'a stale Agent revision must be a visible state, not a silent success', ).toBeVisible(); await expect(page.locator(BIND_STALE)).toHaveText(/stale|revision|изменил|устар/i); // Отказ не изменил ни published snapshot, ни Agent bindings. const agentSummary = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}`, ); const agentVersion = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}/versions/${agentSummary.current_draft_version}`, ); expect(agentVersion.resource_bindings).toEqual([]); const publishedAfter = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/resources/${resourceId}/versions/1`, ); expect(publishedAfter).toEqual(publishedBefore); const contentAfter = await readResourceVersionDownload(page, workspace.id, resourceId, 1); expect(contentAfter.bodyBase64).toBe(contentBefore.bodyBase64); }); test('story37_at05_binding_preserves_existing_agent_bindings_and_policy', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); // Непустое существующее состояние Agent: опубликованный Operation binding, // нестандартная tool policy и точный Resource binding другой версии. const operationName = uniqueName('story37_preserve_op'); const operation = await page.evaluate( async ({ workspaceId, operationName: name }) => { const schema = (field, description) => ({ type: 'object', description, required: true, nullable: false, fields: { [field]: { type: 'string', description: `${field} value used by the Story 3.7 binding fixture`, required: true, nullable: false, }, }, }); const payload = { name, display_name: 'Story 3.7 preserved binding Operation', category: 'quality', protocol: 'rest', security_level: 'standard', target: { kind: 'rest', base_url: 'https://httpbin.org', method: 'GET', path_template: '/anything', static_headers: {}, }, input_schema: schema('input', 'Binding fixture input contract'), output_schema: schema('output', 'Binding fixture output contract'), input_mapping: { rules: [{ source: '$.mcp.input', target: '$.request.query.input', required: true }], }, output_mapping: { rules: [{ source: '$.response.body.output', target: '$.output.output', required: true }], }, execution_config: { timeout_ms: 1000, headers: {} }, tool_description: { title: 'Story 3.7 preserved binding Operation', description: 'Fixture Operation bound to an Agent before the UI Resource binding.', tags: ['quality'], examples: [], }, wizard_state: null, }; const created = await window.CrankApi.createOperation(workspaceId, payload); await window.CrankApi.getOperation(workspaceId, created.operation_id); await window.CrankApi.publishOperation(workspaceId, created.operation_id, 1); return { operation_id: created.operation_id, tool_name: payload.name, tool_title: payload.display_name, }; }, { workspaceId: workspace.id, operationName }, ); const agentDisplay = uniqueName('Story37 Preserve Agent'); const agent = await createAgent(page, workspace.id, { slug: uniqueName('story37_preserve_agent'), display_name: agentDisplay, description: 'Agent for Story 3.7 preserved bindings.', instructions: {}, tool_selection_policy: { mode: 'search', groups: [], search: { max_results: 7 } }, }); const oldBytes = Buffer.from('story37 preserved binding body\n', 'utf8'); const oldId = await seedDraft( page, workspace.id, textMetadata(uniqueName('story37_preserve_old')), oldBytes, 'preserve-old.txt', 'text/plain', ); await publishThroughApi(page, workspace.id, oldId); const saved = await page.evaluate( async ({ workspaceId, agentId, payload }) => { await window.CrankApi.getAgent(workspaceId, agentId); return window.CrankApi.saveAgentBindings(workspaceId, agentId, payload); }, { workspaceId: workspace.id, agentId: agent.agent_id, payload: { bindings: [ { operation_id: operation.operation_id, operation_version: 1, tool_name: operation.tool_name, tool_title: operation.tool_title, tool_description_override: null, enabled: true, }, ], tool_selection_policy: { mode: 'search', groups: [], search: { max_results: 7 } }, resource_bindings: [{ resource_id: oldId, resource_version: 1 }], }, }, ); expect(saved.bindings.length, 'the Operation binding fixture must be saved').toBe(1); expect(saved.resource_bindings).toEqual([{ resource_id: oldId, resource_version: 1 }]); const seededVersion = saved.version; const newId = await seedDraft( page, workspace.id, textMetadata(uniqueName('story37_preserve_new')), Buffer.from('story37 new exact binding body\n', 'utf8'), 'preserve-new.txt', 'text/plain', ); await publishThroughApi(page, workspace.id, newId); await openResource(page, newId); await expect(page.locator(BIND_FORM)).toBeVisible(); await expect(page.locator(BIND_VERSION)).toHaveText('1'); await page.locator(BIND_AGENT).selectOption({ label: agentDisplay }); await expect(page.locator(BIND_AGENT_VERSION)).toHaveText(String(seededVersion)); await page.locator(BIND_SUBMIT).click(); await expect(page.locator(BIND_STATUS)).toHaveText(BIND_LABEL); await expect(page.locator(BIND_STATUS)).toHaveText( localized('The binding was saved.', 'Привязка сохранена.'), ); const summary = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}`, ); const version = await browserJson( page, 'GET', `/api/admin/workspaces/${workspace.id}/agents/${agent.agent_id}/versions/${summary.current_draft_version}`, ); expect(version.bindings.length, 'the existing Operation binding must be preserved').toBe(1); expect(version.bindings[0].operation_id).toBe(operation.operation_id); expect(version.bindings[0].enabled).toBe(true); expect(version.snapshot.tool_selection_policy.mode, 'the tool policy must be preserved').toBe( 'search', ); expect(version.snapshot.tool_selection_policy.search.max_results).toBe(7); expect(version.resource_bindings, 'existing and new exact bindings must both remain').toEqual([ { resource_id: oldId, resource_version: 1 }, { resource_id: newId, resource_version: 1 }, ]); }); test('story37_at05_delayed_resource_response_does_not_replace_the_selected_resource', async ({ page, }) => { await login(page); const workspace = await getCurrentWorkspace(page); async function seedText(label, text) { const name = uniqueName(label); const resourceId = await seedDraft( page, workspace.id, textMetadata(name), Buffer.from(text, 'utf8'), `${label}.txt`, 'text/plain', ); return { resourceId, name, text }; } const first = await seedText('story37_delayed_a', 'first selection A body\n'); const delayed = await seedText('story37_delayed_b', 'delayed response B body\n'); const current = await seedText('story37_delayed_c', 'current selection C body\n'); await openResource(page, first.resourceId); await expect(page.locator(PREVIEW_TEXT)).toHaveText(first.text); // Network barrier только задерживает реальный ответ GET карточки B; ответ не подменяется. let releaseDelayed; const delayedReleased = new Promise((resolve) => { releaseDelayed = resolve; }); const delayedCard = `**/api/admin/workspaces/${workspace.id}/resources/${delayed.resourceId}`; await page.route(delayedCard, async (route) => { if (route.request().method() === 'GET') { await delayedReleased; } await route.continue(); }); const lateResponse = page.waitForResponse( (response) => response.request().method() === 'GET' && response.url().endsWith(`/resources/${delayed.resourceId}`), ); await page .locator(`[data-testid="resource-list-item"][data-resource-id="${delayed.resourceId}"]`) .click(); await page .locator(`[data-testid="resource-list-item"][data-resource-id="${current.resourceId}"]`) .click(); await expect(page.locator(META_NAME)).toHaveText(current.name); await expect(page.locator(PREVIEW_TEXT)).toHaveText(current.text); releaseDelayed(); await lateResponse; await page.unroute(delayedCard); // Даём позднему ответу B примениться/отброситься до финальных проверок. await page.waitForTimeout(300); await expect(page.locator(META_NAME), 'a delayed response must not replace the selection').toHaveText( current.name, ); await expect(page.locator(PREVIEW_TEXT)).toHaveText(current.text); await expect(page.locator(META_SIZE)).toHaveText(String(Buffer.byteLength(current.text, 'utf8'))); await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS); }); for (const locale of ['ru', 'en']) { // Точные ожидания выбранной локали (не общий RU|EN regex): тест обязан доказать, // что экран действительно переведён, а не просто содержит одну из двух строк. const exact = locale === 'ru' ? { draft: 'Черновик', publish: 'Опубликовать', findingsEmpty: 'Нарушений не найдено.', published: 'Опубликован', archive: 'В архив', bind: 'Привязать точную версию', confirm: 'Подтвердить публикацию?', accept: 'Подтвердить', cancel: 'Отмена', pending: 'Публикуем…', done: 'Ресурс опубликован.', stale: 'Ресурс изменился после загрузки. Обновите данные и повторите.', reload: 'Обновить', secret: 'Публикация отклонена: содержимое содержит секретные данные или ссылку в обход доступа.', } : { draft: 'Draft', publish: 'Publish', findingsEmpty: 'No findings.', published: 'Published', archive: 'Archive', bind: 'Bind exact version', confirm: 'Confirm publication?', accept: 'Confirm', cancel: 'Cancel', pending: 'Publishing…', done: 'The Resource was published.', stale: 'The Resource changed since it was loaded. Reload and try again.', reload: 'Reload', secret: 'Publication refused: the content contains secret material or an access-bypassing reference.', }; test(`story37_at05_lifecycle_actions_are_localized_in_${locale}`, async ({ page }) => { await login(page); await page.evaluate((language) => localStorage.setItem('crank_lang', language), locale); const workspace = await getCurrentWorkspace(page); const draftId = await seedDraft( page, workspace.id, textMetadata(uniqueName(`story37_${locale}_draft`)), Buffer.from('localized draft body\n', 'utf8'), 'localized-draft.txt', 'text/plain', ); const publishedId = await seedDraft( page, workspace.id, textMetadata(uniqueName(`story37_${locale}_published`)), Buffer.from('localized published body\n', 'utf8'), 'localized-published.txt', 'text/plain', ); await publishThroughApi(page, workspace.id, publishedId); // Draft-состояние: action, статус и findings локализованы, без сырых i18n-ключей. await openResource(page, draftId); await expect(page.locator(STATUS)).toHaveText(exact.draft); await expect(page.locator(PUBLISH)).toHaveText(exact.publish); await expect(page.locator(PUBLISH)).not.toHaveText(/^resources\./); await expect(page.locator(FINDINGS_EMPTY)).toHaveText(exact.findingsEmpty); // Published-состояние: точная версия, archive/bind локализованы. await openResource(page, publishedId); await expect(page.locator(STATUS)).toHaveText(exact.published); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(ARCHIVE)).toHaveText(exact.archive); await expect(page.locator(BIND_FORM)).toBeVisible(); await expect(page.locator(BIND_SUBMIT)).toHaveText(exact.bind); // D5: pending/confirmation/done — точные тексты выбранной локали. await openResource(page, draftId); let releaseLocalePublish; const localePublishReleased = new Promise((resolve) => { releaseLocalePublish = resolve; }); await page.route('**/resources/*/publish', async (route) => { if (route.request().method() === 'POST') { await localePublishReleased; } await route.continue(); }); await page.locator(PUBLISH).click(); await expect(page.locator(`${PUBLISH_CONFIRM} [data-confirm-text]`)).toHaveText(exact.confirm); await expect(page.locator(PUBLISH_CONFIRM_ACCEPT)).toHaveText(exact.accept); await expect(page.locator(PUBLISH_CANCEL)).toHaveText(exact.cancel); await page.locator(PUBLISH_CONFIRM_ACCEPT).click(); await expect(page.locator(PUBLISH_STATUS)).toHaveText(exact.pending); releaseLocalePublish(); await expect(page.locator(PUBLISH_STATUS)).toHaveText(exact.done); await expect(page.locator(STATUS)).toHaveText(exact.published); await page.unroute('**/resources/*/publish'); // D5: stale precondition — точное сообщение и точная надпись reload. const currentCard = await readCard(page, workspace.id, draftId); const newerBytes = Buffer.from('localized stale body\n', 'utf8'); const external = await updateResourceDraft( page, workspace.id, draftId, { description: 'localized stale draft', mime_type: 'text/plain', sensitivity: 'internal', expected_updated_at: currentCard.resource.updated_at, }, newerBytes, 'localized-stale.txt', 'text/plain', ); expect(external.status, `the external edit must succeed: ${external.text}`).toBe(200); await publishThroughUi(page); await expect(page.locator(`${STALE} [data-stale-text]`)).toHaveText(exact.stale); await expect(page.locator(RELOAD)).toHaveText(exact.reload); // D2/D5: отказ публикации — точное сообщение выбранной локали. const secretId = await seedDraft( page, workspace.id, textMetadata(uniqueName(`story37_${locale}_secret`)), Buffer.from('password = story37-localized-canary-42\n', 'utf8'), 'localized-secret.txt', 'text/plain', ); await openResource(page, secretId); await publishThroughUi(page); await expect(page.locator(PUBLISH_STATUS)).toHaveText(exact.secret); }); } // --------------------------------------------------------------------------- // D1 (TL review R1): смена выбора не наследует lifecycle/CAS/версию прежнего Resource // --------------------------------------------------------------------------- test('story37_at05_selection_change_invalidates_previous_lifecycle_and_cas', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const publishedBytes = Buffer.from('story37 previous published body\n', 'utf8'); const publishedId = await seedDraft( page, ws, textMetadata(uniqueName('story37_prev_published')), publishedBytes, 'prev-published.txt', 'text/plain', ); await publishThroughApi(page, ws, publishedId); const draftB = { id: await seedDraft( page, ws, textMetadata(uniqueName('story37_next_draft_b')), Buffer.from('story37 next draft B body\n', 'utf8'), 'next-b.txt', 'text/plain', ), name: '', text: 'story37 next draft B body\n', }; draftB.name = (await readCard(page, ws, draftB.id)).resource.name; const draftC = { id: await seedDraft( page, ws, textMetadata(uniqueName('story37_next_draft_c')), Buffer.from('story37 next draft C body\n', 'utf8'), 'next-c.txt', 'text/plain', ), name: '', text: 'story37 next draft C body\n', }; draftC.name = (await readCard(page, ws, draftC.id)).resource.name; // Выбор опубликованного A: экран владеет его lifecycle, CAS и точной версией. await openResource(page, publishedId); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(BIND_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISH)).toBeEnabled(); await expect(page.locator(ARCHIVE)).toBeEnabled(); // Пока новый Resource не загружен, действия недоступны и версия A не показывается. let releaseDraft; const draftReleased = new Promise((resolve) => { releaseDraft = resolve; }); const draftCard = `**/api/admin/workspaces/${ws}/resources/${draftB.id}`; await page.route(draftCard, async (route) => { if (route.request().method() === 'GET') { await draftReleased; } await route.continue(); }); const lateDraft = page.waitForResponse( (response) => response.request().method() === 'GET' && response.url().endsWith(`/resources/${draftB.id}`), ); await page.locator(`[data-testid="resource-list-item"][data-resource-id="${draftB.id}"]`).click(); await expect(page.locator(PUBLISHED)).toHaveCount(0); await expect(page.locator(PUBLISHED_VERSION)).toHaveCount(0); await expect(page.locator(BIND_VERSION)).toHaveText(''); await expect(page.locator(BIND_FORM)).toBeHidden(); await expect(page.locator(PUBLISH)).toBeDisabled(); await expect(page.locator(ARCHIVE)).toBeDisabled(); await expect(page.locator(STATUS)).toHaveText(''); releaseDraft(); await lateDraft; await page.unroute(draftCard); // Загруженный Draft B владеет собственным (пустым) публикационным состоянием. await expect(page.locator(META_NAME)).toHaveText(draftB.name); await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS); await expect(page.locator(PUBLISHED)).toHaveCount(0); await expect(page.locator(BIND_FORM)).toBeHidden(); await expect(page.locator(BIND_VERSION)).toHaveText(''); await expect(page.locator(PUBLISH)).toBeEnabled(); // Отказ загрузки нового Resource оставляет экран без действий прежнего выбора. const mutations = []; page.on('request', (request) => { const method = request.method(); if ( ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && (/\/resources\/[^/]+\/(publish|archive)$/.test(request.url()) || /\/agents\/[^/]+\/bindings$/.test(request.url())) ) { mutations.push(`${method} ${request.url()}`); } }); const failingCard = `**/api/admin/workspaces/${ws}/resources/${draftC.id}`; await page.route(failingCard, (route) => route.request().method() === 'GET' ? route.abort('failed') : route.continue(), ); await page.locator(`[data-testid="resource-list-item"][data-resource-id="${draftC.id}"]`).click(); await expect(page.locator('#resources-status')).toHaveText( localized('The Resource could not be loaded.', 'Не удалось загрузить ресурс.'), ); await expect(page.locator(PUBLISH)).toBeDisabled(); await expect(page.locator(ARCHIVE)).toBeDisabled(); await expect(page.locator(PUBLISHED)).toHaveCount(0); await expect(page.locator(BIND_VERSION)).toHaveText(''); expect(mutations, 'a failed selection must not send any mutation').toEqual([]); await page.unroute(failingCard); // Повторный выбор C загружает его и публикует с его собственным CAS. await page.locator(`[data-testid="resource-list-item"][data-resource-id="${draftC.id}"]`).click(); await expect(page.locator(META_NAME)).toHaveText(draftC.name); await publishThroughUi(page); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); // Ни одна мутация не ушла к A/B, и A сохранил собственную опубликованную версию. expect(mutations.length).toBe(1); expect(mutations[0]).toContain(`/resources/${draftC.id}/publish`); await browserJson(page, 'GET', `/api/admin/workspaces/${ws}/resources/${publishedId}/versions/1`); const cardA = await readCard(page, ws, publishedId); expect(cardA.resource.status).toBe('published'); expect(cardA.resource.latest_published_version).toBe(1); const cardB = await readCard(page, ws, draftB.id); expect(cardB.resource.status).toBe('draft'); }); // D1: поздний preview-ответ прежнего поколения не откатывает принятую публикацию. test('story37_at05_delayed_preview_does_not_rollback_accepted_publication', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const bytes = Buffer.from('story37 delayed preview body\n', 'utf8'); const resourceId = await seedDraft( page, ws, textMetadata(uniqueName('story37_delayed_preview')), bytes, 'delayed-preview.txt', 'text/plain', ); let releasePreview; const previewReleased = new Promise((resolve) => { releasePreview = resolve; }); let previewRequests = 0; const previewUrl = `**/api/admin/workspaces/${ws}/resources/${resourceId}/preview`; await page.route(previewUrl, async (route) => { previewRequests += 1; if (previewRequests === 1) { await previewReleased; } await route.continue(); }); await openResource(page, resourceId); // Карточка уже загружена, а preview ещё в полёте. await expect(page.locator(PUBLISH)).toBeEnabled(); await publishThroughUi(page); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); // E1 (TL review R2): принятая публикация не открывает редактор до прихода preview. // Иначе metadata-only правка отправила бы пустой content и получила 422. await expect( page.locator(EDIT_SUBMIT), 'publish must not enable the editor while the initial preview is still pending (E1)', ).toBeDisabled(); await expect(page.locator(EDIT_CONTENT)).toBeDisabled(); await expect(page.locator(EDIT_CONTENT)).toHaveValue(''); // Поздний preview приходит после принятой мутации: экран остаётся на новом снимке. releasePreview(); await page.waitForTimeout(500); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); await expect(page.locator(PUBLISHED_SIZE)).toHaveText(String(bytes.length)); await expect(page.locator(PUBLISHED_DIGEST)).toHaveText(sha256Hex(bytes)); await expect(page.locator(META_SIZE)).toHaveText(String(bytes.length)); // E1: только coherent снимок текущего выбора открывает редактор с исходными bytes. await expect(page.locator(EDIT_CONTENT)).toBeEnabled(); await expect( page.locator(EDIT_CONTENT), 'the editor must show the exact bytes of the current snapshot', ).toHaveValue(bytes.toString('utf8')); await page.locator(EDIT_DESCRIPTION).fill('story37 delayed preview metadata-only edit'); const [editResponse] = await Promise.all([ page.waitForResponse( (response) => response.request().method() === 'PUT' && response.url().endsWith(`/resources/${resourceId}`), ), page.locator(EDIT_SUBMIT).click(), ]); expect(editResponse.status(), 'a metadata-only edit must be accepted').toBe(200); await expect(page.locator(EDIT_STATUS)).toHaveText(/saved|сохран/i); await expect(page.locator(META_DESCRIPTION)).toHaveText('story37 delayed preview metadata-only edit'); const preserved = await readResourceDownload(page, ws, resourceId); expect(preserved.status).toBe(200); expect(preserved.bodyBase64, 'the original bytes must be preserved').toBe(bytes.toString('base64')); // Coherent CAS: archive проходит только если precondition не откатился preview-ответом. await page.locator(ARCHIVE).click(); await page.locator(ARCHIVE_CONFIRM_ACCEPT).click(); await expect(page.locator(STATUS)).toHaveText(/archived|архив/i); await expect(page.locator(STALE)).toHaveCount(0); const archived = await readCard(page, ws, resourceId); expect(archived.resource.status).toBe('archived'); }); // D1: явная безопасная ошибка точного Published GET и отказ от binding по непрочитанному указателю. test('story37_at05_published_snapshot_error_is_visible_and_blocks_binding', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const agentDisplay = uniqueName('Story37 Published Error Agent'); await createAgent(page, ws, { slug: uniqueName('story37_published_error_agent'), display_name: agentDisplay, description: 'Agent fixture for the published snapshot error state.', instructions: {}, tool_selection_policy: {}, }); const resourceId = await seedDraft( page, ws, textMetadata(uniqueName('story37_published_error')), Buffer.from('story37 published error body\n', 'utf8'), 'published-error.txt', 'text/plain', ); await publishThroughApi(page, ws, resourceId); const versionUrl = `**/api/admin/workspaces/${ws}/resources/${resourceId}/versions/1`; await page.route(versionUrl, (route) => route.request().method() === 'GET' ? route.abort('failed') : route.continue(), ); await openResource(page, resourceId); await expect(page.locator(PUBLISHED_ERROR), 'a failed exact read must be visible').toBeVisible(); await expect(page.locator(PUBLISHED_ERROR)).toHaveText( localized( 'The exact Published Version could not be loaded. Reload and try again.', 'Не удалось загрузить точную опубликованную версию. Обновите страницу и повторите.', ), ); await expect(page.locator(PUBLISHED)).toHaveCount(0); // Указатель версии есть, но непрочитанный snapshot не открывает binding. await expect(page.locator(BIND_FORM)).toBeVisible(); await page.locator(BIND_AGENT).selectOption({ label: agentDisplay }); await expect(page.locator(BIND_SUBMIT)).toBeDisabled(); await page.unroute(versionUrl); }); // --------------------------------------------------------------------------- // D4 (TL review R1): поздние ответы Agent не перекрашивают форму другого выбора // --------------------------------------------------------------------------- async function latestAgentVersion(page, workspaceId, agentId) { const summary = await browserJson(page, 'GET', `/api/admin/workspaces/${workspaceId}/agents/${agentId}`); return browserJson( page, 'GET', `/api/admin/workspaces/${workspaceId}/agents/${agentId}/versions/${summary.current_draft_version}`, ); } test('story37_at05_delayed_agent_load_does_not_switch_the_binding_target', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const labelA = uniqueName('Story37 Delay Agent A'); const agentA = await createAgent(page, ws, { slug: uniqueName('story37_delay_agent_a'), display_name: labelA, description: 'Delayed Agent A for the binding target regression.', instructions: {}, tool_selection_policy: {}, }); const labelB = uniqueName('Story37 Delay Agent B'); const agentB = await createAgent(page, ws, { slug: uniqueName('story37_delay_agent_b'), display_name: labelB, description: 'Delayed Agent B for the binding target regression.', instructions: {}, tool_selection_policy: {}, }); const resourceId = await seedDraft( page, ws, textMetadata(uniqueName('story37_delay_agent_res')), Buffer.from('story37 delayed agent body\n', 'utf8'), 'delayed-agent.txt', 'text/plain', ); await publishThroughApi(page, ws, resourceId); await openResource(page, resourceId); await expect(page.locator(BIND_FORM)).toBeVisible(); // Barrier задерживает реальный ответ версии Agent A — ответ не подменяется. let releaseAgent; const agentReleased = new Promise((resolve) => { releaseAgent = resolve; }); const agentVersionUrl = `**/api/admin/workspaces/${ws}/agents/${agentA.agent_id}/versions/*`; await page.route(agentVersionUrl, async (route) => { if (route.request().method() === 'GET') { await agentReleased; } await route.continue(); }); await page.locator(BIND_AGENT).selectOption({ label: labelA }); await page.locator(BIND_AGENT).selectOption({ label: labelB }); await expect(page.locator(BIND_AGENT_VERSION)).toHaveText('1'); await expect(page.locator(BIND_SUBMIT)).toBeEnabled(); releaseAgent(); await page.waitForTimeout(400); await page.unroute(agentVersionUrl); // Поздний ответ A не подменил выбранного B и не показал его версию. await expect(page.locator(BIND_AGENT)).toHaveValue(agentB.agent_id); await expect(page.locator(BIND_AGENT_VERSION)).toHaveText('1'); await expect(page.locator(BIND_STATUS)).toHaveText(''); const bindRequests = []; page.on('request', (request) => { if (request.method() === 'POST' && /\/agents\/[^/]+\/bindings$/.test(request.url())) { bindRequests.push(request.url()); } }); await page.locator(BIND_SUBMIT).click(); await expect(page.locator(BIND_STATUS)).toHaveText( localized('The binding was saved.', 'Привязка сохранена.'), ); expect(bindRequests, 'the binding must go to the selected Agent only').toHaveLength(1); expect(bindRequests[0]).toContain(`/agents/${agentB.agent_id}/bindings`); const versionB = await latestAgentVersion(page, ws, agentB.agent_id); expect(versionB.resource_bindings).toEqual([{ resource_id: resourceId, resource_version: 1 }]); const versionA = await latestAgentVersion(page, ws, agentA.agent_id); expect( versionA.resource_bindings, 'the delayed A snapshot must not be written to the shown selection', ).toEqual([]); }); test('story37_at05_delayed_bind_response_does_not_render_on_another_agent', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const labelA = uniqueName('Story37 Delayed Bind A'); const agentA = await createAgent(page, ws, { slug: uniqueName('story37_delay_bind_a'), display_name: labelA, description: 'Agent A for the delayed bind response regression.', instructions: {}, tool_selection_policy: {}, }); const labelB = uniqueName('Story37 Delayed Bind B'); const agentB = await createAgent(page, ws, { slug: uniqueName('story37_delay_bind_b'), display_name: labelB, description: 'Agent B for the delayed bind response regression.', instructions: {}, tool_selection_policy: {}, }); const resourceId = await seedDraft( page, ws, textMetadata(uniqueName('story37_delay_bind_res')), Buffer.from('story37 delayed bind body\n', 'utf8'), 'delayed-bind.txt', 'text/plain', ); await publishThroughApi(page, ws, resourceId); await openResource(page, resourceId); await expect(page.locator(BIND_FORM)).toBeVisible(); await page.locator(BIND_AGENT).selectOption({ label: labelA }); await expect(page.locator(BIND_AGENT_VERSION)).toHaveText('1'); // Barrier задерживает только реальный ответ мутации A. let releaseBind; const bindReleased = new Promise((resolve) => { releaseBind = resolve; }); const bindUrl = `**/api/admin/workspaces/${ws}/agents/${agentA.agent_id}/bindings`; await page.route(bindUrl, async (route) => { if (route.request().method() === 'POST') { await bindReleased; } await route.continue(); }); await page.locator(BIND_SUBMIT).click(); await expect(page.locator(BIND_STATUS)).toHaveText( localized('Binding…', 'Привязываем…'), ); // Пользователь переключился на другого Agent до ответа A. await page.locator(BIND_AGENT).selectOption({ label: labelB }); await expect(page.locator(BIND_AGENT_VERSION)).toHaveText('1'); releaseBind(); await page.waitForTimeout(400); await page.unroute(bindUrl); // Ответ по A не отрисовал success/error в форме B. await expect(page.locator(BIND_AGENT)).toHaveValue(agentB.agent_id); await expect(page.locator(BIND_STATUS)).toHaveText(''); await expect(page.locator(BIND_STALE)).toBeHidden(); await expect(page.locator(BIND_SUBMIT)).toBeEnabled(); const versionB = await latestAgentVersion(page, ws, agentB.agent_id); expect(versionB.resource_bindings, 'the delayed A response must not write to B').toEqual([]); const versionA = await latestAgentVersion(page, ws, agentA.agent_id); expect(versionA.resource_bindings).toEqual([{ resource_id: resourceId, resource_version: 1 }]); }); // D5 (TL review R1): stale archive → видимый reload → успешный archive. test('story37_at06_stale_archive_is_visible_and_recovers_after_reload', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const originalBytes = Buffer.from('story37 archive stale body\n', 'utf8'); const resourceId = await seedDraft( page, ws, textMetadata(uniqueName('story37_archive_stale')), originalBytes, 'archive-stale.txt', 'text/plain', ); await publishThroughApi(page, ws, resourceId); await openResource(page, resourceId); await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS); const beforeVersion = await browserJson( page, 'GET', `/api/admin/workspaces/${ws}/resources/${resourceId}/versions/1`, ); // Внешняя правка после загрузки: экран держит устаревший precondition. const currentCard = await readCard(page, ws, resourceId); const newerBytes = Buffer.from('story37 archive stale body v2\n', 'utf8'); const external = await updateResourceDraft( page, ws, resourceId, { description: 'story37 archive stale draft', mime_type: 'text/plain', sensitivity: 'internal', expected_updated_at: currentCard.resource.updated_at, }, newerBytes, 'archive-stale.txt', 'text/plain', ); expect(external.status, `the external edit must succeed: ${external.text}`).toBe(200); await page.locator(ARCHIVE).click(); await page.locator(ARCHIVE_CONFIRM_ACCEPT).click(); await expect(page.locator(STALE), 'a stale archive must be a visible state').toBeVisible(); await expect(page.locator(STALE)).toHaveText(STALE_MESSAGE); await expect(page.locator(RELOAD)).toBeVisible(); // Отказ не архивировал Resource: внешняя правка сделала его Draft'ом, но точная // Published Version 1 остаётся discoverable и неизменной. const stillPublished = await readCard(page, ws, resourceId); expect(stillPublished.resource.status).toBe('draft'); expect(stillPublished.resource.latest_published_version).toBe(1); await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1'); // Reload подхватывает актуальный Draft и позволяет архивировать с его CAS. await page.locator(RELOAD).click(); await expect(page.locator(STALE)).toHaveCount(0); await expect(page.locator(META_SIZE)).toHaveText(String(newerBytes.length)); await page.locator(ARCHIVE).click(); await page.locator(ARCHIVE_CONFIRM_ACCEPT).click(); await expect(page.locator(STATUS)).toHaveText(/archived|архив/i); const archived = await readCard(page, ws, resourceId); expect(archived.resource.status).toBe('archived'); const afterVersion = await browserJson( page, 'GET', `/api/admin/workspaces/${ws}/resources/${resourceId}/versions/1`, ); expect(afterVersion).toEqual(beforeVersion); }); // D2 (TL review R1): findings preview показывает реальные коды без bytes. test('story37_at01_secret_findings_are_visible_in_preview_without_bytes', async ({ page }) => { await login(page); const workspace = await getCurrentWorkspace(page); const ws = workspace.id; const canary = `story37-findings-canary-${Date.now()}`; const secret = `password = ${canary}\n`; const secretId = await seedDraft( page, ws, textMetadata(uniqueName('story37_findings_secret')), Buffer.from(secret, 'utf8'), 'findings-secret.txt', 'text/plain', ); await openResource(page, secretId); await expect(page.locator(FINDINGS_ITEM), 'a refused publication must be visible in preview').toHaveCount(1); await expect(page.locator(FINDINGS_ITEM)).toHaveText(/resource_secret_findings/); await expect(page.locator(FINDINGS_EMPTY)).toHaveText(''); const findingsHtml = await page.locator(FINDINGS).innerHTML(); expect(findingsHtml, 'findings must not embed the matched bytes').not.toContain(canary); // Preview остаётся read-only: публикации нет. await browserJson( page, 'GET', `/api/admin/workspaces/${ws}/resources/${secretId}/versions/1`, undefined, [404], ); const card = await readCard(page, ws, secretId); expect(card.resource.status).toBe('draft'); // Clean control: у обычного содержимого findings пустые. const cleanId = await seedDraft( page, ws, textMetadata(uniqueName('story37_findings_clean')), Buffer.from('ordinary findings-free body\n', 'utf8'), 'findings-clean.txt', 'text/plain', ); await openResource(page, cleanId); await expect(page.locator(FINDINGS_ITEM)).toHaveCount(0); await expect(page.locator(FINDINGS_EMPTY)).toHaveText(NO_FINDINGS); });