Files
crank/apps/ui/tests/e2e/resources.spec.js
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

1606 lines
73 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ATDD для AT-3.6-07, UI-половина Story 3.6 «typed static Resource Drafts».
//
// Источники: SPEC v4 `resource-drafts-story36-spec.md` §2 (AT-3.6-07), D-6 (инертный текст
// через `textContent`, скачивание — только octet-stream attachment), D-5 (text/html и
// image/svg+xml разрешены лишь для kind=binary и никогда не рендерятся как активные),
// D-16 (uri/name/kind неизменяемы, изменяемы description/MIME/sensitivity/content);
// QA test-design run77 (UI-требования); TL review run101:42 (R-B).
//
// Состояние на этой стадии: страница `/resources` существует только как просмотр, формы
// создания/списка/редактирования в ней нет, поэтому первый тест RED на первом отсутствующем
// узле (`[data-testid="resource-create-form"]`). Ожидаемые формы здесь описаны тестом, но
// production-форма на стадии ATDD не пишется.
//
// Требуемый UI-контракт, который обязан доставить BUILD (R-B требует проверять весь
// обещанный сценарий, а не только первый RED):
// * nav `a.nav-link[href="/resources"]` открывает `/resources`;
// * `[data-testid="resource-create-form"]` с полями `resource-form-uri`, `-name`, `-kind`
// (select), `-mime-type`, `-sensitivity` (select), `-description`, `-content` (textarea)
// и submit `-submit`; для kind=binary содержимое загружается реальным файловым полем
// `[data-testid="resource-form-file"]` (произвольные, в том числе не-UTF8, bytes);
// * `[data-testid="resource-list"]` со строками `[data-testid="resource-list-item"]`;
// клик выбирает Draft и отражается в URL (`?resource_id=…`), поэтому reload
// восстанавливает тот же Draft;
// * `[data-testid="resource-edit-form"]` с полями `resource-edit-description`,
// `resource-edit-mime-type`, `resource-edit-sensitivity`, `resource-edit-content`
// (для binary — файловое `resource-edit-file`) и submit `resource-edit-submit`;
// * карточка просмотра показывает наблюдаемые значения: `resource-meta-uri`, `-name`,
// `-kind`, `-mime`, `-size`, `-digest`, `-version`, `-description`, `-sensitivity`
// и (только text/json) инертный `resource-preview-text`;
// * `[data-testid="resource-preview-error"]` — видимый безопасный отказ preview;
// * `[data-testid="resource-download"]` — настоящая ссылка (клик = скачивание).
//
// Запуск на существующем стенде (один default stack, workers=1, retries строго 0):
// npm --prefix apps/ui run e2e -- tests/e2e/resources.spec.js --workers=1 --retries=0
const { test, expect } = require('@playwright/test');
const {
browserJson,
createResourceDraft,
getCurrentWorkspace,
login,
readResourceDownload,
readResourcePreview,
uniqueName,
} = require('./helpers');
const MARKER_PATH = '/story36-marker';
const MARKER_URL = 'http://127.0.0.1:3311/story36-marker.svg';
const PREVIEW = '[data-testid="resources-preview"]';
const PREVIEW_TEXT = '[data-testid="resource-preview-text"]';
const PREVIEW_ERROR = '[data-testid="resource-preview-error"]';
const META_URI = '[data-testid="resource-meta-uri"]';
const META_NAME = '[data-testid="resource-meta-name"]';
const META_KIND = '[data-testid="resource-meta-kind"]';
const META_MIME = '[data-testid="resource-meta-mime"]';
const META_SIZE = '[data-testid="resource-meta-size"]';
const META_DIGEST = '[data-testid="resource-meta-digest"]';
const META_VERSION = '[data-testid="resource-meta-version"]';
const META_DESCRIPTION = '[data-testid="resource-meta-description"]';
const META_SENSITIVITY = '[data-testid="resource-meta-sensitivity"]';
const CREATE_FORM = '[data-testid="resource-create-form"]';
const FORM_URI = '[data-testid="resource-form-uri"]';
const FORM_NAME = '[data-testid="resource-form-name"]';
const FORM_KIND = '[data-testid="resource-form-kind"]';
const FORM_MIME = '[data-testid="resource-form-mime-type"]';
const FORM_SENSITIVITY = '[data-testid="resource-form-sensitivity"]';
const FORM_DESCRIPTION = '[data-testid="resource-form-description"]';
const FORM_CONTENT = '[data-testid="resource-form-content"]';
const FORM_FILE = '[data-testid="resource-form-file"]';
const FORM_SUBMIT = '[data-testid="resource-form-submit"]';
const LIST_ITEM = '[data-testid="resource-list-item"]';
const EDIT_FORM = '[data-testid="resource-edit-form"]';
const EDIT_DESCRIPTION = '[data-testid="resource-edit-description"]';
const EDIT_MIME = '[data-testid="resource-edit-mime-type"]';
const EDIT_SENSITIVITY = '[data-testid="resource-edit-sensitivity"]';
const EDIT_CONTENT = '[data-testid="resource-edit-content"]';
const EDIT_FILE = '[data-testid="resource-edit-file"]';
const EDIT_SUBMIT = '[data-testid="resource-edit-submit"]';
const EDIT_STATUS = '#resource-edit-status';
const DOWNLOAD = '[data-testid="resource-download"]';
/// Произвольные bytes для binary-ветки: PNG-сигнатура + байты, не являющиеся UTF-8.
const BINARY_BYTES = Buffer.from([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff, 0xfe, 0x80, 0x01, 0x7f, 0xc3, 0x28,
]);
/// Те же bytes после первого редактирования: тоже не UTF-8 и другой длины.
const BINARY_BYTES_EDITED = Buffer.concat([BINARY_BYTES, Buffer.from([0xde, 0xad, 0xbe, 0xef])]);
const SCENARIOS = [
{
label: 'text',
kind: 'text',
mime: 'text/plain',
// Владельцем text/* является kind=text, поэтому MIME действительно меняется.
editedMime: 'text/markdown',
description: 'text journey description',
editedDescription: 'text journey description v2',
content: 'journey text body\n',
editedContent: 'journey text body\nedited v2\n',
thirdContent: 'journey text body\nedited v2\nthird pass\n',
expectedExtension: '.md',
},
{
label: 'json',
kind: 'json',
mime: 'application/json',
// Единственный json-владелец MIME остаётся тем же: смена MIME проверяется явно ниже.
editedMime: 'application/json',
description: 'json journey description',
editedDescription: 'json journey description v2',
content: '{"journey":"body"}\n',
editedContent: '{"journey":"body","edited":true}\n',
// Третья версия — снова ВАЛИДНЫЙ JSON: правильная реализация обязана его принять,
// а не отказать (R-B).
thirdContent: '{"journey":"body","edited":true,"third":true}\n',
expectedExtension: '.json',
},
{
label: 'binary',
kind: 'binary',
mime: 'application/octet-stream',
editedMime: 'image/png',
description: 'binary journey description',
editedDescription: 'binary journey description v2',
bytes: BINARY_BYTES,
editedBytes: BINARY_BYTES_EDITED,
thirdBytes: Buffer.concat([BINARY_BYTES_EDITED, Buffer.from([0x11, 0x22])]),
expectedExtension: '.png',
},
];
/// Содержимое третьей версии: отдельные валидные bytes/текст, а не конкатенация с мусором.
function thirdPayload(scenario) {
return scenario.kind === 'binary'
? scenario.thirdBytes
: Buffer.from(scenario.thirdContent, 'utf8');
}
/// Метаданные части `metadata` из multipart-тела исходящего PUT (наблюдение того, что
/// отправляет сама форма, а не того, что ответил сервер).
function metadataFromMultipart(body) {
const match = /name="metadata"[\s\S]*?\r\n\r\n([\s\S]*?)\r\n--/.exec(body);
if (!match) return null;
try {
return JSON.parse(match[1]);
} catch (_error) {
return null;
}
}
async function fillCreateForm(page, scenario) {
const name = uniqueName(`journey${scenario.label}`);
await page.locator(FORM_URI).fill(`crank://e2e/${name}`);
await page.locator(FORM_NAME).fill(name);
await page.locator(FORM_KIND).selectOption(scenario.kind);
await page.locator(FORM_MIME).fill(scenario.mime);
await page.locator(FORM_SENSITIVITY).selectOption('internal');
await page.locator(FORM_DESCRIPTION).fill(scenario.description);
if (scenario.kind === 'binary') {
// Реальная загрузка файла произвольными bytes, а не строка в textarea.
await page.locator(FORM_FILE).setInputFiles({
name: 'journey.png',
mimeType: scenario.mime,
buffer: scenario.bytes,
});
} else {
await page.locator(FORM_CONTENT).fill(scenario.content);
}
await page.locator(FORM_SUBMIT).click();
return name;
}
async function selectFromList(page, name) {
const row = page.locator(LIST_ITEM, { hasText: name }).first();
await expect(
row,
`the Draft \`${name}\` must be selectable from the UI list (P1)`,
).toBeVisible();
await row.click();
const selected = new URL(page.url()).searchParams.get('resource_id');
expect(
selected,
'selecting a Draft must be reflected in the URL so reload restores it',
).toBeTruthy();
return selected;
}
/// SHA-256 независимым оракулом браузера (digest не берётся из ответа API).
async function sha256Base64(page, buffer) {
return page.evaluate(async (base64) => {
const raw = atob(base64);
const bytes = new Uint8Array(raw.length);
for (let index = 0; index < raw.length; index += 1) bytes[index] = raw.charCodeAt(index);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest))
.map((byte) => byte.toString(16).padStart(2, '0'))
.join('');
}, buffer.toString('base64'));
}
test('story36_at07_ui_journey_from_operations_creates_selects_edits_and_downloads', async ({ page }) => {
// Наблюдение исходящих PUT: проверяется то, что отправляет сама форма (R-B),
// а не только отсутствие ошибки в ответе.
const observedPuts = [];
await page.route('**/resources/*', async (route) => {
const request = route.request();
if (request.method() === 'PUT') {
const buffer = request.postDataBuffer();
observedPuts.push(buffer ? buffer.toString('utf8') : '');
}
await route.continue();
});
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
// 1. Вход из Operations обычной навигацией, а не прямым URL с ID.
await page.locator('a.nav-link[href="/resources"]').first().click();
await expect(page).toHaveURL(/\/resources(\?|$)/);
await expect(
page.locator(CREATE_FORM),
'Operations → Resources must offer a create form (P1): the page currently only renders a seeded preview',
).toBeVisible();
for (const scenario of SCENARIOS) {
// 2. Создание каждого kind через реальные клики формы.
const name = await fillCreateForm(page, scenario);
const selectedId = await selectFromList(page, name);
const originalBytes = scenario.kind === 'binary' ? scenario.bytes : Buffer.from(scenario.content, 'utf8');
const editedBytes =
scenario.kind === 'binary' ? scenario.editedBytes : Buffer.from(scenario.editedContent, 'utf8');
await expect(
page.locator(PREVIEW),
`${scenario.label}: selecting must load the Draft preview`,
).toBeVisible();
// Стабильные идентификаторы и точные metadata до редактирования.
await expect(page.locator(META_URI), `${scenario.label}: uri is stable`).toHaveText(
`crank://e2e/${name}`,
);
await expect(page.locator(META_NAME), `${scenario.label}: name is stable`).toHaveText(name);
await expect(page.locator(META_KIND), `${scenario.label}: kind is stable`).toHaveText(scenario.kind);
await expect(page.locator(META_MIME)).toHaveText(scenario.mime);
await expect(page.locator(META_SIZE)).toHaveText(String(originalBytes.length));
await expect(page.locator(META_VERSION), `${scenario.label}: first version`).toHaveText('1');
await expect(page.locator(META_DESCRIPTION)).toHaveText(scenario.description);
await expect(page.locator(META_SENSITIVITY)).toHaveText('internal');
const originalDigest = await sha256Base64(page, originalBytes);
await expect(page.locator(META_DIGEST), `${scenario.label}: digest of the stored bytes`).toHaveText(
originalDigest,
);
if (scenario.kind !== 'binary') {
await expect(
page.locator(PREVIEW_TEXT),
`${scenario.label}: preview must show the exact stored bytes`,
).toHaveText(scenario.content);
} else {
await expect(page.locator(PREVIEW_TEXT)).toHaveText('');
}
// 3. Редактирование изменяемых полей: description, MIME, sensitivity, content.
await expect(
page.locator(EDIT_FORM),
`${scenario.label}: the selected Draft must be editable (P1)`,
).toBeVisible();
await page.locator(EDIT_DESCRIPTION).fill(scenario.editedDescription);
await page.locator(EDIT_MIME).fill(scenario.editedMime);
await page.locator(EDIT_SENSITIVITY).selectOption('public');
if (scenario.kind === 'binary') {
await page.locator(EDIT_FILE).setInputFiles({
name: 'journey-edited.png',
mimeType: scenario.editedMime,
buffer: scenario.editedBytes,
});
} else {
await page.locator(EDIT_CONTENT).fill(scenario.editedContent);
}
await page.locator(EDIT_SUBMIT).click();
// 4. reload восстанавливает тот же Draft и показывает новые значения.
await page.reload();
await expect(page.locator(PREVIEW), 'reload must restore the selected Draft').toBeVisible();
await expect(page.locator(META_VERSION), `${scenario.label}: the edit must create version 2`).toHaveText(
'2',
);
await expect(page.locator(META_DESCRIPTION)).toHaveText(scenario.editedDescription);
await expect(page.locator(META_SENSITIVITY)).toHaveText('public');
await expect(page.locator(META_MIME)).toHaveText(scenario.editedMime);
await expect(page.locator(META_SIZE)).toHaveText(String(editedBytes.length));
const editedDigest = await sha256Base64(page, editedBytes);
expect(editedDigest, 'editing the content must change the digest').not.toBe(originalDigest);
await expect(page.locator(META_DIGEST)).toHaveText(editedDigest);
// uri/name/kind неизменяемы и после обновления.
await expect(page.locator(META_URI)).toHaveText(`crank://e2e/${name}`);
await expect(page.locator(META_NAME)).toHaveText(name);
await expect(page.locator(META_KIND)).toHaveText(scenario.kind);
await expect(page.locator(LIST_ITEM, { hasText: name }).first(), 'uri/name/kind stay stable').toBeVisible();
if (scenario.kind !== 'binary') {
await expect(page.locator(PREVIEW_TEXT), 'reload must show the edited bytes').toHaveText(
scenario.editedContent,
);
}
// Независимое чтение API подтверждает те же значения, что и страница.
const preview = await readResourcePreview(page, workspace.id, selectedId);
expect(preview.status, 'the edited Draft must stay readable').toBe(200);
expect(preview.json.version.version).toBe(2);
expect(preview.json.resource.uri).toBe(`crank://e2e/${name}`);
expect(preview.json.resource.name).toBe(name);
expect(preview.json.resource.kind).toBe(scenario.kind);
expect(preview.json.resource.description).toBe(scenario.editedDescription);
expect(preview.json.version.sensitivity).toBe('public');
expect(preview.json.version.mime_type).toBe(scenario.editedMime);
expect(preview.json.version.size_bytes).toBe(editedBytes.length);
// 5. Действительное скачивание кликом по ссылке — точные bytes и безопасное имя файла.
const [download] = await Promise.all([
page.waitForEvent('download'),
page.locator(DOWNLOAD).click(),
]);
const chunks = [];
const stream = await download.createReadStream();
for await (const chunk of stream) chunks.push(chunk);
const downloaded = Buffer.concat(chunks);
expect(
downloaded.toString('base64'),
`${scenario.label}: the clicked download must return the exact edited bytes`,
).toBe(editedBytes.toString('base64'));
const filename = download.suggestedFilename();
expect(
filename.endsWith(scenario.expectedExtension),
`${scenario.label}: derived filename must follow the declared MIME: ${filename}`,
).toBe(true);
expect(
filename.includes('/') || filename.includes('\\') || filename.includes('..'),
`${scenario.label}: filename must stay sanitized: ${filename}`,
).toBe(false);
// Заголовки скачивания не зависят от заявленного MIME (D-6).
const headers = await readResourceDownload(page, workspace.id, selectedId);
expect(headers.status).toBe(200);
expect(headers.headers['content-type']).toBe('application/octet-stream');
expect(headers.headers['content-disposition']).toMatch(/^attachment/);
expect(headers.bodyBase64).toBe(editedBytes.toString('base64'));
// 6. Второе редактирование после reload доказывает, что форма отправляет актуальный
// precondition и валидное содержимое третьей версии (R-B: валидный отдельный JSON,
// а не конкатенация с мусором, которую правильная реализация обязана отвергнуть).
const thirdBytes = thirdPayload(scenario);
const beforeThird = await readResourcePreview(page, workspace.id, selectedId);
expect(beforeThird.status, 'the card must be readable before the third edit').toBe(200);
const precondition = beforeThird.json.resource.updated_at;
expect(precondition, 'the card must expose its precondition timestamp').toBeTruthy();
const putsBeforeThird = observedPuts.length;
if (scenario.kind === 'binary') {
await page.locator(EDIT_FILE).setInputFiles({
name: 'journey-third.png',
mimeType: scenario.editedMime,
buffer: thirdBytes,
});
} else {
await page.locator(EDIT_CONTENT).fill(scenario.thirdContent);
}
await page.locator(EDIT_SUBMIT).click();
await page.reload();
await expect(page.locator(META_VERSION), 'a second edit after reload must succeed').toHaveText('3');
// 6a. Наблюдаемый запрос: форма действительно отправила актуальный precondition.
expect(
observedPuts.length,
'the third edit must be observable as an outgoing PUT request',
).toBeGreaterThan(putsBeforeThird);
const thirdMetadata = metadataFromMultipart(observedPuts[observedPuts.length - 1]);
expect(
thirdMetadata,
`the outgoing PUT must carry a metadata part: ${observedPuts[observedPuts.length - 1]}`,
).toBeTruthy();
expect(
thirdMetadata.expected_updated_at,
'the form must send the precondition it just read, not a stale or invented value',
).toBe(precondition);
expect(thirdMetadata.description).toBe(scenario.editedDescription);
expect(thirdMetadata.mime_type).toBe(scenario.editedMime);
expect(thirdMetadata.sensitivity).toBe('public');
expect(
Object.prototype.hasOwnProperty.call(thirdMetadata, 'uri'),
'an edit must not resend immutable identifiers',
).toBe(false);
// 6b. Наблюдаемое состояние: тот же Resource (URL и идентификаторы), новая версия,
// точные bytes третьей версии и обновлённый precondition.
const urlAfterThird = new URL(page.url());
expect(
urlAfterThird.searchParams.get('resource_id'),
'reload must keep the same selected Draft',
).toBe(selectedId);
await expect(page.locator(META_URI)).toHaveText(`crank://e2e/${name}`);
await expect(page.locator(META_NAME)).toHaveText(name);
await expect(page.locator(META_KIND)).toHaveText(scenario.kind);
await expect(page.locator(META_SIZE)).toHaveText(String(thirdBytes.length));
const thirdDigest = await sha256Base64(page, thirdBytes);
await expect(page.locator(META_DIGEST), 'the third version digest is the stored bytes digest').toHaveText(
thirdDigest,
);
if (scenario.kind !== 'binary') {
await expect(page.locator(PREVIEW_TEXT)).toHaveText(scenario.thirdContent);
}
const thirdPreview = await readResourcePreview(page, workspace.id, selectedId);
expect(thirdPreview.status).toBe(200);
expect(thirdPreview.json.version.version).toBe(3);
expect(thirdPreview.json.version.size_bytes).toBe(thirdBytes.length);
expect(thirdPreview.json.version.digest).toBe(thirdDigest);
expect(
thirdPreview.json.resource.updated_at,
'an accepted edit must move the precondition timestamp',
).not.toBe(precondition);
const thirdDownload = await readResourceDownload(page, workspace.id, selectedId);
expect(
thirdDownload.bodyBase64,
`${scenario.label}: the third version must serve the exact edited bytes`,
).toBe(thirdBytes.toString('base64'));
}
});
test('story36_at07_card_ok_with_refused_preview_is_a_visible_safe_error', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
// Существующий Draft: карточка читается (200), а отказ preview приходит на самом маршруте
// preview (422). Отсутствующий идентификатор не заменяет эту проверку (R-B).
const name = uniqueName('preview_refusal');
const metadata = {
uri: `crank://e2e/${name}`,
name,
description: 'preview refusal description',
kind: 'text',
mime_type: 'text/plain',
sensitivity: 'internal',
};
// Механизм наблюдения multipart-тела проверяется здесь же на состоявшемся create-запросе:
// если браузер не отдаёт тело, оракул третьей версии в основном сценарии был бы
// недоказуемым, а не «зелёным».
const observedCreateBodies = [];
await page.route('**/resources', async (route) => {
if (route.request().method() === 'POST') {
const buffer = route.request().postDataBuffer();
observedCreateBodies.push(buffer ? buffer.toString('utf8') : '');
}
await route.continue();
});
const created = await createResourceDraft(page, workspace.id, metadata, Buffer.from('visible body\n', 'utf8'), 'visible.txt', 'text/plain');
expect(created.status, `seeding the Draft must succeed: ${created.text}`).toBe(201);
const resourceId = created.json.resource.resource_id || created.json.resource.id;
await page.unroute('**/resources');
expect(
observedCreateBodies.length,
'the outgoing multipart create must be observable as a request body',
).toBeGreaterThan(0);
const observedCreateMetadata = metadataFromMultipart(observedCreateBodies[0]);
expect(observedCreateMetadata, `metadata part of the observed create: ${observedCreateBodies[0]}`).toBeTruthy();
expect(observedCreateMetadata.uri).toBe(metadata.uri);
expect(observedCreateMetadata.name).toBe(name);
// Первая навигация: preview отвечает безопасным отказом, карточка при этом 200.
let intercepted = 0;
await page.route('**/resources/*/preview', async (route) => {
intercepted += 1;
await route.fulfill({
status: 422,
contentType: 'application/json',
body: JSON.stringify({
error: {
code: 'resource_content_invalid_utf8',
message: 'resource content is not valid UTF-8',
context: { field: 'content' },
},
}),
});
});
await page.goto(
`/resources?resource_id=${encodeURIComponent(resourceId)}`,
);
await expect(
page.locator(PREVIEW_ERROR),
'a refused preview must be a visible safe error, not an empty success (P1/F08)',
).toBeVisible();
await expect(page.locator(PREVIEW_ERROR)).not.toHaveText('');
// Карточка при этом действительно загрузилась: отказ preview виден на состоявшемся экране.
await expect(page.locator(META_NAME)).toHaveText(name);
expect(intercepted, 'the intercepted preview route must have been exercised').toBeGreaterThan(0);
// Восстановление: валидный reload без подмены снова показывает содержимое.
await page.unroute('**/resources/*/preview');
await page.reload();
await expect(page.locator(PREVIEW_ERROR)).toHaveCount(0);
await expect(
page.locator(PREVIEW_TEXT),
'a valid reload must recover the preview',
).toHaveText('visible body\n');
});
// ---------------------------------------------------------------------------
// Активное содержимое: однофакторные негативы, каждый проверяется безусловно,
// плюс рабочий положительный контроль перехватчика маркера.
// ---------------------------------------------------------------------------
async function createDraft(page, workspace, metadata, bytes, filename, mimeType) {
const created = await createResourceDraft(page, workspace.id, metadata, bytes, filename, mimeType);
expect(
created.status,
`${metadata.kind}/${metadata.mime_type}: draft creation must succeed: ${created.text}`,
).toBe(201);
return created.json.resource.resource_id || created.json.resource.id;
}
// Положительный контроль «страница действительно загрузила данные именно этого Resource»:
// до него ни один негативный assertion не считается доказательством.
async function openLoadedPreview(page, resourceId, { kind, mime, size }) {
await page.goto(`/resources?resource_id=${encodeURIComponent(resourceId)}`);
await expect(page.locator(PREVIEW)).toBeVisible();
await expect(page.locator(META_KIND)).toHaveText(kind);
await expect(page.locator(META_MIME)).toHaveText(mime);
await expect(page.locator(META_SIZE)).toHaveText(String(size));
}
test('story36_at07_inert_preview_and_attachment_download', async ({ page }) => {
const markerRequests = [];
const dialogs = [];
const mainFrameNavigations = [];
page.on('request', (request) => {
if (request.url().includes(MARKER_PATH)) markerRequests.push(request.url());
});
await page.route(`**${MARKER_PATH}*`, (route) => {
markerRequests.push(route.request().url());
route.fulfill({ status: 200, body: 'marker' });
});
page.on('dialog', async (dialog) => {
dialogs.push(dialog.message());
await dialog.dismiss();
});
page.on('framenavigated', (frame) => {
if (frame === page.mainFrame()) mainFrameNavigations.push(frame.url());
});
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const origin = new URL(page.url()).origin;
// ---------------------------------------------------------------------
// 1. Разрешённая text-ветка: точное видимое содержимое и точные download bytes
// ---------------------------------------------------------------------
const literal = '<b id="story36-literal">story36 literal</b>';
const textPayload = `before ${literal} after\n<script>window.__c36_inline = "executed";</script>`;
const textBytes = Buffer.from(textPayload, 'utf8');
const textName = uniqueName('inert');
const textMeta = {
uri: `crank://e2e/${textName}`,
name: textName,
description: '',
kind: 'text',
mime_type: 'text/plain',
sensitivity: 'public',
};
const textId = await createDraft(page, workspace, textMeta, textBytes, 'inert.txt', 'text/plain');
await openLoadedPreview(page, textId, {
kind: 'text',
mime: 'text/plain',
size: textBytes.length,
});
// Инертный текст: literal markup виден как текст, а не как узел.
await expect(page.locator(PREVIEW_TEXT)).toHaveText(textPayload);
await expect(page.locator('#story36-literal')).toHaveCount(0);
await expect(page.locator(`${PREVIEW} script, ${PREVIEW} img, ${PREVIEW} a`)).toHaveCount(0);
expect(await page.evaluate(() => window.__c36_inline), 'inline markup must not execute').toBeUndefined();
const textDownload = await readResourceDownload(page, workspace.id, textId);
expect(textDownload.status).toBe(200);
expect(textDownload.headers['content-type']).toBe('application/octet-stream');
expect(textDownload.headers['content-disposition']).toMatch(/^attachment/);
expect(textDownload.headers['x-content-type-options']).toBe('nosniff');
expect(textDownload.headers['content-security-policy']).toBe("default-src 'none'; sandbox");
expect(textDownload.bodyBase64, 'download must return the exact stored bytes').toBe(
textBytes.toString('base64'),
);
// ---------------------------------------------------------------------
// 2. Разрешённая JSON-ветка: тот же инертный рендер, точные bytes
// ---------------------------------------------------------------------
const jsonPayload = '{"note":"<script>window.__c36_json = 1;</script>","n":1}';
const jsonBytes = Buffer.from(jsonPayload, 'utf8');
const jsonName = uniqueName('json');
const jsonMeta = {
uri: `crank://e2e/${jsonName}`,
name: jsonName,
description: '',
kind: 'json',
mime_type: 'application/json',
sensitivity: 'public',
};
const jsonId = await createDraft(page, workspace, jsonMeta, jsonBytes, 'payload.json', 'application/json');
await openLoadedPreview(page, jsonId, {
kind: 'json',
mime: 'application/json',
size: jsonBytes.length,
});
await expect(page.locator(PREVIEW_TEXT)).toHaveText(jsonPayload);
await expect(page.locator(`${PREVIEW} script`)).toHaveCount(0);
expect(await page.evaluate(() => window.__c36_json)).toBeUndefined();
const jsonDownload = await readResourceDownload(page, workspace.id, jsonId);
expect(jsonDownload.bodyBase64).toBe(jsonBytes.toString('base64'));
// ---------------------------------------------------------------------
// 3. binary-ветка: bytes не показываются вообще, metadata точная, download инертен
// ---------------------------------------------------------------------
const binaryCases = [
{
label: 'binary-html',
mime: 'text/html',
filename: '../../evil.html',
body: '<html><body><script>window.__c36_active = "html";</script><img src="x" onerror="window.__c36_active = \'handler\'"></body></html>',
},
{
label: 'binary-svg',
mime: 'image/svg+xml',
filename: 'evil.svg',
body: '<svg xmlns="http://www.w3.org/2000/svg" onload="window.__c36_active = \'svg\'"></svg>',
},
{
label: 'binary-octet-stream',
// UTF-8-валидная разметка, но kind=binary: ветка выбирается kind, а не разбором байтов.
mime: 'application/octet-stream',
filename: 'evil.bin',
body: `<img src="${MARKER_URL}"><script>window.__c36_active = "octet";</script>`,
},
{
label: 'binary-not-utf8',
// Реальные произвольные bytes: не-UTF8 последовательности не должны ломать экран.
mime: 'image/png',
filename: 'raw.png',
body: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff, 0xfe, 0x80, 0xc3, 0x28, 0x7f]),
},
];
for (const scenario of binaryCases) {
const bytes = Buffer.isBuffer(scenario.body) ? scenario.body : Buffer.from(scenario.body, 'utf8');
const name = uniqueName('active');
const metadata = {
uri: `crank://e2e/${name}`,
name,
description: '',
kind: 'binary',
mime_type: scenario.mime,
sensitivity: 'public',
};
const resourceId = await createDraft(page, workspace, metadata, bytes, scenario.filename, scenario.mime);
await openLoadedPreview(page, resourceId, {
kind: 'binary',
mime: scenario.mime,
size: bytes.length,
});
// Binary preview не отдаёт bytes (D-6): ни текста, ни активных узлов.
await expect(
page.locator(`${PREVIEW} script, ${PREVIEW} img, ${PREVIEW} svg, ${PREVIEW} iframe`),
`${scenario.label}: no active node may be rendered inside the preview`,
).toHaveCount(0);
await expect(
page.locator(PREVIEW_TEXT),
`${scenario.label}: a binary preview must show no content`,
).toHaveText('');
const previewHtml = await page.locator(PREVIEW).innerHTML();
expect(
previewHtml.includes('__c36_active'),
`${scenario.label}: preview must not embed the payload bytes: ${previewHtml}`,
).toBe(false);
expect(
await page.evaluate(() => window.__c36_active),
`${scenario.label}: markup must not execute`,
).toBeUndefined();
expect(dialogs, `${scenario.label}: no dialog may open`).toEqual([]);
expect(markerRequests, `${scenario.label}: no request to the external marker`).toEqual([]);
// Preview-эндпоинт подтверждает отсутствие bytes независимым чтением API.
const preview = await readResourcePreview(page, workspace.id, resourceId);
expect(preview.status, `${scenario.label}: preview endpoint must answer`).toBe(200);
expect(preview.json && preview.json.preview ? preview.json.preview.text : null).toBeNull();
const download = await readResourceDownload(page, workspace.id, resourceId);
expect(download.status).toBe(200);
expect(
download.headers['content-type'],
`${scenario.label}: declared MIME must not become the HTTP type`,
).toBe('application/octet-stream');
expect(download.headers['content-disposition']).toMatch(/^attachment/);
expect(download.bodyBase64, `${scenario.label}: download must return the exact stored bytes`).toBe(
bytes.toString('base64'),
);
}
// ---------------------------------------------------------------------
// 4. javascript: URL безусловно не становится ссылкой и не исполняется (D-5)
// ---------------------------------------------------------------------
const jsPayload = Buffer.from(
`<a id="story36-js-link" href="javascript:window.__c36_active = 'javascript'">open</a>`,
'utf8',
);
const jsName = uniqueName('jsurl');
const jsId = await createDraft(
page,
workspace,
{
uri: `crank://e2e/${jsName}`,
name: jsName,
description: '',
kind: 'binary',
mime_type: 'text/html',
sensitivity: 'public',
},
jsPayload,
'link.html',
'text/html',
);
await openLoadedPreview(page, jsId, {
kind: 'binary',
mime: 'text/html',
size: jsPayload.length,
});
await expect(
page.locator('#story36-js-link'),
'raw bytes must never become a link node inside the preview',
).toHaveCount(0);
await expect(
page.locator(`${PREVIEW} a[href^="javascript:"]`),
'no javascript: URL may reach a link inside the preview',
).toHaveCount(0);
expect(await page.evaluate(() => window.__c36_active), 'javascript: URL must not execute').toBeUndefined();
expect(markerRequests, 'an inert preview must not fetch the external marker').toEqual([]);
// Тот же payload как text обязан остаться инертным текстом, а не узлом-ссылкой.
const jsAsText = uniqueName('jsurl_text');
const jsAsTextId = await createDraft(
page,
workspace,
{
uri: `crank://e2e/${jsAsText}`,
name: jsAsText,
description: '',
kind: 'text',
mime_type: 'text/plain',
sensitivity: 'public',
},
jsPayload,
'link.txt',
'text/plain',
);
await openLoadedPreview(page, jsAsTextId, {
kind: 'text',
mime: 'text/plain',
size: jsPayload.length,
});
await expect(page.locator(PREVIEW_TEXT)).toHaveText(jsPayload.toString('utf8'));
await expect(page.locator('#story36-js-link')).toHaveCount(0);
await expect(page.locator(`${PREVIEW} a`)).toHaveCount(0);
expect(await page.evaluate(() => window.__c36_active)).toBeUndefined();
// ---------------------------------------------------------------------
// 5. Origin/navigation подтверждены: активное содержимое не увело страницу
// ---------------------------------------------------------------------
expect(new URL(page.url()).origin).toBe(origin);
expect(page.url()).toContain('/resources');
for (const url of mainFrameNavigations) {
expect(new URL(url).origin, `main frame must stay on the Crank origin: ${url}`).toBe(origin);
}
// 6. Положительный контроль sink-а: при настоящем внедрении перехватчик маркера сработал бы.
await page.evaluate((markerUrl) => {
const probe = document.createElement('img');
probe.src = markerUrl;
document.body.appendChild(probe);
}, MARKER_URL);
await expect
.poll(() => markerRequests.length, 'marker interception must observe a real request')
.toBeGreaterThan(0);
});
// ---------------------------------------------------------------------------
// F1–F3 (TL run109 CODE-REVIEW): один снимок ответа на экране, допуск поздних
// ответов только к актуальному выбору и форма, которая не переносит payload
// между двумя черновиками. Проверки идут на неизменённом actual `resources.js`;
// порядок ответов управляется через `page.route`, а не паузами в тесте.
// ---------------------------------------------------------------------------
const { createHash } = require('crypto');
function sha256HexUtf8(text) {
return createHash('sha256').update(Buffer.from(text, 'utf8')).digest('hex');
}
function textMetadata(uri, name, description, sensitivity = 'internal') {
return {
uri,
name,
description,
kind: 'text',
mime_type: 'text/plain',
sensitivity,
};
}
function binaryMetadata(uri, name, description) {
return {
uri,
name,
description,
kind: 'binary',
mime_type: 'application/octet-stream',
sensitivity: 'internal',
};
}
/// Захват исходящих PUT: наблюдается то, что реально отправляет форма.
function observePuts(page, observed) {
return page.route('**/resources/*', async (route) => {
const request = route.request();
if (request.method() === 'PUT') {
const buffer = request.postDataBuffer();
observed.push({ url: request.url(), body: buffer ? buffer.toString('utf8') : '' });
}
await route.continue();
});
}
/// F1: экран не смешивает metadata одного ответа с текстом другого.
///
/// Карточка отвечает снимком версии N (реальный ответ API до обновления), а
/// `preview` — снимком N+1 с другим текстом/digest/size/description/updated_at.
/// Ожидание: все отображаемые metadata, precondition формы и текст относятся к
/// **одному** из двух снимков, а не к разным.
test('story36_f1_the_screen_shows_metadata_and_text_of_one_single_snapshot', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const name = uniqueName('f1_snapshot');
const textV1 = 'f1 text of version one\n';
const created = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${name}`, name, 'f1 description v1'),
Buffer.from(textV1, 'utf8'),
'f1.txt',
'text/plain',
);
expect(created.status, `seeding the Draft must succeed: ${created.text}`).toBe(201);
const resourceId = created.json.resource.resource_id || created.json.resource.id;
// Реальные ответы API: снимок N берётся как есть, снимок N+1 отличается всеми
// наблюдаемыми полями и остаётся внутренне согласованным.
const previewN = await readResourcePreview(page, workspace.id, resourceId);
expect(previewN.status, 'the seeded snapshot must be readable').toBe(200);
const cardFixture = {
resource: previewN.json.resource,
version: previewN.json.version,
findings: previewN.json.findings || [],
};
const textN1 = 'f1 text of the later snapshot\n';
const descriptionN1 = 'f1 description v2';
const updatedAtN1 = '2026-01-02T03:04:05Z';
const digestN1 = sha256HexUtf8(textN1);
const previewFixture = {
resource: {
...previewN.json.resource,
description: descriptionN1,
current_draft_version: previewN.json.version.version + 1,
updated_at: updatedAtN1,
},
version: {
...previewN.json.version,
version: previewN.json.version.version + 1,
digest: digestN1,
size_bytes: Buffer.byteLength(textN1, 'utf8'),
created_at: updatedAtN1,
superseded_at: null,
},
findings: previewN.json.findings || [],
preview: { text: textN1 },
};
const observedPuts = [];
await page.route('**/resources/*', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname;
if (request.method() === 'GET' && path.endsWith(`/resources/${resourceId}`)) {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(cardFixture),
});
return;
}
if (request.method() === 'PUT') {
const buffer = request.postDataBuffer();
observedPuts.push({ url: request.url(), body: buffer ? buffer.toString('utf8') : '' });
}
await route.continue();
});
await page.route('**/resources/*/preview', async (route) => {
if (route.request().method() === 'GET') {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(previewFixture),
});
return;
}
await route.continue();
});
await page.goto(`/resources?resource_id=${encodeURIComponent(resourceId)}`);
await expect(page.locator(PREVIEW_TEXT), 'the later snapshot text must be displayed').toHaveText(
textN1,
);
const displayed = {
version: ((await page.locator(META_VERSION).textContent()) || '').trim(),
digest: ((await page.locator(META_DIGEST).textContent()) || '').trim(),
size: ((await page.locator(META_SIZE).textContent()) || '').trim(),
description: ((await page.locator(META_DESCRIPTION).textContent()) || '').trim(),
text: (await page.locator(PREVIEW_TEXT).textContent()) || '',
};
const snapshotN = {
version: String(cardFixture.version.version),
digest: cardFixture.version.digest,
size: String(cardFixture.version.size_bytes),
description: cardFixture.resource.description,
updated_at: cardFixture.resource.updated_at,
text: previewN.json.preview.text,
};
const snapshotN1 = {
version: String(previewFixture.version.version),
digest: digestN1,
size: String(Buffer.byteLength(textN1, 'utf8')),
description: descriptionN1,
updated_at: updatedAtN1,
text: textN1,
};
const same = (snapshot) =>
displayed.version === snapshot.version &&
displayed.digest === snapshot.digest &&
displayed.size === snapshot.size &&
displayed.description === snapshot.description &&
displayed.text === snapshot.text;
const matchesN = same(snapshotN);
const matchesN1 = same(snapshotN1);
expect(
matchesN || matchesN1,
'every displayed metadata field and the text must belong to one single API snapshot (F1); ' +
`observed ${JSON.stringify(displayed)}`,
).toBe(true);
// Precondition формы обязан быть precondition того же снимка, что показан на экране.
const shownUpdatedAt = matchesN1 ? updatedAtN1 : snapshotN.updated_at;
await page.locator(EDIT_DESCRIPTION).fill(displayed.description || '');
await page.locator(EDIT_SUBMIT).click();
await expect
.poll(() => observedPuts.length, 'the edit form must be observable as an outgoing PUT')
.toBeGreaterThan(0);
const metadata = metadataFromMultipart(observedPuts[observedPuts.length - 1].body);
expect(metadata, `the outgoing PUT must carry metadata: ${observedPuts[observedPuts.length - 1].body}`).toBeTruthy();
expect(
metadata.expected_updated_at,
'the precondition must come from the same snapshot as the displayed metadata and text (F1)',
).toBe(shownUpdatedAt);
});
/// F2: поздний ответ прежнего выбора не меняет ни экран, ни цель редактирования.
///
/// Сценарий: A выбран, его карточка удерживается; затем выбирается B и его карточка
/// тоже удерживается (пока текущий выбор не загружен, редактировать нельзя); после
/// загрузки B отпускается ответ A. Ожидание: экран, ссылка скачивания и следующая
/// правка относятся к актуальному выбору B, а поздний ответ A действительно получен и
/// прочитан страницей — иначе «экран не изменился» доказывало бы лишь то, что ответ не
/// дошёл (TL run111: `route.continue()` сам по себе — не барьер обработки).
test('story36_f2_a_late_response_of_a_previous_selection_must_not_change_the_edit_target', async ({
page,
}) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const nameA = uniqueName('f2_late_a');
const nameB = uniqueName('f2_late_b');
const draftA = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${nameA}`, nameA, 'f2 draft a'),
Buffer.from('f2 body a\n', 'utf8'),
'a.txt',
'text/plain',
);
const draftB = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${nameB}`, nameB, 'f2 draft b'),
Buffer.from('f2 body b\n', 'utf8'),
'b.txt',
'text/plain',
);
expect(draftA.status, `seed A: ${draftA.text}`).toBe(201);
expect(draftB.status, `seed B: ${draftB.text}`).toBe(201);
const idA = draftA.json.resource.resource_id;
const idB = draftB.json.resource.resource_id;
// Наблюдатель чтения тела ответа: он ставится до навигации и фиксирует момент, когда
// именно страница (а не тест) прочитала тело позднего ответа.
await page.addInitScript(() => {
const observed = {};
Object.defineProperty(window, '__crankF2', { value: { observed } });
const realFetch = window.fetch.bind(window);
window.fetch = function (input, init) {
const url = typeof input === 'string' ? input : (input && input.url) || '';
const pending = realFetch(input, init);
pending
.then((response) => {
const originalText = response.text.bind(response);
response.text = function () {
const body = originalText();
body.then(() => {
observed[url] = (observed[url] || 0) + 1;
});
return body;
};
})
.catch(() => {});
return pending;
};
});
let releaseA = () => {};
const holdA = new Promise((resolve) => {
releaseA = resolve;
});
let releaseB = () => {};
const holdB = new Promise((resolve) => {
releaseB = resolve;
});
let seenA = () => {};
const aRequestSeen = new Promise((resolve) => {
seenA = resolve;
});
let holdFirstB = true;
const observedPuts = [];
await page.route('**/resources/*', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname;
if (request.method() === 'GET' && path.endsWith(`/resources/${idA}`)) {
seenA();
await holdA;
await route.continue();
return;
}
if (request.method() === 'GET' && path.endsWith(`/resources/${idB}`) && holdFirstB) {
holdFirstB = false;
await holdB;
await route.continue();
return;
}
if (request.method() === 'PUT') {
const buffer = request.postDataBuffer();
observedPuts.push({ url: request.url(), body: buffer ? buffer.toString('utf8') : '' });
}
await route.continue();
});
await page.goto('/resources');
await selectFromList(page, nameA);
await aRequestSeen;
await selectFromList(page, nameB);
// Текущий выбор ещё не загружен: форма редактирования должна быть недоступна.
await expect(
page.locator(EDIT_DESCRIPTION),
'editing must stay unavailable until the current selection is loaded (F2)',
).toBeDisabled();
releaseB();
await expect(page.locator(META_NAME), 'the current selection must be loaded').toHaveText(nameB);
await expect(page.locator(EDIT_DESCRIPTION)).toBeEnabled();
releaseA();
// Барьер: поздний ответ A реально получен и его тело прочитано самой страницей.
await expect
.poll(
() =>
page.evaluate((suffix) => {
const observed = window.__crankF2.observed;
return Object.keys(observed)
.filter((url) => url.endsWith(suffix))
.reduce((total, url) => total + observed[url], 0);
}, `/resources/${idA}`),
'the late response of the previous selection must really be received and read by the page',
)
.toBeGreaterThan(0);
// Микротаски страницы (включая обработчик загрузки) завершаются до следующего кадра,
// поэтому это детерминированный барьер без произвольной задержки.
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => resolve())));
await expect(
page.locator(META_NAME),
'a late response of a previous selection must not replace the current one (F2)',
).toHaveText(nameB);
// R1/R3: и инертный текст предпросмотра обязан остаться текстом текущего выбора —
// поздний ответ A не должен подменить ни metadata, ни видимое содержимое.
await expect(
page.locator(PREVIEW_TEXT),
'the inert preview text must stay the current selection snapshot (F2/R1)',
).toHaveText('f2 body b\n');
expect(
new URL(page.url()).searchParams.get('resource_id'),
'the selected Draft in the URL must stay the current one',
).toBe(idB);
expect(
await page.locator(DOWNLOAD).getAttribute('href'),
'the download link must belong to the current selection (F2)',
).toBe(`/api/admin/workspaces/${workspace.id}/resources/${idB}/content`);
await page.locator(EDIT_DESCRIPTION).fill('f2 edited description');
await page.locator(EDIT_SUBMIT).click();
await expect
.poll(() => observedPuts.length, 'the edit must be observable as an outgoing PUT')
.toBeGreaterThan(0);
expect(
observedPuts[observedPuts.length - 1].url.endsWith(`/resources/${idB}`),
'the edit must go to the currently selected Draft, not to the late one (F2): ' +
observedPuts[observedPuts.length - 1].url,
).toBe(true);
});
/// F3a: форма редактирования показывает bytes текущего снимка и не переносит
/// введённый текст предыдущего выбора в следующий Draft.
test('story36_f3a_the_editor_shows_the_bytes_of_the_selected_snapshot', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const firstTextName = uniqueName('f3_text_one');
const secondTextName = uniqueName('f3_text_two');
const firstText = 'f3 stored text one\n';
const secondText = 'f3 stored text two\n';
const firstTextDraft = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${firstTextName}`, firstTextName, 'f3 text one'),
Buffer.from(firstText, 'utf8'),
'f3-one.txt',
'text/plain',
);
const secondTextDraft = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${secondTextName}`, secondTextName, 'f3 text two'),
Buffer.from(secondText, 'utf8'),
'f3-two.txt',
'text/plain',
);
for (const seeded of [firstTextDraft, secondTextDraft]) {
expect(seeded.status, `seeding the Draft must succeed: ${seeded.text}`).toBe(201);
}
const firstTextId = firstTextDraft.json.resource.resource_id;
// (1) Выбор Draft заполняет редактор его текущими bytes, без повторного ручного ввода.
await page.goto(`/resources?resource_id=${encodeURIComponent(firstTextId)}`);
await expect(page.locator(PREVIEW_TEXT)).toHaveText(firstText);
await expect(
page.locator(EDIT_CONTENT),
'the editor must show the bytes of the selected snapshot (F3)',
).toHaveValue(firstText);
// (2) Введённый текст предыдущего выбора не остаётся в редакторе другого Draft.
await page.goto('/resources');
await selectFromList(page, firstTextName);
await expect(page.locator(META_NAME)).toHaveText(firstTextName);
await expect(page.locator(EDIT_CONTENT)).toHaveValue(firstText);
await page.locator(EDIT_CONTENT).fill('f3 text typed for the previous selection');
await selectFromList(page, secondTextName);
await expect(page.locator(META_NAME)).toHaveText(secondTextName);
await expect(
page.locator(EDIT_CONTENT),
'text typed for a previous selection must not stay in the editor of another Draft (F3)',
).toHaveValue(secondText);
});
/// F3b: выбранный файл замены не переносится в следующий Draft; явно выбранный
/// файл текущего Draft при этом действительно отправляется.
test('story36_f3b_a_replacement_file_must_not_be_carried_between_drafts', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const binaryAName = uniqueName('f3_binary_a');
const binaryBName = uniqueName('f3_binary_b');
const markerA = 'C36-F3-FILE-FOR-A-MARKER';
const markerB = 'C36-F3-FILE-FOR-B-MARKER';
const binaryADraft = await createResourceDraft(
page,
workspace.id,
binaryMetadata(`crank://e2e/${binaryAName}`, binaryAName, 'f3 binary a'),
Buffer.from(`${markerA}\n`, 'utf8'),
'f3-a.bin',
'application/octet-stream',
);
const binaryBDraft = await createResourceDraft(
page,
workspace.id,
binaryMetadata(`crank://e2e/${binaryBName}`, binaryBName, 'f3 binary b'),
Buffer.from(`${markerB}\n`, 'utf8'),
'f3-b.bin',
'application/octet-stream',
);
for (const seeded of [binaryADraft, binaryBDraft]) {
expect(seeded.status, `seeding the Draft must succeed: ${seeded.text}`).toBe(201);
}
const binaryBId = binaryBDraft.json.resource.resource_id;
const observedPuts = [];
await observePuts(page, observedPuts);
await page.goto('/resources');
await selectFromList(page, binaryAName);
await expect(page.locator(META_NAME)).toHaveText(binaryAName);
await page.locator(EDIT_FILE).setInputFiles({
name: 'for-a.bin',
mimeType: 'application/octet-stream',
buffer: Buffer.from(`${markerA}-SELECTED\n`, 'utf8'),
});
expect(
await page.locator(EDIT_FILE).inputValue(),
'the chosen replacement file must be observable before the selection changes',
).toContain('for-a.bin');
await selectFromList(page, binaryBName);
await expect(page.locator(META_NAME)).toHaveText(binaryBName);
expect(
await page.locator(EDIT_FILE).inputValue(),
'a replacement file chosen for another Draft must not stay selected for this one (F3)',
).toBe('');
// R3 (TL run113): binary-черновик не сохраняется «без файла». Пока файл замены не выбран
// заново, submit обязан дать видимый отказ, не отправить ни одного PUT и не изменить
// состояние B (ни версию, ни bytes). Промолчавшее сохранение считалось бы потерей данных.
const beforeRefusal = observedPuts.length;
await page.locator(EDIT_SUBMIT).click();
await expect(
page.locator(EDIT_STATUS),
'saving a binary draft without a chosen replacement file must show a visible refusal',
).toHaveText(/file|файл/i);
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => resolve())));
expect(
observedPuts.length,
'a refused binary save without a replacement file must not send any PUT',
).toBe(beforeRefusal);
await expect(
page.locator(META_VERSION),
'a refused binary save must not create a new version of the selected draft',
).toHaveText('1');
const refusedBytes = await readResourceDownload(page, workspace.id, binaryBId);
expect(refusedBytes.status, 'the refused draft must still be downloadable').toBe(200);
expect(
Buffer.from(refusedBytes.bodyBase64, 'base64').toString('utf8'),
'a refused binary save must leave the selected draft bytes exactly as they were',
).toBe(`${markerB}\n`);
// Положительный контроль канала наблюдения: явно выбранный файл текущего Draft
// действительно уходит в PUT именно этого Draft.
await page.locator(EDIT_FILE).setInputFiles({
name: 'for-b.bin',
mimeType: 'application/octet-stream',
buffer: Buffer.from(`${markerB}-SELECTED\n`, 'utf8'),
});
const before = observedPuts.length;
await page.locator(EDIT_SUBMIT).click();
await expect
.poll(() => observedPuts.length, 'the explicit replacement must be observable as a PUT')
.toBeGreaterThan(before);
const explicit = observedPuts[observedPuts.length - 1];
expect(
explicit.url.endsWith(`/resources/${binaryBId}`),
`the explicit replacement must go to the current Draft: ${explicit.url}`,
).toBe(true);
expect(
explicit.body.includes(`${markerB}-SELECTED`),
'an explicitly chosen file must be sent for the current Draft',
).toBe(true);
expect(
explicit.body.includes(markerA),
'the payload of a previously selected Draft must never be sent for this one (F3)',
).toBe(false);
});
/// R3 (TL run113 F3a): обычное редактирование обязано действительно сохраняться.
///
/// Для kind=text И kind=json редактор уже содержит действующие bytes выбранного
/// черновика; меняется только metadata (описание), содержимое не вводится заново.
/// Принятая версия проверяется независимо: карточкой API, текстом предпросмотра и
/// точными bytes скачивания, а не только наблюдаемым исходящим PUT.
test('story36_f3a_metadata_only_edit_is_accepted_and_keeps_exact_bytes', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const scenarios = [
{ label: 'text', mime: 'text/plain', extension: 'txt', body: 'metadata only text body\n' },
{
label: 'json',
mime: 'application/json',
extension: 'json',
body: '{"metadata":"only"}\n',
},
];
for (const scenario of scenarios) {
const name = uniqueName(`f3_meta_${scenario.label}`);
const metadata =
scenario.label === 'json'
? {
uri: `crank://e2e/${name}`,
name,
description: `f3 metadata-only ${scenario.label}`,
kind: 'json',
mime_type: 'application/json',
sensitivity: 'internal',
}
: textMetadata(`crank://e2e/${name}`, name, `f3 metadata-only ${scenario.label}`);
const seeded = await createResourceDraft(
page,
workspace.id,
metadata,
Buffer.from(scenario.body, 'utf8'),
`${name}.${scenario.extension}`,
scenario.mime,
);
expect(seeded.status, `seeding the ${scenario.label} draft: ${seeded.text}`).toBe(201);
const id = seeded.json.resource.resource_id;
const observedPuts = [];
await observePuts(page, observedPuts);
await page.goto(`/resources?resource_id=${encodeURIComponent(id)}`);
await expect(page.locator(PREVIEW_TEXT)).toHaveText(scenario.body);
await expect(
page.locator(EDIT_CONTENT),
'the editor must already contain the stored bytes of the selected draft (F3/R3)',
).toHaveValue(scenario.body);
const editedDescription = `metadata only ${scenario.label} v2`;
await page.locator(EDIT_DESCRIPTION).fill(editedDescription);
const before = observedPuts.length;
await page.locator(EDIT_SUBMIT).click();
await expect(
page.locator(EDIT_STATUS),
'an accepted metadata-only edit must be observable as a successful save',
).toHaveText(/saved|сохранен/i);
await expect(
page.locator(META_VERSION),
'a metadata-only edit must create the next version, not silently do nothing',
).toHaveText('2');
await expect(page.locator(META_DESCRIPTION)).toHaveText(editedDescription);
await expect(
page.locator(PREVIEW_TEXT),
'the inert preview must still show the exact stored bytes after the edit',
).toHaveText(scenario.body);
await expect(
page.locator(EDIT_CONTENT),
'the editor must keep showing the accepted bytes after the edit',
).toHaveValue(scenario.body);
// Содержимое не вводилось заново: на провод ушли именно прежние bytes редактора.
expect(
observedPuts.length,
`the metadata-only edit must be sent as a PUT for the selected draft (${scenario.label})`,
).toBeGreaterThan(before);
const sent = observedPuts[observedPuts.length - 1];
expect(
sent.url.endsWith(`/resources/${id}`),
`the metadata-only edit must go to the selected draft: ${sent.url}`,
).toBe(true);
expect(
sent.body.includes(scenario.body.trim()),
'the pre-filled editor bytes must be sent without retyping them',
).toBe(true);
// Независимая проверка принятой версии: карточка и точные bytes скачивания.
const card = await browserJson(
page,
'GET',
`/api/admin/workspaces/${workspace.id}/resources/${id}`,
undefined,
[200],
);
expect(card.version.version, 'the stored version must be the next one').toBe(2);
expect(card.resource.description).toBe(editedDescription);
expect(card.version.size_bytes).toBe(Buffer.byteLength(scenario.body));
const download = await readResourceDownload(page, workspace.id, id);
expect(download.status, 'the new version must stay downloadable').toBe(200);
expect(
Buffer.from(download.bodyBase64, 'base64').toString('utf8'),
'a metadata-only edit must keep the exact original bytes',
).toBe(scenario.body);
}
});
/// R1 (TL run113 BH2): пока новый выбор не загружен (или его загрузка отказала), экран
/// не должен оставлять доступным действие прежнего выбора — ссылку скачивания A.
///
/// Маршрут: A загружен полностью (ссылка A видна как положительный контроль) → выбор B
/// удержан → ссылка A недоступна → загрузка B отказала → ссылка A по-прежнему недоступна
/// и виден отказ → успешный выбор B даёт ссылку/идентичность/фактические bytes B →
/// поздний ответ предпросмотра A не подменяет снимок B.
test('story36_r1_a_pending_or_failed_selection_must_not_leave_the_previous_download_reachable', async ({
page,
}) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
const nameA = uniqueName('r1_prev_a');
const nameB = uniqueName('r1_next_b');
const bodyA = 'r1 body a\n';
const bodyB = 'r1 body b\n';
const draftA = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${nameA}`, nameA, 'r1 draft a'),
Buffer.from(bodyA, 'utf8'),
'r1-a.txt',
'text/plain',
);
const draftB = await createResourceDraft(
page,
workspace.id,
textMetadata(`crank://e2e/${nameB}`, nameB, 'r1 draft b'),
Buffer.from(bodyB, 'utf8'),
'r1-b.txt',
'text/plain',
);
expect(draftA.status, `seed A: ${draftA.text}`).toBe(201);
expect(draftB.status, `seed B: ${draftB.text}`).toBe(201);
const idA = draftA.json.resource.resource_id;
const idB = draftB.json.resource.resource_id;
// Наблюдатель чтения тела ответа: фиксирует момент, когда страница действительно
// прочитала поздний ответ предпросмотра A (не только получила его по сети).
await page.addInitScript(() => {
const observed = {};
Object.defineProperty(window, '__crankR1', { value: { observed } });
const realFetch = window.fetch.bind(window);
window.fetch = function (input, init) {
const url = typeof input === 'string' ? input : (input && input.url) || '';
const pending = realFetch(input, init);
pending
.then((response) => {
const originalText = response.text.bind(response);
response.text = function () {
const body = originalText();
body.then(() => {
observed[url] = (observed[url] || 0) + 1;
});
return body;
};
})
.catch(() => {});
return pending;
};
});
const control = { holdB: true, failB: true };
let releaseB = () => {};
const holdB = new Promise((resolve) => {
releaseB = resolve;
});
let releasePreviewA = () => {};
const holdPreviewA = new Promise((resolve) => {
releasePreviewA = resolve;
});
let seenPreviewA = () => {};
const previewASeen = new Promise((resolve) => {
seenPreviewA = resolve;
});
await page.route('**/resources/**', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname;
if (request.method() === 'GET' && path.endsWith(`/resources/${idA}/preview`)) {
seenPreviewA();
await holdPreviewA;
await route.continue();
return;
}
if (request.method() === 'GET' && path.endsWith(`/resources/${idB}`) && control.holdB) {
control.holdB = false;
await holdB;
if (control.failB) {
await route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({
error: { code: 'internal_error', message: 'forced e2e failure' },
}),
});
return;
}
}
await route.continue();
});
const downloadHrefA = `/api/admin/workspaces/${workspace.id}/resources/${idA}/content`;
const downloadHrefB = `/api/admin/workspaces/${workspace.id}/resources/${idB}/content`;
await page.goto('/resources');
// (1) A загружен: карточка применена, а ссылка скачивания A доступна — это
// положительный контроль того, что «недоступно» ниже действительно наблюдение.
await selectFromList(page, nameA);
await previewASeen;
await expect(page.locator(META_NAME)).toHaveText(nameA);
await expect(
page.locator(DOWNLOAD),
'a loaded selection must offer its own download',
).toBeVisible();
expect(await page.locator(DOWNLOAD).getAttribute('href')).toBe(downloadHrefA);
// (2) Выбор B удержан: наблюдается, осталась ли доступной ссылка прежнего выбора.
// Наблюдение не прерывает тест: иначе непроверяемыми остались бы ветки отказа и успеха.
await selectFromList(page, nameB);
const pendingVisible = await page.locator(DOWNLOAD).isVisible();
const pendingHref = await page.locator(DOWNLOAD).getAttribute('href');
// (3) Загрузка B отказала: отказ виден, ссылка прежнего выбора наблюдается снова.
releaseB();
await expect(
page.locator('#resources-status'),
'a failed selection must be visible as an error state',
).toHaveText('forced e2e failure');
const failedVisible = await page.locator(DOWNLOAD).isVisible();
const failedHref = await page.locator(DOWNLOAD).getAttribute('href');
// (4) Успешный выбор B: ссылка, идентичность и фактические bytes относятся к B.
control.failB = false;
await selectFromList(page, nameB);
await expect(page.locator(META_NAME)).toHaveText(nameB);
await expect(page.locator(PREVIEW_TEXT)).toHaveText(bodyB);
await expect(page.locator(DOWNLOAD)).toBeVisible();
expect(
await page.locator(DOWNLOAD).getAttribute('href'),
'the download link must belong to the current selection (R1)',
).toBe(downloadHrefB);
const downloadB = await readResourceDownload(page, workspace.id, idB);
expect(downloadB.status, 'the current selection must be downloadable').toBe(200);
expect(
Buffer.from(downloadB.bodyBase64, 'base64').toString('utf8'),
'the download must serve the bytes of the current selection (R1)',
).toBe(bodyB);
// (5) Поздний ответ предпросмотра A (он был удержан) действительно получен и прочитан
// страницей, но снимок текущего выбора B не подменяет.
releasePreviewA();
await expect
.poll(
() =>
page.evaluate((suffix) => {
const observed = window.__crankR1.observed;
return Object.keys(observed)
.filter((url) => url.endsWith(suffix))
.reduce((total, url) => total + observed[url], 0);
}, `/resources/${idA}/preview`),
'the late preview of the previous selection must really be received and read by the page',
)
.toBeGreaterThan(0);
await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => resolve())));
await expect(
page.locator(PREVIEW_TEXT),
'a late preview of the previous selection must not replace the current snapshot (R1)',
).toHaveText(bodyB);
await expect(page.locator(META_NAME)).toHaveText(nameB);
expect(await page.locator(DOWNLOAD).getAttribute('href')).toBe(downloadHrefB);
// Итоговый вердикт R1: в обоих состояниях нового выбора доступной ссылки прежнего
// черновика быть не должно. Все наблюдения перечислены в сообщении.
const observations = [
`while the new selection was pending: visible=${pendingVisible} href=${pendingHref}`,
`after the new selection failed: visible=${failedVisible} href=${failedHref}`,
];
expect(
pendingVisible || failedVisible,
'the download of the previous selection must not stay reachable while the newly selected ' +
`draft is pending or its load has failed (R1); observations: ${observations.join('; ')}`,
).toBe(false);
});