Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
750 lines
34 KiB
JavaScript
750 lines
34 KiB
JavaScript
// ATDD (RED) для Story 3.15 — UI переноса шаблонов сообщений (Prompts): export Draft,
|
||
// export точной Published Version, импорт envelope как нового owned Draft, состояния
|
||
// RU/EN, validation/error/confirmation/loading/stale-response и inert preview.
|
||
//
|
||
// Источники: `epics.md`:2887–2918 (AC1/AC2/AC3), Gitea #22, принятый контракт
|
||
// `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-prompt-portability/spec.md` §5,
|
||
// `test-design-epic-3.md`:117 (3.15-E2E-A/B), принятый аналог Story 3.9
|
||
// (`resources-story39.spec.js`).
|
||
//
|
||
// Состояние на этой стадии: страница `/prompts` умеет list/select/edit/publish/archive
|
||
// (Story 3.12/3.13), но импорт/экспорт отсутствуют. Каждый тест доходит до конкретного
|
||
// отсутствующего пользовательского действия и падает на реальном отсутствии UI, а не на
|
||
// setup; seed/publish — существующие принятые контракты (позитивный контроль харнесса).
|
||
//
|
||
// Требуемый UI-контракт (data-testid — часть ATDD):
|
||
// prompt-export, prompt-published-export, prompt-import, prompt-import-file,
|
||
// prompt-import-submit, prompt-import-preview, prompt-import-confirm(+ -confirm-accept/-cancel),
|
||
// prompt-import-status, prompt-import-error, prompt-portability-stale.
|
||
// Импорт: структурная проверка файла до сети, inert-предпросмотр последствий («новый Draft,
|
||
// без публикации»), явное подтверждение, затем реальный POST .../prompts/import.
|
||
//
|
||
// Запуск: npm --prefix apps/ui run e2e -- tests/e2e/prompts-story315.spec.js --workers=1 --retries=0
|
||
|
||
const fs = require('fs');
|
||
const { test, expect } = require('@playwright/test');
|
||
const { browserJson, getCurrentWorkspace, login, uniqueName } = require('./helpers');
|
||
|
||
const EXPORT = '[data-testid="prompt-export"]';
|
||
const PUBLISHED_EXPORT = '[data-testid="prompt-published-export"]';
|
||
const IMPORT = '[data-testid="prompt-import"]';
|
||
const IMPORT_FILE = '[data-testid="prompt-import-file"]';
|
||
const IMPORT_SUBMIT = '[data-testid="prompt-import-submit"]';
|
||
const IMPORT_PREVIEW = '[data-testid="prompt-import-preview"]';
|
||
const IMPORT_CONFIRM = '[data-testid="prompt-import-confirm"]';
|
||
const IMPORT_CONFIRM_ACCEPT = '[data-testid="prompt-import-confirm-accept"]';
|
||
const IMPORT_CANCEL = '[data-testid="prompt-import-cancel"]';
|
||
const IMPORT_STATUS = '[data-testid="prompt-import-status"]';
|
||
const IMPORT_ERROR = '[data-testid="prompt-import-error"]';
|
||
const STALE_ALERT = '[data-testid="prompt-portability-stale"]';
|
||
const LIST_ITEM = '[data-testid="prompt-list-item"]';
|
||
const STATE_LABEL = '#prompt-state-label';
|
||
const STATE_DETAIL = '#prompt-state-detail';
|
||
const PUBLISHED = '[data-testid="prompt-published"]';
|
||
const PUBLISHED_VERSION = '#prompt-published-version';
|
||
|
||
const ENVELOPE_FORMAT = 'crank-prompt-portability';
|
||
const ENVELOPE_VERSION = 1;
|
||
const DRAFT_STATUS = /draft|черновик/i;
|
||
const PUBLISHED_STATUS = /published|опубликован/i;
|
||
const IMPORTED_NOTICE = /import|импорт/i;
|
||
const EXPORT_LABEL = /export|экспорт/i;
|
||
const IMPORT_LABEL = /import|импорт/i;
|
||
const RU_EXPORT = /экспорт/i;
|
||
const RU_IMPORT = /импорт/i;
|
||
|
||
function promptPayload(name, description = 'story315 ui fixture') {
|
||
return {
|
||
name,
|
||
description,
|
||
sensitivity: 'internal',
|
||
arguments: [
|
||
{ name: 'count', schema: { type: 'integer' }, required: true },
|
||
{
|
||
name: 'tone',
|
||
schema: { type: 'string', enum: ['warm', 'plain'] },
|
||
required: false,
|
||
default: 'warm',
|
||
},
|
||
],
|
||
messages: [
|
||
{ role: 'system', content: 'Be {{tone}}.' },
|
||
{ role: 'user', content: 'Count {{count}}.' },
|
||
{ role: 'assistant', content: 'Done.' },
|
||
],
|
||
};
|
||
}
|
||
|
||
function promptBlock(payload) {
|
||
return {
|
||
name: payload.name,
|
||
description: payload.description,
|
||
sensitivity: payload.sensitivity,
|
||
arguments: payload.arguments,
|
||
messages: payload.messages,
|
||
};
|
||
}
|
||
|
||
function portableEnvelope(payload, source = { kind: 'draft', version: 1 }) {
|
||
return {
|
||
format: ENVELOPE_FORMAT,
|
||
version: ENVELOPE_VERSION,
|
||
prompt: promptBlock(payload),
|
||
source,
|
||
};
|
||
}
|
||
|
||
async function openPrompts(page) {
|
||
await page.goto('/prompts');
|
||
await expect(page.locator('[data-testid="prompts-page"]')).toBeVisible();
|
||
await page.waitForFunction(() => {
|
||
const items = document.querySelectorAll('[data-testid="prompt-list-item"]').length;
|
||
const empty = document.getElementById('prompt-empty');
|
||
return items > 0 || (empty && !empty.hidden);
|
||
});
|
||
}
|
||
|
||
async function selectPrompt(page, name) {
|
||
await page.locator(LIST_ITEM).filter({ hasText: name }).click();
|
||
await expect(page.locator(STATE_LABEL)).toBeVisible();
|
||
}
|
||
|
||
async function pageContext(page) {
|
||
const workspace = await getCurrentWorkspace(page);
|
||
const base = `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/prompts`;
|
||
return { workspace, base };
|
||
}
|
||
|
||
async function seedPrompt(page, base, payload) {
|
||
const created = await browserJson(page, 'POST', base, payload, [201]);
|
||
return created.prompt_id;
|
||
}
|
||
|
||
async function publishPrompt(page, base, promptId) {
|
||
const draft = await browserJson(page, 'GET', `${base}/${promptId}`);
|
||
return browserJson(page, 'POST', `${base}/${promptId}`, {
|
||
action: 'publish',
|
||
expected_updated_at: draft.updated_at,
|
||
});
|
||
}
|
||
|
||
async function listPrompts(page, base) {
|
||
return browserJson(page, 'GET', base);
|
||
}
|
||
|
||
async function setImportFile(page, content) {
|
||
await page.locator(IMPORT_FILE).setInputFiles({
|
||
name: 'prompt.crank-prompt.json',
|
||
mimeType: 'application/json',
|
||
buffer: Buffer.from(typeof content === 'string' ? content : JSON.stringify(content)),
|
||
});
|
||
}
|
||
|
||
async function downloadEnvelope(page, selector) {
|
||
await expect(
|
||
page.locator(selector),
|
||
'the portability export action must exist on the Prompts screen',
|
||
).toBeVisible();
|
||
const [download] = await Promise.all([
|
||
page.waitForEvent('download'),
|
||
page.locator(selector).click(),
|
||
]);
|
||
const path = await download.path();
|
||
const raw = fs.readFileSync(path, 'utf8');
|
||
return { download, raw, envelope: JSON.parse(raw) };
|
||
}
|
||
|
||
function expectAllowlistedEnvelope(envelope, { payload, source }) {
|
||
expect(envelope.format).toBe(ENVELOPE_FORMAT);
|
||
expect(envelope.version).toBe(ENVELOPE_VERSION);
|
||
expect(Object.keys(envelope).sort()).toEqual(['format', 'prompt', 'source', 'version']);
|
||
expect(Object.keys(envelope.prompt).sort()).toEqual([
|
||
'arguments',
|
||
'description',
|
||
'messages',
|
||
'name',
|
||
'sensitivity',
|
||
]);
|
||
expect(Object.keys(envelope.source).sort()).toEqual(['kind', 'version']);
|
||
expect(envelope.prompt).toEqual(promptBlock(payload));
|
||
expect(envelope.source).toEqual(source);
|
||
|
||
// Манифест не содержит идентичностей/lifecycle/хранилищных полей.
|
||
const manifest = JSON.stringify(envelope);
|
||
expect(manifest).not.toMatch(
|
||
/prompt_id|workspace_id|owner|"status"|published_at|created_at|storage|artifact|credential/i,
|
||
);
|
||
expect(manifest).not.toMatch(/\/home\/|\.tmp\/|postgres:\/\//);
|
||
}
|
||
|
||
/// Счётчик реально отправленных POST на импорт: структурно неверный файл не должен
|
||
/// доходить до сети.
|
||
function countImportPosts(page) {
|
||
const counter = { count: 0 };
|
||
page.on('request', (request) => {
|
||
if (request.method() === 'POST' && /\/prompts\/import$/.test(request.url())) {
|
||
counter.count += 1;
|
||
}
|
||
});
|
||
return counter;
|
||
}
|
||
|
||
/// Клавиатурный путь: до элемента доходим Tab-ами, активируем Enter/Space.
|
||
async function focusByTab(page, selector, maxTabs = 6) {
|
||
for (let attempt = 0; attempt < maxTabs; attempt += 1) {
|
||
await page.keyboard.press('Tab');
|
||
if (await page.locator(selector).evaluate((node) => node === document.activeElement)) {
|
||
return;
|
||
}
|
||
}
|
||
throw new Error(`the control ${selector} must be reachable with Tab in at most ${maxTabs} steps`);
|
||
}
|
||
|
||
test.describe('Story 3.15 Prompt portability', () => {
|
||
test('story315_at02_export_import_ui_creates_new_draft_and_never_publishes', async ({
|
||
page,
|
||
}) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const name = uniqueName('story315_export');
|
||
const sourcePayload = promptPayload(name, 'story315 export fixture');
|
||
const sourceId = await seedPrompt(page, base, sourcePayload);
|
||
|
||
await page.evaluate(() => window.setLang('en'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, name);
|
||
|
||
// AC1/AC3: экспорт Draft из UI — реальный скачанный envelope с definition.
|
||
const draftExport = await downloadEnvelope(page, EXPORT);
|
||
expect(draftExport.download.suggestedFilename()).toMatch(/\.crank-prompt\.json$/);
|
||
expectAllowlistedEnvelope(draftExport.envelope, {
|
||
payload: sourcePayload,
|
||
source: { kind: 'draft', version: 1 },
|
||
});
|
||
|
||
// AC2: пока файл не выбран, предпросмотра и подтверждения нет (empty state).
|
||
await expect(page.locator(IMPORT)).toBeVisible();
|
||
await expect(page.locator(IMPORT_PREVIEW)).toHaveCount(0);
|
||
await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0);
|
||
|
||
// AC1: импорт всегда создаёт новый Draft текущего владельца, без автопубликации.
|
||
const targetName = uniqueName('story315_imported');
|
||
const targetPayload = {
|
||
...promptPayload(targetName, 'story315 imported fixture'),
|
||
messages: [
|
||
{ role: 'system', content: 'Be {{tone}}, safely.' },
|
||
{ role: 'user', content: 'Imported count {{count}}.' },
|
||
],
|
||
};
|
||
const before = (await listPrompts(page, base)).items.length;
|
||
|
||
await setImportFile(page, portableEnvelope(targetPayload));
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(
|
||
page.locator(IMPORT_PREVIEW),
|
||
'a structurally valid envelope must show the consequences before creating a Draft',
|
||
).toBeVisible();
|
||
await expect(page.locator(IMPORT_PREVIEW)).toContainText(targetName);
|
||
await expect(
|
||
page.locator(IMPORT_PREVIEW),
|
||
'the preview must state that a new Draft is created and nothing is published',
|
||
).toContainText(DRAFT_STATUS);
|
||
await expect(page.locator(IMPORT_CONFIRM), 'import must be confirmed explicitly').toBeVisible();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toContainText(targetName);
|
||
|
||
const untouched = await listPrompts(page, base);
|
||
expect(
|
||
untouched.items.length,
|
||
'nothing may be created before the confirmation is accepted',
|
||
).toBe(before);
|
||
|
||
await page.locator(IMPORT_CONFIRM_ACCEPT).click();
|
||
await expect(page.locator(IMPORT_STATUS)).toHaveText(IMPORTED_NOTICE);
|
||
|
||
const after = await listPrompts(page, base);
|
||
expect(after.items.length, 'the import must add exactly one Draft').toBe(before + 1);
|
||
const importedCard = after.items.find((item) => item.name === targetName);
|
||
expect(importedCard, 'the imported Draft must appear in the list').toBeTruthy();
|
||
const importedId = importedCard.prompt_id;
|
||
expect(importedId, 'import must create a new Prompt identity').not.toBe(sourceId);
|
||
expect(importedCard.status).toBe('draft');
|
||
expect(importedCard.latest_published_version).toBeNull();
|
||
expect(importedCard.definition.arguments).toEqual(targetPayload.arguments);
|
||
expect(importedCard.definition.messages).toEqual(targetPayload.messages);
|
||
|
||
// UI различает Draft и Published Version: у импортированного публикаций нет.
|
||
await openPrompts(page);
|
||
await selectPrompt(page, targetName);
|
||
await expect(page.locator(STATE_LABEL)).toHaveText(DRAFT_STATUS);
|
||
await expect(page.locator(PUBLISHED)).toHaveCount(0);
|
||
await expect(page.locator(PUBLISHED_EXPORT)).toHaveCount(0);
|
||
|
||
// AC1/AC3: экспорт точной Published Version — после явной публикации Draft.
|
||
await publishPrompt(page, base, importedId);
|
||
// AC1/AC3 (immutable, QA F4): правка Draft после публикации не меняет снимок v1,
|
||
// поэтому экспорт точной версии обязан нести именно опубликованный контент.
|
||
const publishedDraft = await browserJson(page, 'GET', `${base}/${importedId}`);
|
||
const editedPayload = {
|
||
...targetPayload,
|
||
description: 'story315 draft edited after publication',
|
||
};
|
||
const edited = await browserJson(page, 'PUT', `${base}/${importedId}`, {
|
||
...editedPayload,
|
||
expected_updated_at: publishedDraft.updated_at,
|
||
});
|
||
expect(edited.version, 'the edit opens a new Draft revision').toBe(2);
|
||
await openPrompts(page);
|
||
await selectPrompt(page, targetName);
|
||
await expect(page.locator(STATE_LABEL)).toHaveText(DRAFT_STATUS);
|
||
await page.locator('#prompt-view-published').click();
|
||
await expect(page.locator(PUBLISHED)).toBeVisible();
|
||
await expect(page.locator(PUBLISHED_VERSION)).toHaveText('v1');
|
||
const publishedExport = await downloadEnvelope(page, PUBLISHED_EXPORT);
|
||
expectAllowlistedEnvelope(publishedExport.envelope, {
|
||
payload: targetPayload,
|
||
source: { kind: 'published', version: 1 },
|
||
});
|
||
|
||
// Источник остался неизменным: каждая установка/workspace получил свой Draft.
|
||
const sourceAfter = await browserJson(page, 'GET', `${base}/${sourceId}`);
|
||
expect(sourceAfter.version).toBe(1);
|
||
expect(sourceAfter.latest_published_version).toBeNull();
|
||
});
|
||
|
||
test('story315_at02_ru_en_states_and_exact_version_distinction', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const name = uniqueName('story315_locale');
|
||
const payload = promptPayload(name, 'story315 locale fixture');
|
||
const promptId = await seedPrompt(page, base, payload);
|
||
|
||
const labels = {};
|
||
for (const locale of ['en', 'ru']) {
|
||
await page.evaluate((language) => window.setLang(language), locale);
|
||
await openPrompts(page);
|
||
await selectPrompt(page, name);
|
||
|
||
await expect(page.locator(IMPORT), 'the import section must be localized').toBeVisible();
|
||
const exportLabel = (await page.locator(EXPORT).innerText()).trim();
|
||
const importLabel = (await page.locator(IMPORT).innerText()).trim();
|
||
labels[locale] = { exportLabel, importLabel };
|
||
|
||
expect(exportLabel, `${locale}: export action must be labelled`).toMatch(EXPORT_LABEL);
|
||
expect(importLabel, `${locale}: import section must be labelled`).toMatch(IMPORT_LABEL);
|
||
if (locale === 'ru') {
|
||
expect(exportLabel).toMatch(RU_EXPORT);
|
||
expect(importLabel).toMatch(RU_IMPORT);
|
||
await expect(page.locator(STATE_LABEL)).toHaveText(DRAFT_STATUS);
|
||
} else {
|
||
expect(exportLabel).not.toMatch(RU_EXPORT);
|
||
expect(importLabel).not.toMatch(RU_IMPORT);
|
||
await expect(page.locator(STATE_LABEL)).toHaveText(/draft/i);
|
||
}
|
||
await expect(page.locator(STATE_DETAIL)).not.toBeEmpty();
|
||
// Черновик без публикаций не показывает блок точной версии.
|
||
await expect(page.locator(PUBLISHED)).toHaveCount(0);
|
||
}
|
||
expect(
|
||
labels.en.exportLabel,
|
||
'RU and EN labels must be different translations, not one hardcoded string',
|
||
).not.toBe(labels.ru.exportLabel);
|
||
|
||
// Точная Published Version отображается как отдельный снимок, отличимый от Draft.
|
||
await publishPrompt(page, base, promptId);
|
||
await page.evaluate(() => window.setLang('en'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, name);
|
||
await expect(page.locator(STATE_LABEL)).toHaveText(PUBLISHED_STATUS);
|
||
await page.locator('#prompt-view-published').click();
|
||
await expect(page.locator(PUBLISHED)).toBeVisible();
|
||
await expect(page.locator(PUBLISHED_VERSION)).toHaveText('v1');
|
||
await expect(page.locator(PUBLISHED_EXPORT)).toBeVisible();
|
||
});
|
||
|
||
test('story315_at02_import_validation_errors_are_safe_and_inert', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const name = uniqueName('story315_invalid');
|
||
const payload = promptPayload(name, 'story315 invalid fixture');
|
||
const promptId = await seedPrompt(page, base, payload);
|
||
|
||
await page.evaluate(() => window.setLang('ru'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, name);
|
||
await expect(page.locator(IMPORT)).toBeVisible();
|
||
|
||
const countDrafts = async () => (await listPrompts(page, base)).items.length;
|
||
const before = await countDrafts();
|
||
|
||
// Malformed JSON — validation state до подтверждения, ничего не отправлено.
|
||
await setImportFile(page, '{');
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_ERROR), 'malformed envelope must be reported safely').toBeVisible();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0);
|
||
const malformedText = await page.locator(IMPORT_ERROR).innerText();
|
||
expect(malformedText).not.toMatch(/\/home\/|\.tmp\/|storage|postgres:\/\//);
|
||
expect(await countDrafts(), 'malformed import must not create a Prompt').toBe(before);
|
||
|
||
// Структурно некорректные, но валидные JSON: неизвестный ключ, чужая версия формата
|
||
// и внедрённая идентичность. Ошибка до подтверждения, POST не отправлен.
|
||
const importPosts = countImportPosts(page);
|
||
const baseEnvelope = portableEnvelope(payload);
|
||
const structuralDefects = [
|
||
{
|
||
label: 'unsupported format version',
|
||
envelope: { ...baseEnvelope, version: 2 },
|
||
},
|
||
{
|
||
label: 'unknown key',
|
||
envelope: { ...baseEnvelope, prompt: { ...baseEnvelope.prompt, storage_path: '/home/leak' } },
|
||
},
|
||
{
|
||
label: 'injected prompt identity',
|
||
envelope: {
|
||
...baseEnvelope,
|
||
prompt: { ...baseEnvelope.prompt, prompt_id: 'prm_foreign' },
|
||
},
|
||
},
|
||
];
|
||
for (const defect of structuralDefects) {
|
||
await setImportFile(page, defect.envelope);
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(
|
||
page.locator(IMPORT_ERROR),
|
||
`${defect.label} must be rejected before confirmation`,
|
||
).toBeVisible();
|
||
await expect(
|
||
page.locator(IMPORT_CONFIRM),
|
||
`${defect.label} must never reach the confirmation step`,
|
||
).toHaveCount(0);
|
||
await expect(page.locator(IMPORT_PREVIEW)).toHaveCount(0);
|
||
}
|
||
expect(importPosts.count, 'structurally invalid envelopes must not be POSTed').toBe(0);
|
||
expect(await countDrafts(), 'structurally invalid imports must not create a Prompt').toBe(
|
||
before,
|
||
);
|
||
|
||
// Server rejection (definition/placeholder) после подтверждения: безопасный текст,
|
||
// без definition-содержимого, без создания Prompt.
|
||
const invalidDefinition = portableEnvelope({
|
||
...promptPayload(uniqueName('story315_bad_definition')),
|
||
messages: [{ role: 'user', content: '{{undeclared_argument}}' }],
|
||
});
|
||
await setImportFile(page, invalidDefinition);
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toBeVisible();
|
||
await page.locator(IMPORT_CONFIRM_ACCEPT).click();
|
||
await expect(page.locator(IMPORT_ERROR), 'a server definition failure must be visible').toBeVisible();
|
||
const definitionError = await page.locator(IMPORT_ERROR).innerText();
|
||
expect(definitionError).not.toMatch(/\/home\/|\.tmp\/|storage|postgres:\/\//);
|
||
expect(await countDrafts(), 'a rejected import must not create a Prompt').toBe(before);
|
||
|
||
// Отмена подтверждения ничего не создаёт.
|
||
const cancelled = portableEnvelope({
|
||
...promptPayload(uniqueName('story315_cancel_target')),
|
||
});
|
||
await setImportFile(page, cancelled);
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toBeVisible();
|
||
await page.locator(IMPORT_CANCEL).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0);
|
||
expect(await countDrafts(), 'a cancelled import must not create a Prompt').toBe(before);
|
||
|
||
// Inert preview: HTML из перенесённого шаблона показывается как текст и не исполняется.
|
||
const injected = uniqueName('story315_inert');
|
||
const inertEnvelope = portableEnvelope({
|
||
...promptPayload(injected),
|
||
messages: [
|
||
{
|
||
role: 'user',
|
||
content: '</pre><img src=x onerror="window.__prompt315_injected=1">Count {{count}}.',
|
||
},
|
||
],
|
||
});
|
||
await setImportFile(page, inertEnvelope);
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_PREVIEW)).toBeVisible();
|
||
await expect(page.locator(IMPORT_PREVIEW)).toContainText('onerror=');
|
||
expect(
|
||
await page.evaluate(() => window.__prompt315_injected),
|
||
'an imported definition must be previewed as inert text, never executed as HTML',
|
||
).toBeUndefined();
|
||
expect(
|
||
await page.evaluate(() => document.querySelectorAll('img[src="x"]').length),
|
||
'an imported definition must not inject markup into the page',
|
||
).toBe(0);
|
||
});
|
||
|
||
test('story315_at02_keyboard_only_import_path', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const seedName = uniqueName('story315_keyboard_seed');
|
||
await seedPrompt(page, base, promptPayload(seedName, 'story315 keyboard seed'));
|
||
|
||
await page.evaluate(() => window.setLang('en'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, seedName);
|
||
|
||
const targetName = uniqueName('story315_keyboard_target');
|
||
await expect(
|
||
page.locator(IMPORT_FILE),
|
||
'the import file control must exist before the keyboard-only path',
|
||
).toBeVisible();
|
||
await setImportFile(page, portableEnvelope(promptPayload(targetName)));
|
||
await page.locator(IMPORT_FILE).focus();
|
||
await focusByTab(page, IMPORT_SUBMIT);
|
||
await page.keyboard.press('Enter');
|
||
await expect(page.locator(IMPORT_CONFIRM), 'Enter must activate the import preview').toBeVisible();
|
||
await focusByTab(page, IMPORT_CONFIRM_ACCEPT);
|
||
await page.keyboard.press('Enter');
|
||
await expect(page.locator(IMPORT_STATUS)).toHaveText(IMPORTED_NOTICE);
|
||
|
||
const listed = await listPrompts(page, base);
|
||
expect(
|
||
listed.items.some((item) => item.name === targetName),
|
||
'the keyboard-only path must create the Draft',
|
||
).toBe(true);
|
||
});
|
||
|
||
test('story315_at03_stale_selection_never_applies_portability_response', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const firstName = uniqueName('story315_stale_a');
|
||
const secondName = uniqueName('story315_stale_b');
|
||
const firstId = await seedPrompt(page, base, promptPayload(firstName, 'story315 stale a'));
|
||
const secondId = await seedPrompt(page, base, promptPayload(secondName, 'story315 stale b'));
|
||
|
||
// Network barrier: задержка реального ответа, не подмена контракта.
|
||
let releaseResponse;
|
||
const responseDelivered = new Promise((resolve) => {
|
||
releaseResponse = resolve;
|
||
});
|
||
await page.route('**/prompts/*/export*', async (route) => {
|
||
await new Promise((resolve) => setTimeout(resolve, 1_500));
|
||
await route.continue().catch(() => {});
|
||
releaseResponse();
|
||
});
|
||
let downloads = 0;
|
||
page.on('download', () => {
|
||
downloads += 1;
|
||
});
|
||
|
||
await openPrompts(page);
|
||
await selectPrompt(page, firstName);
|
||
await expect(
|
||
page.locator(EXPORT),
|
||
'the portability export action must exist before the stale-response case',
|
||
).toBeVisible();
|
||
await page.locator(EXPORT).click();
|
||
// Пользователь меняет выбор до прихода ответа прежнего Prompt.
|
||
await page.locator(`${LIST_ITEM}[data-prompt-id="${secondId}"]`).click();
|
||
await expect(page.locator(STATE_LABEL)).toContainText(DRAFT_STATUS);
|
||
|
||
// Барьер — фактическая обработка позднего ответа (stale-alert), а не фиксированный sleep.
|
||
await expect(
|
||
page.locator(STALE_ALERT),
|
||
'a stale-response state must be visible to the user',
|
||
).toBeVisible();
|
||
await responseDelivered;
|
||
await page.waitForTimeout(200);
|
||
|
||
expect(downloads, 'a stale export response must not start a download').toBe(0);
|
||
const secondDraft = await browserJson(page, 'GET', `${base}/${secondId}`);
|
||
expect(secondDraft.name).toBe(secondName);
|
||
expect(secondDraft.updated_at).toBeTruthy();
|
||
expect(firstId).not.toBe(secondId);
|
||
});
|
||
|
||
test('story315_at03_late_import_is_not_attributed_to_another_prompt', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const firstName = uniqueName('story315_import_stale_a');
|
||
const firstId = await seedPrompt(
|
||
page,
|
||
base,
|
||
promptPayload(firstName, 'story315 import stale a'),
|
||
);
|
||
const secondName = uniqueName('story315_import_stale_b');
|
||
const secondId = await seedPrompt(page, base, promptPayload(secondName, 'story315 import stale b'));
|
||
|
||
await openPrompts(page);
|
||
await selectPrompt(page, firstName);
|
||
await expect(
|
||
page.locator(IMPORT),
|
||
'the import section must exist before the late-response case',
|
||
).toBeVisible();
|
||
|
||
await page.route('**/prompts/import', async (route) => {
|
||
if (route.request().method() === 'POST') {
|
||
await new Promise((resolve) => setTimeout(resolve, 1_500));
|
||
}
|
||
await route.continue().catch(() => {});
|
||
});
|
||
const staleName = uniqueName('story315_import_stale_target');
|
||
const before = (await listPrompts(page, base)).items.length;
|
||
await setImportFile(page, portableEnvelope(promptPayload(staleName)));
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toBeVisible();
|
||
const idleImportLabel = (await page.locator(IMPORT_SUBMIT).innerText()).trim();
|
||
await page.locator(IMPORT_CONFIRM_ACCEPT).click();
|
||
// Пока POST в полёте, кнопка disabled, aria-busy и с локализованной pending-подписью.
|
||
await expect(
|
||
page.locator(IMPORT_SUBMIT),
|
||
'the submit action must be disabled while the import is in flight',
|
||
).toBeDisabled();
|
||
await expect(page.locator(IMPORT_SUBMIT)).toHaveAttribute('aria-busy', 'true');
|
||
const pendingLabel = (await page.locator(IMPORT_SUBMIT).innerText()).trim();
|
||
expect(
|
||
pendingLabel,
|
||
'the pending state must be localized and distinct from the idle label',
|
||
).not.toBe(idleImportLabel);
|
||
expect(pendingLabel).toMatch(IMPORT_LABEL);
|
||
|
||
await page.locator(`${LIST_ITEM}[data-prompt-id="${secondId}"]`).click();
|
||
await expect(
|
||
page.locator(STALE_ALERT),
|
||
'a late import response must be reported as stale, not attributed to another Prompt',
|
||
).toBeVisible();
|
||
await expect(page.locator(IMPORT_SUBMIT)).toBeEnabled();
|
||
await expect(page.locator(IMPORT_SUBMIT)).toHaveAttribute('aria-busy', 'false');
|
||
await expect(page.locator(IMPORT_SUBMIT)).toHaveText(idleImportLabel);
|
||
await expect(
|
||
page.locator(IMPORT_STATUS),
|
||
'the success notice must not be attributed to the new selection',
|
||
).not.toHaveText(IMPORTED_NOTICE);
|
||
await expect(page.locator(STATE_LABEL)).toContainText(DRAFT_STATUS);
|
||
|
||
// Серверная правда: задержанный импорт создал ровно один новый Draft.
|
||
const listed = await listPrompts(page, base);
|
||
expect(listed.items.length, 'the delayed import still creates exactly one Draft').toBe(
|
||
before + 1,
|
||
);
|
||
expect(
|
||
listed.items.some((item) => item.name === staleName),
|
||
'the imported Draft must exist in the target workspace',
|
||
).toBe(true);
|
||
expect(firstId).not.toBe(secondId);
|
||
});
|
||
|
||
/// N1 (QA finding, t_c1f9df6a): отменённый импорт не должен восстанавливаться сменой
|
||
/// языка — иначе подтверждение старого файла возвращается и создаёт лишний черновик.
|
||
test('story315_n1_cancelled_import_is_not_restored_by_language_switch', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const seedName = uniqueName('story315_cancel_lang_seed');
|
||
await seedPrompt(page, base, promptPayload(seedName, 'story315 cancel language seed'));
|
||
|
||
await page.evaluate(() => window.setLang('en'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, seedName);
|
||
|
||
const targetName = uniqueName('story315_cancel_lang_target');
|
||
const before = (await listPrompts(page, base)).items.length;
|
||
await setImportFile(page, portableEnvelope(promptPayload(targetName)));
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toBeVisible();
|
||
await page.locator(IMPORT_CANCEL).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0);
|
||
|
||
for (const locale of ['ru', 'en', 'ru']) {
|
||
await page.evaluate((language) => window.setLang(language), locale);
|
||
await expect(
|
||
page.locator(IMPORT_CONFIRM),
|
||
`a cancelled import must stay cancelled after switching to ${locale}`,
|
||
).toHaveCount(0);
|
||
}
|
||
// Явный повторный preview того же файла по-прежнему возможен: сброс состояния
|
||
// не запрещает независимый повторный импорт.
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toContainText(targetName);
|
||
await page.locator(IMPORT_CANCEL).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0);
|
||
expect(
|
||
(await listPrompts(page, base)).items.length,
|
||
'a cancelled import must never create a Prompt, including after a language switch',
|
||
).toBe(before);
|
||
});
|
||
|
||
/// N1: успешный импорт одноразовый — RU/EN не возвращает ни подтверждение, ни
|
||
/// устаревший предпросмотр и не создаёт дополнительный черновик.
|
||
test('story315_n1_completed_import_is_not_reoffered_by_language_switch', async ({ page }) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const seedName = uniqueName('story315_done_lang_seed');
|
||
await seedPrompt(page, base, promptPayload(seedName, 'story315 done language seed'));
|
||
|
||
await page.evaluate(() => window.setLang('en'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, seedName);
|
||
|
||
const targetName = uniqueName('story315_done_lang_target');
|
||
const before = (await listPrompts(page, base)).items.length;
|
||
await setImportFile(page, portableEnvelope(promptPayload(targetName)));
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toBeVisible();
|
||
await page.locator(IMPORT_CONFIRM_ACCEPT).click();
|
||
await expect(page.locator(IMPORT_STATUS)).toHaveText(IMPORTED_NOTICE);
|
||
const afterImport = (await listPrompts(page, base)).items.length;
|
||
expect(afterImport, 'the accepted import creates exactly one Draft').toBe(before + 1);
|
||
|
||
for (const locale of ['ru', 'en']) {
|
||
await page.evaluate((language) => window.setLang(language), locale);
|
||
await expect(
|
||
page.locator(IMPORT_CONFIRM),
|
||
`a completed import must not be offered again after switching to ${locale}`,
|
||
).toHaveCount(0);
|
||
await expect(
|
||
page.locator(IMPORT_PREVIEW),
|
||
`a completed import must not keep a stale preview after switching to ${locale}`,
|
||
).toHaveCount(0);
|
||
}
|
||
expect(
|
||
(await listPrompts(page, base)).items.length,
|
||
'a language switch after a completed import must not create an extra Draft',
|
||
).toBe(afterImport);
|
||
});
|
||
|
||
/// N1: смена языка во время POST импорта не должна возвращать активное повторное
|
||
/// подтверждение того же файла.
|
||
test('story315_n1_pending_import_confirmation_is_not_restored_by_language_switch', async ({
|
||
page,
|
||
}) => {
|
||
await login(page);
|
||
const { base } = await pageContext(page);
|
||
const seedName = uniqueName('story315_inflight_lang_seed');
|
||
await seedPrompt(page, base, promptPayload(seedName, 'story315 in-flight language seed'));
|
||
|
||
await page.evaluate(() => window.setLang('en'));
|
||
await openPrompts(page);
|
||
await selectPrompt(page, seedName);
|
||
|
||
await page.route('**/prompts/import', async (route) => {
|
||
if (route.request().method() === 'POST') {
|
||
await new Promise((resolve) => setTimeout(resolve, 1_500));
|
||
}
|
||
await route.continue().catch(() => {});
|
||
});
|
||
|
||
const targetName = uniqueName('story315_inflight_lang_target');
|
||
const before = (await listPrompts(page, base)).items.length;
|
||
await setImportFile(page, portableEnvelope(promptPayload(targetName)));
|
||
await page.locator(IMPORT_SUBMIT).click();
|
||
await expect(page.locator(IMPORT_CONFIRM)).toBeVisible();
|
||
await page.locator(IMPORT_CONFIRM_ACCEPT).click();
|
||
await expect(page.locator(IMPORT_SUBMIT)).toBeDisabled();
|
||
|
||
await page.evaluate(() => window.setLang('ru'));
|
||
await expect(
|
||
page.locator(IMPORT_CONFIRM),
|
||
'a language switch during the pending import must not restore the confirmation',
|
||
).toHaveCount(0);
|
||
|
||
await expect(page.locator(IMPORT_STATUS)).toHaveText(IMPORTED_NOTICE);
|
||
await expect(page.locator(IMPORT_CONFIRM)).toHaveCount(0);
|
||
expect(
|
||
(await listPrompts(page, base)).items.length,
|
||
'one confirmation accepts exactly one import',
|
||
).toBe(before + 1);
|
||
});
|
||
});
|