Files
crank/apps/ui/tests/e2e/resources-story310.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

802 lines
40 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 (RED) Story 3.10 / FR-16 — UI определения и публикации REST-backed Resource
// template: выбор опубликованной операции, параметры, findings, подтверждение
// публикации, stale-response и RU/EN.
//
// Источник: `_bmad-output/initiative-crank/epic-mcp-capabilities/spec-resource-templates/spec.md`
// §6 (UI contract) + §5 (AC5). Состояние на момент написания: страница
// `/resources` умеет static create/preview/publish (Story 3.6–3.9), но панели
// источника нет. Каждый RED доходит до конкретного отсутствующего действия и
// падает на реальном отсутствии UI; static control — существующий принятый контракт.
//
// Запуск: npm --prefix apps/ui run e2e -- tests/e2e/resources-story310.spec.js --workers=1 --retries=0
const { test, expect } = require('@playwright/test');
const {
browserJson,
createPublishedOperation,
createResourceDraft,
createTemplateDraft,
getCurrentWorkspace,
localized,
login,
uniqueName,
} = require('./helpers');
const SOURCE_MODE = '[data-testid="resource-source-mode"]';
const SOURCE_PANEL = '[data-testid="resource-source-panel"]';
const SOURCE_LOADING = '[data-testid="resource-source-loading"]';
const SOURCE_EMPTY = '[data-testid="resource-source-empty"]';
const SOURCE_OPERATION = '[data-testid="resource-source-operation"]';
const SOURCE_VERSION = '[data-testid="resource-source-version"]';
const SOURCE_URI_TEMPLATE = '[data-testid="resource-source-uri-template"]';
const SOURCE_BIND = '[data-testid="resource-source-bind"]';
const SOURCE_STATUS = '[data-testid="resource-source-status"]';
const SOURCE_PREVIEW = '[data-testid="resource-source-preview"]';
const SOURCE_FACTS = '[data-testid="resource-source-facts"]';
const SOURCE_PINNED = '[data-testid="resource-source-pinned"]';
const SOURCE_SAFETY = '[data-testid="resource-source-safety"]';
const SOURCE_SENSITIVITY = '[data-testid="resource-source-sensitivity"]';
const SOURCE_ACCESS = '[data-testid="resource-source-access"]';
const SOURCE_FINDINGS = '[data-testid="resource-source-findings"]';
const SOURCE_CONFIRM_FACTS = '[data-testid="resource-source-confirm-facts"]';
const PARAM_ROW = '[data-testid="resource-param-row"]';
const PARAM_NAME = '[data-testid="resource-param-name"]';
const PARAM_TYPE = '[data-testid="resource-param-type"]';
const PARAM_INPUT_PATH = '[data-testid="resource-param-input-path"]';
const PUBLISH_CONFIRM = '[data-testid="resource-publish-confirm"]';
const PUBLISH_ACCEPT = '[data-testid="resource-publish-confirm-accept"]';
const PUBLISH_CANCEL = '[data-testid="resource-publish-cancel"]';
const PUBLISH = '[data-testid="resource-publish"]';
const STATUS = '[data-testid="resource-status"]';
const PUBLISHED = '[data-testid="resource-published"]';
const PUBLISHED_VERSION = '[data-testid="resource-published-version"]';
const META_NAME = '[data-testid="resource-meta-name"]';
const LIST_ITEM = '[data-testid="resource-list-item"]';
const DRAFT_STATUS = /draft|черновик/i;
const PUBLISHED_STATUS = /published|опубликован/i;
const READ_SAFE = /read-safe|read safe|безопасн|только чтение/i;
function readOperationPayload(name, override = {}) {
return {
name,
display_name: name,
category: 'sales',
protocol: 'rest',
security_level: 'standard',
target: {
kind: 'rest',
base_url: 'http://127.0.0.1:9',
method: override.method || 'GET',
path_template: '/orders/{order_id}',
},
input_schema: override.input_schema || {
type: 'object',
required: true,
fields: { order_id: { type: 'string', required: true, format: 'uuid' } },
},
output_schema: { type: 'object', required: true, fields: { id: { type: 'string', required: true } } },
input_mapping: {
rules: [{ source: '$.mcp.order_id', target: '$.request.path.order_id', required: true }],
},
output_mapping: {
rules: [{ source: '$.response.body.id', target: '$.output.id', required: true }],
},
execution_config: override.execution_config || { timeout_ms: 1000, safety: { class: 'read' } },
tool_description: { title: name, description: 'Story 3.10 UI fixture' },
};
}
function templateMetadata(name, operationId, override = {}) {
return {
uri: `crank://e2e/${name}`,
name,
description: 'story310 ui template',
kind: 'text',
mime_type: 'text/plain',
sensitivity: override.sensitivity || 'internal',
source: {
operation_id: operationId,
operation_version: 1,
uri_template: override.uri_template || 'crank://orders/{order_id}',
parameters: override.parameters || [
{
name: 'order_id',
input_path: override.input_path || 'input.order_id',
schema: { type: 'string', required: true, format: 'uuid' },
},
],
cache: { ttl_ms: 60000, vary: ['order_id'], max_bytes: 65536 },
failure: { outcome: 'error' },
},
};
}
async function seedPublishedOperation(page, workspaceId, prefix, override = {}) {
const name = uniqueName(prefix);
const result = await createPublishedOperation(page, workspaceId, readOperationPayload(name, override));
expect(
result.status,
`published operation fixture must be created through the accepted contract: ${result.text}`,
).toBe(200);
return { name, operationId: result.operation_id };
}
async function seedTemplateDraft(page, workspaceId, prefix, operationId, override = {}) {
const name = uniqueName(prefix);
const metadata = templateMetadata(name, operationId, override);
const created = await createTemplateDraft(page, workspaceId, metadata);
expect(
created.status,
`template Draft fixture must be created: ${created.text}`,
).toBe(201);
return {
name,
resourceId: created.json.resource.resource_id,
findings: created.json.findings || [],
};
}
async function openResource(page, resourceId) {
await page.goto(`/resources?resource_id=${encodeURIComponent(resourceId)}`);
await expect(page.locator(META_NAME)).not.toBeEmpty();
}
async function selectRestMode(page) {
await expect(
page.locator(SOURCE_MODE),
'the create form must offer a REST-backed source mode',
).toBeVisible();
await page.locator(SOURCE_MODE).selectOption('rest');
}
test('story310_ui_static_control_creates_a_static_draft', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id, 'an E2E workspace must be available').toBeTruthy();
await page.goto('/resources');
const name = uniqueName('story310_static_control');
await page.locator('#resource-form-uri').fill(`crank://e2e/${name}`);
await page.locator('#resource-form-name').fill(name);
await page.locator('#resource-form-kind').selectOption('text');
await page.locator('#resource-form-mime-type').fill('text/plain');
await page.locator('#resource-form-content').fill('story310 static control body\n');
await page.locator('#resource-form-submit').click();
await expect
.poll(
async () => {
const listed = await browserJson(page, 'GET', `/api/admin/workspaces/${workspace.id}/resources`);
return listed.items.some((item) => item.resource.uri === `crank://e2e/${name}`);
},
{ message: 'the existing static create contract must still work', timeout: 10000 },
)
.toBe(true);
const listed = await browserJson(page, 'GET', `/api/admin/workspaces/${workspace.id}/resources`);
const created = listed.items.find((item) => item.resource.uri === `crank://e2e/${name}`);
expect(created.resource.status).toBe('draft');
await page.goto('/resources');
await expect(page.locator(LIST_ITEM).filter({ hasText: name })).toBeVisible();
});
test('story310_ui_source_picker_loading_empty_and_published_selection', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const published = await seedPublishedOperation(page, workspace.id, 'story310_picker_read');
const draftOnlyName = uniqueName('story310_picker_draft');
await browserJson(
page,
'POST',
`/api/admin/workspaces/${workspace.id}/operations`,
readOperationPayload(draftOnlyName),
[201, 200],
);
// Empty state: workspace без опубликованных операций (управляемый ответ сервера).
const operationsPredicate = (url) => url.pathname.endsWith('/operations');
await page.route(
operationsPredicate,
async (route) => {
await new Promise((resolve) => setTimeout(resolve, 300));
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
});
},
);
await page.goto('/resources');
await selectRestMode(page);
await expect(page.locator(SOURCE_LOADING), 'the picker must show a loading state').toBeVisible();
await expect(page.locator(SOURCE_EMPTY), 'an empty source list must be explained').toBeVisible();
// Тот же predicate/handler: новый predicate оставил бы старый handler активным.
await page.unroute(operationsPredicate);
// Published selection: Draft-only операции недоступны.
await page.goto('/resources');
await selectRestMode(page);
await expect(page.locator(SOURCE_PANEL)).toBeVisible();
const options = page.locator(`${SOURCE_OPERATION} option`);
await expect(options.filter({ hasText: published.name })).toHaveCount(1);
await expect(options.filter({ hasText: draftOnlyName })).toHaveCount(0);
await page.locator(SOURCE_OPERATION).selectOption({ label: published.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{order_id}');
await page.locator(SOURCE_BIND).click();
await expect(page.locator(SOURCE_STATUS)).toContainText(published.operationId);
await expect(page.locator(SOURCE_STATUS)).toContainText('1');
await expect(page.locator(PARAM_ROW)).toHaveCount(1);
await expect(page.locator(PARAM_NAME)).toHaveText('order_id');
await expect(page.locator(PARAM_TYPE)).toHaveText(/string/i);
await expect(page.locator(PARAM_INPUT_PATH)).toHaveValue('input.order_id');
});
test('story310_ui_source_validation_blocks_publish_and_shows_mapping_errors', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const read = await seedPublishedOperation(page, workspace.id, 'story310_valid_read');
const accepted = await seedTemplateDraft(page, workspace.id, 'story310_ui_valid', read.operationId);
await openResource(page, accepted.resourceId);
await expect(page.locator(SOURCE_FACTS), 'the selected template must show its pinned source').toBeVisible();
await expect(page.locator(SOURCE_PINNED)).toContainText(read.operationId);
await expect(page.locator(SOURCE_SAFETY)).toHaveText(/GET/i);
await expect(page.locator(SOURCE_SAFETY)).toHaveText(READ_SAFE);
await expect(page.locator(SOURCE_SENSITIVITY)).toHaveText(/internal|внутрен/i);
await expect(page.locator(SOURCE_ACCESS)).toContainText(/standard|стандарт/i);
await expect
.poll(async () => (await page.locator(SOURCE_FINDINGS).innerText()).trim())
.not.toMatch(/resource_source_/);
await expect(page.locator(PUBLISH)).toBeEnabled();
// Server-authoritative blocker: параметр, которого нет в URI-шаблоне.
const blocked = await seedTemplateDraft(page, workspace.id, 'story310_ui_blocked', read.operationId, {
uri_template: 'crank://orders/{order_id}',
parameters: [
{ name: 'order_id', input_path: 'input.order_id', schema: { type: 'string', required: true, format: 'uuid' } },
{ name: 'tenant_id', input_path: 'input.order_id', schema: { type: 'string', required: true } },
],
});
await openResource(page, blocked.resourceId);
await expect(page.locator(SOURCE_FINDINGS)).toBeVisible();
await expect(page.locator(PUBLISH), 'a blocked template must not be publishable').toBeDisabled();
// Ошибка строки параметра видна для параметра, которого нет в шаблоне.
await expect(
page
.locator(PARAM_ROW)
.filter({ hasText: 'tenant_id' })
.locator('[data-testid="resource-param-error"]'),
).toBeVisible();
});
test('story310_ui_publish_confirmation_pins_exact_facts_and_cancel_is_inert', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const read = await seedPublishedOperation(page, workspace.id, 'story310_confirm_read');
// Полный пользовательский путь: выбрать опубликованную операцию, привязать
// версию, проверить/создать черновик, затем публикация с подтверждением.
await page.goto('/resources');
await selectRestMode(page);
const name = uniqueName('story310_ui_confirm');
await page.locator('#resource-form-uri').fill(`crank://e2e/${name}`);
await page.locator('#resource-form-name').fill(name);
await page.locator('#resource-form-mime-type').fill('text/plain');
await page.locator(SOURCE_OPERATION).selectOption({ label: read.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{order_id}');
await page.locator(SOURCE_BIND).click();
// Ждём реальный ответ create, а не гонку «сразу после click».
const createResponse = page.waitForResponse(
(response) =>
response.request().method() === 'POST' &&
/\/resources$/.test(new URL(response.url()).pathname),
);
await page.locator(SOURCE_PREVIEW).click();
const createdResponse = await createResponse;
expect(createdResponse.status(), 'the source panel must create the template Draft').toBe(201);
const createdBody = await createdResponse.json();
const resourceId = createdBody.resource.resource_id;
await openResource(page, resourceId);
await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS);
await expect(page.locator(SOURCE_PINNED)).toContainText(read.operationId);
const publishRequests = { count: 0 };
page.on('request', (request) => {
if (request.method() === 'POST' && /\/resources\/[^/]+\/publish$/.test(request.url())) {
publishRequests.count += 1;
}
});
await page.locator(PUBLISH).click();
await expect(page.locator(PUBLISH_CONFIRM)).toBeVisible();
const facts = page.locator(SOURCE_CONFIRM_FACTS);
await expect(facts).toBeVisible();
await expect(facts).toContainText(read.operationId);
await expect(facts).toContainText('1');
await expect(facts).toContainText(/GET/i);
await expect(facts).toContainText(/internal|внутрен/i);
await expect(facts).toContainText(/standard|стандарт/i);
await page.locator(PUBLISH_CANCEL).click();
await expect(page.locator(PUBLISH_CONFIRM)).toHaveCount(0);
expect(publishRequests.count, 'cancel must not publish anything').toBe(0);
await expect(page.locator(STATUS)).toHaveText(DRAFT_STATUS);
await expect(page.locator(PUBLISHED)).toHaveCount(0);
await page.locator(PUBLISH).click();
await page.locator(PUBLISH_ACCEPT).click();
await expect(page.locator(PUBLISHED)).toBeVisible();
await expect(page.locator(PUBLISHED_VERSION)).toHaveText('1');
await expect(page.locator(STATUS)).toHaveText(PUBLISHED_STATUS);
expect(publishRequests.count, 'accept must publish exactly once').toBe(1);
});
test('story310_ui_stale_preview_does_not_override_new_selection', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const first = await seedPublishedOperation(page, workspace.id, 'story310_stale_first');
const second = await seedPublishedOperation(page, workspace.id, 'story310_stale_second');
const firstDraft = await seedTemplateDraft(page, workspace.id, 'story310_ui_stale_a', first.operationId);
const secondDraft = await seedTemplateDraft(page, workspace.id, 'story310_ui_stale_b', second.operationId);
await page.route(
(url) => url.pathname.endsWith(`/resources/${firstDraft.resourceId}/preview`),
async (route) => {
await new Promise((resolve) => setTimeout(resolve, 1500));
await route.continue();
},
);
// Поздний ответ первого выбора действительно отправлен и доставлен — иначе
// stale-oracle был бы пустым.
const firstRequestSent = page.waitForRequest((request) =>
request.url().endsWith(`/resources/${firstDraft.resourceId}/preview`),
);
const firstResponseDelivered = page.waitForResponse(
(response) =>
response.url().endsWith(`/resources/${firstDraft.resourceId}/preview`) &&
response.status() === 200,
);
await openResource(page, firstDraft.resourceId);
await firstRequestSent;
await expect(page.locator(LIST_ITEM).filter({ hasText: secondDraft.name })).toBeVisible();
await page.locator(LIST_ITEM).filter({ hasText: secondDraft.name }).click();
await expect(page.locator(META_NAME)).toHaveText(secondDraft.name);
await expect(page.locator(SOURCE_PINNED)).toContainText(second.operationId);
// Ответ прежнего выбора доставлен уже после нового выбора и не перекрашивает его.
const delivered = await firstResponseDelivered;
expect(delivered.status()).toBe(200);
await page.waitForTimeout(300);
await expect(page.locator(META_NAME)).toHaveText(secondDraft.name);
await expect(page.locator(SOURCE_PINNED)).toContainText(second.operationId);
await expect(page.locator(SOURCE_PINNED)).not.toContainText(first.operationId);
});
test('story310_ui_source_picker_error_is_visible_localized_and_recoverable', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const published = await seedPublishedOperation(page, workspace.id, 'story310_error_read');
const publishCalls = { count: 0 };
page.on('request', (request) => {
if (request.method() === 'POST' && /\/resources\/[^/]+\/publish$/.test(request.url())) {
publishCalls.count += 1;
}
});
const operationsPredicate = (url) => url.pathname.endsWith('/operations');
await page.route(operationsPredicate, (route) =>
route.fulfill({
status: 503,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'upstream_unavailable', message: 'picker unavailable' } }),
}),
);
const statuses = {};
for (const locale of ['en', 'ru']) {
await page.evaluate((language) => localStorage.setItem('crank_lang', language), locale);
await page.goto('/resources');
await selectRestMode(page);
await expect(page.locator(SOURCE_STATUS), `${locale}: the picker error must be visible`).not.toBeEmpty();
await expect(page.locator(SOURCE_EMPTY), `${locale}: an error is not an empty list`).toBeHidden();
statuses[locale] = (await page.locator(SOURCE_STATUS).innerText()).trim();
expect(statuses[locale], `${locale}: a localized message, not a raw key`).not.toMatch(/resources\.source\./);
expect(statuses[locale].length).toBeGreaterThan(0);
}
expect(statuses.en, 'RU and EN status messages must differ').not.toBe(statuses.ru);
expect(publishCalls.count, 'a failed picker must never publish').toBe(0);
// Успешный ответ восстанавливает picker (тот же predicate снят точно).
await page.unroute(operationsPredicate);
await page.goto('/resources');
await selectRestMode(page);
await expect(
page.locator(`${SOURCE_OPERATION} option`).filter({ hasText: published.name }),
).toHaveCount(1);
await expect(page.locator(SOURCE_STATUS)).toBeEmpty();
expect(publishCalls.count, 'browsing the picker must never publish').toBe(0);
});
test('story310_ui_source_block_is_localized_ru_en', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const read = await seedPublishedOperation(page, workspace.id, 'story310_locale_read');
const draft = await seedTemplateDraft(page, workspace.id, 'story310_ui_locale', read.operationId, {
parameters: [
{ name: 'order_id', input_path: 'input.missing_field', schema: { type: 'string', required: true, format: 'uuid' } },
],
});
const labels = {};
for (const locale of ['en', 'ru']) {
await page.evaluate((language) => localStorage.setItem('crank_lang', language), locale);
await openResource(page, draft.resourceId);
await expect(page.locator(SOURCE_FACTS)).toBeVisible();
labels[locale] = {
safety: (await page.locator(SOURCE_SAFETY).innerText()).trim(),
findings: (await page.locator(SOURCE_FINDINGS).innerText()).trim(),
};
expect(labels[locale].safety, `${locale}: safety label must resolve`).not.toMatch(/resources\.source\./);
expect(labels[locale].findings, `${locale}: findings must resolve`).not.toMatch(/resources\.source\./);
expect(labels[locale].findings, `${locale}: raw finding codes stay out of prose`).not.toMatch(
/resource_source_/,
);
}
expect(
labels.en.findings,
'RU and EN findings must be different translations, not one hardcoded string',
).not.toBe(labels.ru.findings);
expect(labels.en.safety).not.toBe(labels.ru.safety);
// Static block keeps its existing labels in both locales.
await expect(page.locator('[data-testid="resource-import"]')).toBeVisible();
});
test('story310_ui_mapping_replaces_stale_schema_with_pinned_field_facts', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operation = await seedPublishedOperation(page, workspace.id, 'story310_mapping_schema', {
input_schema: { type: 'object', required: true, fields: {
order_id: { type: 'string', required: true, format: 'uuid' },
count: { type: 'integer', required: true },
} },
});
const draft = await seedTemplateDraft(page, workspace.id, 'story310_mapping_schema_draft', operation.operationId);
const pinned = page.waitForResponse((response) =>
response.url().includes(`/operations/${operation.operationId}/versions/1`));
await openResource(page, draft.resourceId);
await pinned;
await page.locator(`#resource-draft-params ${PARAM_INPUT_PATH}`).fill('input.count');
await expect(page.locator(`#resource-draft-params ${PARAM_TYPE}`)).toHaveText('integer');
const put = page.waitForResponse((response) => response.request().method() === 'PUT' && response.url().includes(`/resources/${draft.resourceId}`));
await page.locator('#resource-edit-submit').click();
const saved = await put;
expect(saved.status()).toBe(200);
await expect(page.locator(PARAM_INPUT_PATH)).toHaveValue('input.count');
await expect(page.locator(PUBLISH)).toBeEnabled();
});
test('story310_ui_pinned_schemas_remain_isolated_between_open_draft_and_create_form', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operationA = await seedPublishedOperation(page, workspace.id, 'story310_isolation_a', {
input_schema: { type: 'object', required: true, fields: { count: { type: 'string', required: true } } },
});
const operationB = await seedPublishedOperation(page, workspace.id, 'story310_isolation_b', {
input_schema: { type: 'object', required: true, fields: { count: { type: 'integer', required: true } } },
});
const draft = await seedTemplateDraft(page, workspace.id, 'story310_isolation_draft', operationA.operationId, {
parameters: [{ name: 'order_id', input_path: 'input.count', schema: { type: 'string', required: true } }],
});
const pinnedA = page.waitForResponse((response) =>
response.url().includes(`/operations/${operationA.operationId}/versions/1`));
await openResource(page, draft.resourceId);
await pinnedA;
await selectRestMode(page);
await expect(page.locator(`#resource-draft-params ${PARAM_TYPE}`)).toHaveText('string');
await page.locator(SOURCE_OPERATION).selectOption({ label: operationB.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{count}');
await page.locator(SOURCE_BIND).click();
await expect(page.locator(`#resource-source-params ${PARAM_TYPE}`)).toHaveText('integer');
await page.locator('#resource-source-params ' + PARAM_INPUT_PATH).fill('input.count');
const put = page.waitForResponse((response) =>
response.request().method() === 'PUT' && response.url().includes(`/resources/${draft.resourceId}`));
await page.locator('#resource-edit-submit').click();
const saved = await put;
expect(saved.status()).toBe(200);
await expect(page.locator(`#resource-draft-params ${PARAM_TYPE}`)).toHaveText('string');
});
test('story310_ui_create_mapping_uses_the_pinned_input_schema_after_reload_and_publishes', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operation = await seedPublishedOperation(page, workspace.id, 'story310_create_mapping', {
input_schema: { type: 'object', required: true, fields: { count: { type: 'integer', required: true } } },
});
await page.goto('/resources');
await selectRestMode(page);
const name = uniqueName('story310_create_mapping_draft');
await page.locator('#resource-form-uri').fill(`crank://e2e/${name}`);
await page.locator('#resource-form-name').fill(name);
await page.locator('#resource-form-mime-type').fill('text/plain');
await page.locator(SOURCE_OPERATION).selectOption({ label: operation.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{item_id}');
await page.locator(SOURCE_BIND).click();
await expect(page.locator(PARAM_INPUT_PATH)).toHaveValue('input.item_id');
await page.locator(PARAM_INPUT_PATH).fill('input.count');
await expect(page.locator(PARAM_TYPE)).toHaveText('integer');
const createResponsePromise = page.waitForResponse((response) =>
response.request().method() === 'POST' && /\/resources$/.test(new URL(response.url()).pathname));
await page.locator(SOURCE_PREVIEW).click();
const createdResponse = await createResponsePromise;
expect(createdResponse.status()).toBe(201);
const created = await createdResponse.json();
const resourceId = created.resource.resource_id;
await openResource(page, resourceId);
await expect(page.locator(PARAM_TYPE)).toHaveText('integer');
await expect(page.locator(PUBLISH)).toBeEnabled();
const publishResponsePromise = page.waitForResponse((response) =>
response.request().method() === 'POST' && response.url().endsWith(`/resources/${resourceId}/publish`));
await page.locator(PUBLISH).click();
await page.locator(PUBLISH_ACCEPT).click();
expect((await publishResponsePromise).status()).toBe(200);
});
test('story310_ui_mapping_input_keeps_focus_during_keyboard_typing_in_create_and_draft', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operation = await seedPublishedOperation(page, workspace.id, 'story310_keyboard_mapping', {
input_schema: { type: 'object', required: true, fields: { count: { type: 'integer', required: true } } },
});
await page.goto('/resources');
await selectRestMode(page);
const name = uniqueName('story310_keyboard_create');
await page.locator('#resource-form-uri').fill(`crank://e2e/${name}`);
await page.locator('#resource-form-name').fill(name);
await page.locator('#resource-form-mime-type').fill('text/plain');
await page.locator(SOURCE_OPERATION).selectOption({ label: operation.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{item_id}');
await page.locator(SOURCE_BIND).click();
const createPath = page.locator(`#resource-source-params ${PARAM_INPUT_PATH}`);
await expect(createPath).toHaveValue('input.item_id');
await createPath.click();
await page.keyboard.press('Control+A');
await createPath.pressSequentially('input.count');
await expect(createPath).toHaveValue('input.count');
await expect(createPath).toBeFocused();
expect(await createPath.evaluate((input) => input.selectionStart)).toBe('input.count'.length);
const createResponse = page.waitForResponse((response) =>
response.request().method() === 'POST' && new URL(response.url()).pathname.endsWith('/resources'));
await page.locator(SOURCE_PREVIEW).click();
const created = await createResponse;
expect(created.status()).toBe(201);
const resourceId = (await created.json()).resource.resource_id;
await openResource(page, resourceId);
await expect(page.locator(PARAM_INPUT_PATH)).toHaveValue('input.count');
await expect(page.locator(PUBLISH)).toBeEnabled();
const publishResponse = page.waitForResponse((response) =>
response.request().method() === 'POST' && response.url().endsWith(`/resources/${resourceId}/publish`));
await page.locator(PUBLISH).click();
await page.locator(PUBLISH_ACCEPT).click();
expect((await publishResponse).status()).toBe(200);
const draft = await seedTemplateDraft(page, workspace.id, 'story310_keyboard_draft', operation.operationId);
await openResource(page, draft.resourceId);
const draftPath = page.locator(`#resource-draft-params ${PARAM_INPUT_PATH}`);
await draftPath.click();
await page.keyboard.press('Control+A');
await draftPath.pressSequentially('input.count');
await expect(draftPath).toHaveValue('input.count');
await expect(draftPath).toBeFocused();
expect(await draftPath.evaluate((input) => input.selectionStart)).toBe('input.count'.length);
const put = page.waitForResponse((response) =>
response.request().method() === 'PUT' && response.url().endsWith(`/resources/${draft.resourceId}`));
await page.locator('#resource-edit-submit').click();
expect((await put).status()).toBe(200);
await page.reload();
await expect(page.locator(`#resource-draft-params ${PARAM_INPUT_PATH}`)).toHaveValue('input.count');
});
test('story310_ui_binary_template_saves_without_file_but_static_binary_still_requires_replacement', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operation = await seedPublishedOperation(page, workspace.id, 'story310_binary_read');
const name = uniqueName('story310_binary_template');
const metadata = templateMetadata(name, operation.operationId);
metadata.uri = `crank://e2e/${name}`;
metadata.kind = 'binary';
metadata.mime_type = 'application/octet-stream';
const created = await createTemplateDraft(page, workspace.id, metadata);
expect(created.status).toBe(201);
const templateId = created.json.resource.resource_id;
await openResource(page, templateId);
await page.locator('#resource-edit-description').fill('metadata-only update');
const templatePut = page.waitForResponse((response) =>
response.request().method() === 'PUT' && response.url().endsWith(`/resources/${templateId}`));
await page.locator('#resource-edit-submit').click();
expect((await templatePut).status()).toBe(200);
const staticName = uniqueName('story310_binary_static');
const staticDraft = await createResourceDraft(page, workspace.id, {
uri: `crank://e2e/${staticName}`, name: staticName, description: 'static binary', kind: 'binary',
mime_type: 'application/octet-stream', sensitivity: 'internal',
}, Buffer.from([1, 2, 3]), 'static.bin', 'application/octet-stream');
expect(staticDraft.status).toBe(201);
await openResource(page, staticDraft.json.resource.resource_id);
await page.locator('#resource-edit-description').fill('must upload replacement');
await page.locator('#resource-edit-submit').click();
await expect(page.locator('#resource-edit-status')).toContainText(/file|файл/i);
});
test('story310_ui_late_success_keeps_newer_binding_and_uri_change_invalidates_pending_pin', async ({ page }) => {
await login(page);
const first = { operationId: 'late-success-a', name: 'late-success-a' };
const second = { operationId: 'late-success-b', name: 'late-success-b' };
await page.route((url) => url.pathname.endsWith('/operations'), (route) => route.fulfill({
status: 200, contentType: 'application/json',
body: JSON.stringify({ items: [first, second].map((item) => ({ id: item.operationId, name: item.name, latest_published_version: 1 })) }),
}));
await page.route((url) => url.pathname.endsWith(`/operations/${second.operationId}/versions/1`), (route) => route.fulfill({
status: 200, contentType: 'application/json',
body: JSON.stringify({ snapshot: { input_schema: { fields: { order_id: { type: 'integer', required: true } } } } }),
}));
await page.goto('/resources');
await selectRestMode(page);
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{order_id}');
await page.locator(SOURCE_OPERATION).selectOption({ label: first.name });
await page.locator(SOURCE_VERSION).selectOption('1');
let releaseFirst;
let finishFirst;
const firstGate = new Promise((resolve) => { releaseFirst = resolve; });
const firstDone = new Promise((resolve) => { finishFirst = resolve; });
let startedFirst;
const firstStarted = new Promise((resolve) => { startedFirst = resolve; });
const firstPredicate = (url) => url.pathname.endsWith(`/operations/${first.operationId}/versions/1`);
await page.route(firstPredicate, async (route) => {
startedFirst();
await firstGate;
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ snapshot: { input_schema: { fields: { order_id: { type: 'string', required: true } } } } }) });
finishFirst();
});
await page.locator(SOURCE_BIND).click();
await firstStarted;
await page.locator(SOURCE_OPERATION).selectOption({ label: second.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_BIND).click();
await expect(page.locator(SOURCE_STATUS)).toContainText(second.operationId);
releaseFirst();
await firstDone;
await expect(page.locator(SOURCE_STATUS)).toContainText(second.operationId);
let captured;
await page.route((url) => url.pathname.endsWith('/resources'), async (route) => {
captured = route.request().postData();
await route.fulfill({ status: 400, contentType: 'application/json', body: JSON.stringify({ error: { code: 'test_capture' } }) });
});
await page.locator('#resource-form-uri').fill(`crank://e2e/${uniqueName('late_success')}`);
await page.locator('#resource-form-name').fill(uniqueName('late_success_name'));
await page.locator(SOURCE_PREVIEW).click();
await expect.poll(() => captured).toContain(second.operationId);
await page.unroute(firstPredicate);
await page.locator(SOURCE_OPERATION).selectOption({ label: first.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{order_id}');
let releaseUri;
let finishUri;
const uriGate = new Promise((resolve) => { releaseUri = resolve; });
const uriDone = new Promise((resolve) => { finishUri = resolve; });
const uriPredicate = (url) => url.pathname.endsWith(`/operations/${first.operationId}/versions/1`);
await page.route(uriPredicate, async (route) => {
await uriGate;
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ snapshot: { input_schema: { fields: { order_id: { type: 'string', required: true } } } } }) });
finishUri();
});
await page.locator(SOURCE_BIND).click();
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{different}');
releaseUri();
await uriDone;
captured = null;
await page.locator(SOURCE_PREVIEW).click();
await expect(page.locator(SOURCE_STATUS)).not.toBeEmpty();
expect(captured, 'a pin for an old URI must not be created').toBeNull();
await page.unroute(uriPredicate);
await page.locator(SOURCE_OPERATION).selectOption({ label: first.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{order_id}');
let releaseMode;
let finishMode;
let startMode;
const modeGate = new Promise((resolve) => { releaseMode = resolve; });
const modeDone = new Promise((resolve) => { finishMode = resolve; });
const modeStarted = new Promise((resolve) => { startMode = resolve; });
await page.route(uriPredicate, async (route) => {
startMode();
await modeGate;
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ snapshot: { input_schema: { fields: { order_id: { type: 'string', required: true } } } } }) });
finishMode();
});
await page.locator(SOURCE_BIND).click();
await modeStarted;
await page.locator(SOURCE_MODE).selectOption('static');
releaseMode();
await modeDone;
let createCount = 0;
page.on('request', (request) => {
if (request.method() === 'POST' && /\/resources$/.test(new URL(request.url()).pathname)) createCount += 1;
});
await selectRestMode(page);
await expect(page.locator(`${SOURCE_OPERATION} option`).filter({ hasText: first.name })).toHaveCount(1);
await page.locator(SOURCE_PREVIEW).click();
await expect(page.locator(SOURCE_STATUS)).not.toBeEmpty();
expect(createCount, 'switching modes must discard an in-flight pin').toBe(0);
});
test('story310_ui_late_bind_error_does_not_clear_newer_binding', async ({ page }) => {
await login(page);
const first = { operationId: 'late-error-a', name: 'late-error-a' };
const second = { operationId: 'late-error-b', name: 'late-error-b' };
await page.route((url) => url.pathname.endsWith('/operations'), (route) => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ items: [first, second].map((item) => ({ id: item.operationId, name: item.name, latest_published_version: 1 })) }),
}));
await page.route((url) => url.pathname.endsWith(`/operations/${second.operationId}/versions/1`), (route) => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ snapshot: { input_schema: { fields: { order_id: { type: 'string', required: true } } } } }),
}));
await page.goto('/resources');
await selectRestMode(page);
await page.locator(SOURCE_URI_TEMPLATE).fill('crank://orders/{order_id}');
await expect(page.locator(`${SOURCE_OPERATION} option`).filter({ hasText: first.name })).toHaveCount(1);
await page.locator(SOURCE_OPERATION).selectOption({ label: first.name });
await page.locator(SOURCE_VERSION).selectOption('1');
let releaseFirst;
let signalFinished;
const delayed = new Promise((resolve) => { releaseFirst = resolve; });
const finished = new Promise((resolve) => { signalFinished = resolve; });
let signalStarted;
const started = new Promise((resolve) => { signalStarted = resolve; });
await page.route((url) => url.pathname.endsWith(`/operations/${first.operationId}/versions/1`), async (route) => {
signalStarted();
await delayed;
await route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({ error: { code: 'unavailable' } }) });
signalFinished();
});
await page.locator(SOURCE_BIND).click();
await started;
await page.locator(SOURCE_OPERATION).selectOption({ label: second.name });
await page.locator(SOURCE_VERSION).selectOption('1');
await page.locator(SOURCE_BIND).click();
await expect(page.locator(SOURCE_STATUS)).toContainText(second.operationId);
releaseFirst();
await finished;
await expect(page.locator(SOURCE_STATUS)).toContainText(second.operationId);
await page.locator('#resource-form-uri').fill(`crank://e2e/${uniqueName('story310_late_error')}`);
await page.locator('#resource-form-name').fill(uniqueName('story310_late_error_name'));
let createPayload;
await page.route((url) => url.pathname.endsWith('/resources'), async (route) => {
createPayload = route.request().postData();
await route.fulfill({ status: 400, contentType: 'application/json', body: JSON.stringify({ error: { code: 'test_capture' } }) });
});
await page.locator(SOURCE_PREVIEW).click();
await expect.poll(() => createPayload).toContain(second.operationId);
});