feat(import): complete OpenAPI onboarding and verify delivery
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-10-09 17:50:38 +03:00
1 parent bb3e376767
commit e93de7015a
244 files changed
+57020 -5139

No files matched your search

+9
View File
@@ -64,6 +64,15 @@
.onboarding-first-call-evidence dt { color: var(--text-muted, #8b949e); }
.onboarding-first-call-evidence dd { margin: 0; font-family: var(--font-mono, monospace); overflow-wrap: anywhere; }
.onboarding-deep-link-stale { position: fixed; left: 50%; top: 76px; z-index: 810; width: min(520px, calc(100vw - 28px)); transform: translateX(-50%); padding: 14px; border: 1px solid var(--amber, #d29922); border-radius: 10px; background: var(--surface-raised, #161b22); color: var(--text-primary, #f0f6fc); box-shadow: 0 12px 36px rgba(0, 0, 0, .35); }
.onboarding-openapi-path { margin-top: 14px; padding: 12px; border: 1px dashed var(--border-color, #30363d); border-radius: 9px; }
.onboarding-openapi-hint { margin: 0 0 8px; color: var(--text-muted, #8b949e); font-size: 12px; }
.onboarding-import-report { margin-top: 12px; padding: 12px; border: 1px solid var(--border-color, #30363d); border-radius: 9px; }
.onboarding-import-report h3 { margin: 0 0 8px; font-size: 14px; }
.onboarding-import-report-list { display: grid; gap: 8px; margin: 0; padding-left: 20px; }
.onboarding-import-report-item { display: grid; gap: 4px; overflow-wrap: anywhere; font-size: 12px; }
.onboarding-import-drift, .onboarding-import-error { color: var(--amber, #d29922); font-size: 12px; }
.onboarding-import-selected { color: var(--success, #3fb950); font-size: 12px; }
.onboarding-return-context { display: none; }
.onboarding-footer { display: flex; justify-content: space-between; gap: 8px; margin-top: 12px; }
.onboarding-link-button { border: 0; background: transparent; color: var(--text-muted, #8b949e); text-decoration: underline; cursor: pointer; font: inherit; font-size: 12px; }
+358 -4
View File
@@ -160,6 +160,124 @@
margin-top: 18px;
}
.openapi-import-plan-confirmation {
display: grid;
gap: 12px;
padding: 18px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--bg-surface);
}
.openapi-import-plan-confirmation[hidden] {
display: none;
}
.openapi-import-plan-confirmation h3,
.openapi-import-plan-intro,
.openapi-import-plan-versioning,
.openapi-import-plan-summary {
margin: 0;
}
.openapi-import-plan-intro,
.openapi-import-plan-versioning {
color: var(--text-secondary);
font-size: 13px;
}
.openapi-import-plan-versioning:not([hidden]) {
padding: 12px;
border-left: 3px solid var(--accent);
border-radius: 6px;
background: var(--bg-overlay);
}
.openapi-import-plan-counts {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.openapi-import-plan-count {
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text-secondary);
font-size: 12px;
}
.openapi-import-plan-candidates,
.openapi-import-plan-outcomes {
display: grid;
gap: 8px;
}
.openapi-import-findings summary {
cursor: pointer;
color: var(--text-secondary);
font-weight: 700;
}
.openapi-import-findings-page {
display: grid;
gap: 4px;
padding-top: 6px;
}
.openapi-import-findings-pagination {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 8px;
padding-top: 6px;
color: var(--text-secondary);
}
.openapi-import-plan-candidate,
.openapi-import-plan-outcome {
display: grid;
gap: 5px;
padding: 12px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--bg-overlay);
}
.openapi-import-plan-candidate[data-state="blocked"],
.openapi-import-plan-outcome[data-outcome="rejected"] {
border-color: color-mix(in srgb, var(--red) 45%, var(--border));
}
.openapi-import-plan-candidate code,
.openapi-import-plan-outcome code {
color: var(--text-muted);
font-size: 12px;
overflow-wrap: anywhere;
}
.openapi-import-plan-candidate p,
.openapi-import-plan-outcome p {
margin: 0;
color: var(--text-secondary);
font-size: 13px;
}
.openapi-import-plan-reason {
color: var(--text-muted) !important;
}
.openapi-import-plan-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 10px;
}
.openapi-import-plan-summary {
color: var(--text-secondary);
}
.openapi-import-source,
.openapi-import-group {
border: 1px solid var(--border);
@@ -185,7 +303,6 @@
}
#openapi-import-server,
#openapi-import-conflict-mode,
#openapi-import-search,
#openapi-import-method-filter,
.openapi-import-server-custom {
@@ -238,6 +355,30 @@
gap: 14px;
}
.openapi-import-partial-toggle {
display: flex;
align-items: center;
gap: 9px;
width: fit-content;
color: var(--text-primary);
font-size: 13px;
font-weight: 700;
}
.openapi-import-pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
padding: 4px 0;
color: var(--text-secondary);
font-size: 13px;
}
.openapi-import-pagination[hidden] {
display: none;
}
.openapi-import-group-header {
display: flex;
align-items: center;
@@ -266,12 +407,109 @@
}
.openapi-import-operation {
display: grid;
gap: 10px;
padding: 14px 16px;
border-bottom: 1px solid var(--border);
}
.openapi-import-operation-selection {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 12px;
align-items: start;
padding: 14px 16px;
border-bottom: 1px solid var(--border);
cursor: pointer;
}
.openapi-import-security-status {
padding: 6px 0 6px 28px;
color: var(--text-secondary);
font-size: 13px;
font-weight: 700;
}
.openapi-import-decision-controls,
.openapi-import-security-controls {
display: flex;
flex-wrap: wrap;
gap: 10px 14px;
padding-left: 28px;
}
.openapi-import-decision-controls label,
.openapi-import-security-controls label {
display: grid;
gap: 5px;
color: var(--text-secondary);
font-size: 12px;
font-weight: 700;
}
.openapi-import-decision-controls select,
.openapi-import-decision-controls input,
.openapi-import-security-controls select,
.openapi-import-security-controls input {
min-width: 210px;
max-width: min(100%, 360px);
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--bg-surface);
color: var(--text-primary);
}
.openapi-import-security {
display: grid;
gap: 4px;
}
.openapi-import-security-op-status {
padding-left: 28px;
color: var(--text-secondary);
font-size: 12px;
font-weight: 700;
}
.openapi-import-security-op-status[data-status="blocked"] {
color: var(--red);
}
.openapi-import-security-op-status[data-status="resolved"] {
color: var(--green, var(--text-secondary));
}
.openapi-import-security-findings {
align-self: center;
color: var(--amber, var(--text-secondary));
font-size: 12px;
}
.openapi-import-security-guidance {
color: var(--text-secondary);
font-size: 12px;
font-weight: 400;
max-width: 360px;
}
.openapi-import-plan-blocked-help {
margin: 0;
color: var(--red);
font-weight: 700;
}
.openapi-import-plan-version,
.openapi-import-plan-revalidation {
color: var(--text-secondary);
font-size: 12px;
overflow-wrap: anywhere;
}
.openapi-import-plan-stale {
padding: 10px 12px;
border: 1px solid var(--red);
border-radius: 10px;
color: var(--red);
font-weight: 700;
}
.openapi-import-operation:last-child {
@@ -288,6 +526,25 @@
font-size: 12px;
}
.openapi-import-source-location {
color: var(--text-muted);
font-size: 11px;
overflow-wrap: anywhere;
}
.openapi-import-conflict {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px;
color: var(--amber);
font-size: 12px;
}
.openapi-import-conflict-proposal {
color: var(--text-primary);
}
.openapi-import-method {
padding: 4px 8px;
border-radius: 999px;
@@ -297,6 +554,26 @@
font-weight: 800;
}
.openapi-import-operation-readiness {
justify-self: start;
padding: 4px 8px;
border-radius: 999px;
background: var(--surface-muted, #21262d);
color: var(--text-secondary);
font-size: 11px;
font-weight: 800;
}
.openapi-import-operation-readiness-actionable {
background: var(--green-glow, rgba(63, 185, 80, 0.16));
color: var(--green);
}
.openapi-import-operation-readiness-blocked {
background: var(--red-glow, rgba(248, 81, 73, 0.16));
color: var(--red);
}
.openapi-import-findings {
grid-column: 2 / -1;
display: grid;
@@ -304,6 +581,10 @@
font-size: 12px;
}
.openapi-import-operation .openapi-import-findings {
grid-column: auto;
}
.openapi-import-finding {
display: inline-flex;
align-items: baseline;
@@ -461,6 +742,17 @@
font-size: 13px;
}
.openapi-import-result-skipped-page {
margin-top: 6px;
}
.openapi-import-result-skipped-page ul {
max-height: 320px;
overflow: auto;
margin: 0;
padding-left: 22px;
}
.openapi-import-created-list {
display: grid;
gap: 6px;
@@ -475,6 +767,68 @@
text-decoration: none;
}
.openapi-import-blockers-summary {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 12px;
padding: 10px 12px;
border: 1px solid var(--danger, #f85149);
border-radius: 8px;
color: var(--danger, #f85149);
font-size: 12px;
}
.openapi-import-blockers-summary[hidden] {
display: none;
}
.openapi-import-blockers-count {
font-weight: 700;
}
.openapi-import-blocker-code {
padding: 2px 6px;
border-radius: 5px;
background: rgba(248, 81, 73, .12);
font-family: var(--font-mono, monospace);
}
.onboarding-import-draft-choice {
margin-top: 14px;
padding: 12px;
border: 1px solid var(--accent, #58a6ff);
border-radius: 9px;
}
.onboarding-import-draft-choice-title {
display: block;
margin-bottom: 8px;
}
.onboarding-import-draft-choice-list {
display: grid;
gap: 8px;
}
.onboarding-import-draft-option-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 0;
border-top: 1px solid var(--border-color, #30363d);
overflow-wrap: anywhere;
}
.onboarding-import-drift {
color: var(--amber, #d29922);
}
.onboarding-import-draft-selected {
color: var(--success, #3fb950);
}
@media (max-width: 720px) {
.openapi-import-toolbar {
grid-template-columns: 1fr;
@@ -484,7 +838,7 @@
justify-content: flex-start;
}
.openapi-import-operation {
.openapi-import-operation-selection {
grid-template-columns: auto 1fr;
}
+13 -1
View File
@@ -178,7 +178,19 @@
</div><!-- /step-sidebar -->
<!-- ── Main step panel ── -->
<div class="wizard-main"><div id="step-panel-container"><!-- steps loaded dynamically --></div></div>
<div class="wizard-main">
<div id="wizard-live-status" class="info-callout" role="status" aria-live="polite" aria-atomic="true" hidden style="margin-bottom: 20px;">
<svg class="info-callout-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="8" cy="8" r="7"/>
<path d="M8 11V8M8 5v-.5"/>
</svg>
<div class="info-callout-body">
<div class="info-callout-title" id="wizard-live-status-title" data-i18n="wizard.step5.draft_actions">Результат действия</div>
<div class="info-callout-text" id="wizard-live-status-text"></div>
</div>
</div>
<div id="step-panel-container"><!-- steps loaded dynamically --></div>
</div>
</div><!-- /wizard-body -->
<!-- ══ BOTTOM ACTION BAR ══ -->
-11
View File
@@ -131,17 +131,6 @@ tls:
<div class="section-divider-line"></div>
</div>
<div id="wizard-live-status" class="info-callout" role="status" aria-live="polite" aria-atomic="true" hidden style="margin-bottom: 20px;">
<svg class="info-callout-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="8" cy="8" r="7"/>
<path d="M8 11V8M8 5v-.5"/>
</svg>
<div class="info-callout-body">
<div class="info-callout-title" id="wizard-live-status-title" data-i18n="wizard.step5.draft_actions">Результат действия</div>
<div class="info-callout-text" id="wizard-live-status-text"></div>
</div>
</div>
<div id="wizard-mapping-warnings" class="mapping-warnings" hidden data-testid="wizard-mapping-warnings"></div>
<div class="config-card" id="agent-facing-preview-card" style="margin-bottom: 20px;">
+32 -9
View File
@@ -417,13 +417,6 @@
<select id="openapi-import-server"></select>
<input id="openapi-import-server-custom" class="openapi-import-server-custom" type="url" data-i18n-aria-label="openapi.server.custom_aria" aria-label="Свой Base URL" data-i18n-ph="openapi.server.placeholder" placeholder="Или укажите свой base URL, например https://api.example.com">
</div>
<div class="openapi-import-server-row">
<label for="openapi-import-conflict-mode" data-i18n="openapi.conflict.label">Если операция уже существует</label>
<select id="openapi-import-conflict-mode">
<option value="rename" selected data-i18n="openapi.conflict.rename">Создать копию с новым именем</option>
<option value="skip" data-i18n="openapi.conflict.skip">Пропустить</option>
</select>
</div>
<div class="openapi-import-toolbar">
<div class="openapi-import-filter">
<label for="openapi-import-search" data-i18n="openapi.search.label">Поиск методов</label>
@@ -440,13 +433,43 @@
<button class="btn-secondary" id="openapi-import-clear-visible" type="button" data-i18n="openapi.clear_visible">Снять видимые</button>
</div>
</div>
<label class="openapi-import-partial-toggle">
<input id="openapi-import-partial-mode" type="checkbox">
<span data-i18n="openapi.partial_mode">Enable partial import</span>
</label>
<div class="openapi-import-groups" id="openapi-import-groups"></div>
<nav class="openapi-import-pagination" id="openapi-import-pagination" data-testid="openapi-import-pagination" data-i18n-aria-label="openapi.pagination.label" aria-label="Pagination" hidden>
<button class="btn-secondary" id="openapi-import-page-previous" type="button" data-i18n="openapi.pagination.previous">Previous</button>
<span id="openapi-import-page-status" data-testid="openapi-import-page-status" role="status" aria-live="polite" aria-atomic="true"></span>
<button class="btn-secondary" id="openapi-import-page-next" type="button" data-i18n="openapi.pagination.next">Next</button>
</nav>
<div class="openapi-import-footer">
<span id="openapi-import-selection" data-i18n="openapi.selection.empty">Выбрано: 0</span>
<button class="btn-primary" id="openapi-import-create" type="button" data-i18n="openapi.create">Создать черновики</button>
<button class="btn-primary" id="openapi-import-create" type="button" data-i18n="openapi.plan.create">Просмотреть план импорта</button>
</div>
<div class="openapi-import-result" id="openapi-import-result" hidden></div>
<section class="openapi-import-plan-confirmation" id="openapi-import-plan-confirmation" data-testid="openapi-import-apply-confirmation" aria-labelledby="openapi-import-plan-title" hidden>
<h3 id="openapi-import-plan-title" data-i18n="openapi.plan.confirm_title">Подтвердите план импорта</h3>
<p class="openapi-import-plan-intro" data-i18n="openapi.plan.confirm_intro">Перед применением проверьте точный план сервера.</p>
<p class="openapi-import-plan-version" id="openapi-import-plan-version" data-testid="openapi-import-plan-version"></p>
<p class="openapi-import-plan-revalidation" id="openapi-import-plan-revalidation-status" data-testid="openapi-import-plan-revalidation-status" role="status" aria-live="polite" aria-atomic="true"></p>
<p class="openapi-import-plan-stale" id="openapi-import-plan-stale" data-testid="openapi-import-plan-stale" hidden></p>
<p class="openapi-import-plan-blocked-help" id="openapi-import-plan-blocked-help" data-i18n="openapi.plan.blocked_help" hidden>Исправьте решения для заблокированных операций и создайте план заново.</p>
<div class="openapi-import-plan-counts" id="openapi-import-plan-counts" data-testid="openapi-import-apply-counts"></div>
<nav class="openapi-import-pagination" id="openapi-import-plan-pagination" data-testid="openapi-import-plan-pagination" data-i18n-aria-label="openapi.pagination.plan_label" aria-label="Plan candidates" hidden>
<button class="btn-secondary" id="openapi-import-plan-page-previous" type="button" data-i18n="openapi.pagination.previous">Previous</button>
<span id="openapi-import-plan-page-status" data-testid="openapi-import-plan-page-status" role="status" aria-live="polite" aria-atomic="true"></span>
<button class="btn-secondary" id="openapi-import-plan-page-next" type="button" data-i18n="openapi.pagination.next">Next</button>
</nav>
<div class="openapi-import-plan-candidates" id="openapi-import-plan-candidates"></div>
<p class="openapi-import-plan-versioning" id="openapi-import-versioning-consequences" data-testid="openapi-import-versioning-consequences" hidden></p>
<div class="openapi-import-plan-actions">
<button class="btn-secondary" id="openapi-import-plan-reopen" type="button" data-testid="openapi-import-plan-reopen" data-i18n="openapi.plan.reopen">Reopen and check current plan</button>
<button class="btn-secondary" id="openapi-import-plan-back" type="button" data-i18n="openapi.plan.back">Назад к выбору</button>
<button class="btn-primary" id="openapi-import-plan-apply" type="button" data-testid="openapi-import-plan-apply" data-i18n="openapi.plan.apply">Применить импорт</button>
</div>
</section>
</div>
<div class="openapi-import-result" id="openapi-import-result" data-testid="openapi-import-apply-result" hidden></div>
</div>
</section>
</div>
+35
View File
@@ -328,6 +328,12 @@
expected_revision: expectedRevision,
});
},
registerOnboardingImportContext: function(workspaceId, payload) {
return post('/workspaces/' + encodeURIComponent(workspaceId) + '/onboarding/import-context', payload);
},
selectOnboardingImportDraft: function(workspaceId, payload) {
return post('/workspaces/' + encodeURIComponent(workspaceId) + '/onboarding/select-draft', payload);
},
updateWorkspace: function(workspaceId, payload) {
return patch('/workspaces/' + encodeURIComponent(workspaceId), payload);
},
@@ -436,6 +442,35 @@
signal: options && options.signal,
});
},
createOpenApiImportPlan: function(workspaceId, jobId, payload, options) {
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/' + encodeURIComponent(jobId) + '/plans', {
method: 'POST',
headers: headers({
'Content-Type': 'application/json',
'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en',
}),
body: JSON.stringify(payload),
signal: options && options.signal,
});
},
revalidateOpenApiImportPlan: function(workspaceId, planReference, options) {
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/plans/' + encodeURIComponent(planReference), {
method: 'GET',
headers: headers({ 'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en' }),
signal: options && options.signal,
});
},
applyOpenApiImportPlan: function(workspaceId, planReference, payload, options) {
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/' + encodeURIComponent(planReference) + '/apply', {
method: 'POST',
headers: headers({
'Content-Type': 'application/json',
'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en',
}),
body: JSON.stringify(payload),
signal: options && options.signal,
});
},
listAgents: function(workspaceId) {
return get('/workspaces/' + encodeURIComponent(workspaceId) + '/agents');
},
+216 -3
View File
@@ -611,6 +611,27 @@ var TRANSLATIONS = {
'wizard.step2.auth_mode.none': 'No auth',
'wizard.step2.auth_mode.existing': 'Use existing authorization profile',
'wizard.step2.auth_mode.create': 'Create authorization profile now',
'openapi.error.plan_too_large': 'Select at most 512 operations and leave at most 512 excluded operations.',
'openapi.security.alternative_label': 'Security alternative',
'openapi.security.alternative_placeholder': 'Choose a security alternative',
'openapi.security.no_auth': 'No authentication',
'openapi.security.unsupported': 'unsupported',
'openapi.security.profile_label': 'Auth Profile',
'openapi.security.profile_placeholder': 'Choose an Auth Profile',
'openapi.security.status_no_auth': 'No authentication',
'openapi.security.status_required': 'Authentication required',
'openapi.security.status_unresolved': 'Unresolved',
'openapi.security.status_unverified': 'Unverified',
'openapi.security.status_resolved': 'Resolved',
'openapi.security.status_blocked': 'Blocked',
'openapi.security.empty_profiles': 'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.',
'openapi.finding.unsupported_security_scheme': 'Some security requirements could not be imported. Choose a supported alternative or remove the unsupported requirement.',
'openapi.finding.unsupported_security_and_requirement': 'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.',
'openapi.error.security_with_skip': 'A skipped operation cannot be bound to an Auth Profile or a security alternative.',
'openapi.error.auth_unavailable': 'The selected Auth Profile is unavailable or its required Secret is missing. Choose another compatible profile and create a new plan.',
'openapi.error.auth_incompatible': 'The Auth Profile scheme does not match the selected security alternative. Choose a compatible alternative or profile and create a new plan.',
'openapi.error.auth_profile_required': 'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.',
'openapi.error.security_alternative_required': 'The Auth Profile matches multiple security alternatives. Select the exact alternative and create a new plan.',
'wizard.step2.auth_profile': 'Authorization profile',
'wizard.step2.auth_profile_hint': 'The selected profile is applied automatically on every tool call.',
'wizard.step2.auth_profile_empty': 'No authorization profiles yet. Create one below.',
@@ -1658,6 +1679,27 @@ var TRANSLATIONS = {
'wizard.step2.auth_mode.none': 'Без авторизации',
'wizard.step2.auth_mode.existing': 'Использовать существующий профиль авторизации',
'wizard.step2.auth_mode.create': 'Создать профиль авторизации сейчас',
'openapi.error.plan_too_large': 'Выберите не более 512 операций и оставьте не более 512 исключённых операций.',
'openapi.security.alternative_label': 'Вариант безопасности',
'openapi.security.alternative_placeholder': 'Выберите вариант безопасности',
'openapi.security.no_auth': 'Без аутентификации',
'openapi.security.unsupported': 'не поддерживается',
'openapi.security.profile_label': 'Профиль авторизации',
'openapi.security.profile_placeholder': 'Выберите профиль авторизации',
'openapi.security.status_no_auth': 'Без аутентификации',
'openapi.security.status_required': 'Требуется аутентификация',
'openapi.security.status_unresolved': 'Не разрешено',
'openapi.security.status_unverified': 'Не проверено',
'openapi.security.status_resolved': 'Разрешено',
'openapi.security.status_blocked': 'Заблокировано',
'openapi.security.empty_profiles': 'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.',
'openapi.finding.unsupported_security_scheme': 'Некоторые security requirements нельзя импортировать. Выберите поддерживаемый вариант или уберите неподдерживаемое требование.',
'openapi.finding.unsupported_security_and_requirement': 'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.',
'openapi.error.security_with_skip': 'Пропускаемая операция не может быть связана с профилем авторизации или вариантом безопасности.',
'openapi.error.auth_unavailable': 'Выбранный профиль авторизации недоступен, либо отсутствует его обязательный Secret. Выберите другой совместимый профиль и создайте новый план.',
'openapi.error.auth_incompatible': 'Схема профиля авторизации не совпадает с выбранным вариантом безопасности. Выберите совместимый вариант или профиль и создайте новый план.',
'openapi.error.auth_profile_required': 'Для этой операции требуется профиль авторизации. Выберите совместимый профиль и создайте новый план.',
'openapi.error.security_alternative_required': 'Профиль авторизации подходит к нескольким вариантам безопасности. Выберите точный вариант и создайте новый план.',
'wizard.step2.auth_profile': 'Профиль авторизации',
'wizard.step2.auth_profile_hint': 'Выбранный профиль применяется автоматически при каждом вызове инструмента.',
'wizard.step2.auth_profile_empty': 'Профилей авторизации пока нет. Создайте профиль ниже.',
@@ -2092,12 +2134,81 @@ Object.assign(TRANSLATIONS.en, {
'openapi.method.all': 'All methods',
'openapi.select_visible': 'Select visible',
'openapi.clear_visible': 'Clear visible',
'openapi.partial_mode': 'Enable partial import',
'openapi.pagination.previous': 'Previous',
'openapi.pagination.next': 'Next',
'openapi.pagination.label': 'Preview pages',
'openapi.pagination.plan_label': 'Import plan candidates',
'openapi.pagination.result_label': 'Import results',
'openapi.findings.summary': 'Findings: {count}',
'openapi.pagination.status': 'Page {page} of {pages} · {total} matching operations',
'openapi.create': 'Create drafts',
'openapi.plan.create': 'Review import plan',
'openapi.plan.confirm_title': 'Confirm import plan',
'openapi.plan.confirm_intro': 'Review the exact server plan before applying it.',
'openapi.plan.reopen': 'Reopen and check current plan',
'openapi.plan.version': 'Review {version} · reference {reference} · digest {digest}',
'openapi.plan.revalidation_pending': 'Checking this saved plan…',
'openapi.plan.revalidation_current': 'The saved plan is current.',
'openapi.plan.revalidation_stale': 'The saved plan is stale.',
'openapi.plan.revalidation_error': 'The saved plan could not be verified.',
'openapi.plan.revalidation_guidance': 'Return to the preview and create a new plan before applying.',
'openapi.plan.back': 'Back to selection',
'openapi.plan.back_fix': 'Back to fix decisions',
'openapi.plan.apply': 'Apply import',
'openapi.plan.blocked_help': 'Fix the decisions for blocked operations, then create a new plan.',
'openapi.plan.exact_target': 'Exact operation',
'openapi.plan.confirmed_name': 'Confirmed name',
'openapi.decision.action_label': 'Import decision',
'openapi.decision.create': 'Create',
'openapi.decision.skip': 'Skip existing operation',
'openapi.decision.rename': 'Create with a confirmed name',
'openapi.decision.new_version': 'Create a new Draft Version',
'openapi.decision.target_label': 'Existing operation',
'openapi.decision.target_placeholder': 'Choose the exact operation',
'openapi.decision.confirmed_name_label': 'Confirmed name',
'openapi.decision.confirmed_name_placeholder': 'Enter the exact new name',
'openapi.plan.selected': 'Selected: {count}',
'openapi.plan.excluded': 'Excluded: {count}',
'openapi.plan.actionable': 'Actionable: {count}',
'openapi.plan.blocked': 'Blocked: {count}',
'openapi.plan.versioning_new': 'Creates a new Draft Version. The Published Version and history remain unchanged.',
'openapi.plan.action.create': 'Create a new Draft',
'openapi.plan.action.new_version': 'Create a new Draft Version',
'openapi.plan.action.rename': 'Create a separate Draft with the confirmed name',
'openapi.plan.action.skip': 'Keep the existing operation unchanged',
'openapi.plan.action.excluded': 'Excluded from this partial import',
'openapi.plan.action.blocked': 'Blocked and will not be applied',
'openapi.plan.result_title': 'Import plan result',
'openapi.plan.outcome.created': 'Created',
'openapi.plan.outcome.versioned': 'New Draft Version',
'openapi.plan.outcome.renamed': 'Created with confirmed name',
'openapi.plan.outcome.skipped': 'Skipped',
'openapi.plan.outcome.excluded': 'Excluded',
'openapi.plan.outcome.rejected': 'Rejected',
'openapi.plan.summary': 'Applied: {applied}; skipped: {skipped}; excluded: {excluded}; rejected: {rejected}.',
'openapi.plan.repreview': 'This plan is stale or could not be verified. Create a fresh preview and review a new plan.',
'openapi.plan.resolve_conflict': 'Review the conflict decision and create a new plan before applying again.',
'openapi.plan.retry_unknown': 'The Apply result is unknown. Retry sends the same plan reference, digest and idempotency key.',
'openapi.status.planning': 'Preparing the import plan…',
'openapi.status.plan_ready': 'Review the server plan and confirm to apply it.',
'openapi.status.applying': 'Applying the import plan…',
'openapi.status.applied': 'Import plan applied.',
'openapi.error.plan': 'The import plan could not be created.',
'openapi.error.apply': 'The import plan could not be applied.',
'openapi.error.operations_unavailable': 'The workspace operations could not be loaded. Retry the preview before creating a plan.',
'openapi.error.decision_target': 'Choose an exact existing operation for this decision.',
'openapi.error.confirmed_name': 'Enter the exact confirmed name for the rename decision.',
'openapi.error.decision_action': 'Choose a valid import decision.',
'openapi.status.loading_operations': 'Checking existing workspace operations…',
'openapi.selection.empty': 'Selected: 0',
'openapi.selection': 'Selected: {selected} of {total}, shown: {visible}',
'openapi.group.selection': 'selected {selected} of {total}, shown {visible}',
'openapi.group.select': 'Select group',
'openapi.group.select': 'Select group on this page',
'openapi.operation.fields': 'inputs: {input} · outputs: {output}',
'openapi.operation.readiness_actionable': 'Actionable',
'openapi.operation.readiness_blocked': 'Blocked',
'openapi.operation.readiness_unresolved': 'Authentication required',
'openapi.mapping.path': 'Path',
'openapi.mapping.query': 'Query',
'openapi.mapping.header': 'Header',
@@ -2106,6 +2217,8 @@ Object.assign(TRANSLATIONS.en, {
'openapi.source.summary': '{name} · {size} · methods: {count}',
'openapi.status.file_ready': 'File is ready for preview.',
'openapi.status.previewing': 'Uploading and parsing the document…',
'openapi.status.uploading': 'Uploading the document…',
'openapi.status.parsing': 'Parsing the OpenAPI document…',
'openapi.status.preview_ready': 'Document is ready. Select methods to import.',
'openapi.status.creating': 'Creating drafts…',
'openapi.status.created': 'Created: {created}; skipped: {skipped}.',
@@ -2150,6 +2263,21 @@ Object.assign(TRANSLATIONS.en, {
'openapi.result.fix': 'Fix in wizard',
'openapi.result.open': 'Open in wizard',
'openapi.result.skipped': 'Skipped',
'openapi.result.skipped_count': 'Skipped: {count} candidates',
'openapi.blockers.summary': 'Blocked operations: {count}',
'onboarding.openapi_path': 'Start from an OpenAPI document',
'onboarding.openapi_hint': 'Use the canonical OpenAPI import: preview, review the exact plan, then apply it atomically.',
'onboarding.import.choose_draft': 'Choose one Draft to continue with test and publish',
'onboarding.import.report_title': 'OpenAPI import report and Draft choices',
'onboarding.import.continue': 'Continue with this Draft',
'onboarding.import.selected': 'Selected for onboarding',
'onboarding.import.drift': 'The selected Draft changed or is unavailable. Review the report and choose an available Draft again.',
'onboarding.import.registration_pending': 'Import report is being registered. Refresh onboarding before selecting.',
'onboarding.import.registration_failed': 'The import was applied, but its onboarding context could not be confirmed. Refresh to recover the report before continuing.',
'onboarding.import.selection_failed': 'This Draft could not be selected. Refresh the report and review the current Draft choices.',
'onboarding.import.conflict_reload': 'The onboarding state changed. The latest report has been loaded; review it before trying again.',
'onboarding.import.retry_registration': 'Retry report recovery',
'onboarding.import.view_report': 'View the full import report',
});
@@ -2208,12 +2336,81 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.method.all': 'Все методы',
'openapi.select_visible': 'Выбрать видимые',
'openapi.clear_visible': 'Снять видимые',
'openapi.partial_mode': 'Включить частичный импорт',
'openapi.pagination.previous': 'Назад',
'openapi.pagination.next': 'Далее',
'openapi.pagination.label': 'Страницы предпросмотра',
'openapi.pagination.plan_label': 'Кандидаты плана импорта',
'openapi.pagination.result_label': 'Результаты импорта',
'openapi.findings.summary': 'Замечаний: {count}',
'openapi.pagination.status': 'Страница {page} из {pages} · операций по фильтру: {total}',
'openapi.create': 'Создать черновики',
'openapi.plan.create': 'Проверить план импорта',
'openapi.plan.confirm_title': 'Подтвердите план импорта',
'openapi.plan.confirm_intro': 'Перед применением проверьте точный план сервера.',
'openapi.plan.reopen': 'Повторно открыть и проверить план',
'openapi.plan.version': 'Проверка {version} · ссылка {reference} · digest {digest}',
'openapi.plan.revalidation_pending': 'Проверяем сохранённый план…',
'openapi.plan.revalidation_current': 'Сохранённый план актуален.',
'openapi.plan.revalidation_stale': 'Сохранённый план устарел.',
'openapi.plan.revalidation_error': 'Не удалось проверить сохранённый план.',
'openapi.plan.revalidation_guidance': 'Вернитесь к предпросмотру и создайте новый план перед применением.',
'openapi.plan.back': 'Назад к выбору',
'openapi.plan.back_fix': 'Назад к исправлению решений',
'openapi.plan.apply': 'Применить импорт',
'openapi.plan.blocked_help': 'Исправьте решения для заблокированных операций и создайте новый план.',
'openapi.plan.exact_target': 'Точная операция',
'openapi.plan.confirmed_name': 'Подтверждённое имя',
'openapi.decision.action_label': 'Решение для импорта',
'openapi.decision.create': 'Создать',
'openapi.decision.skip': 'Пропустить существующую операцию',
'openapi.decision.rename': 'Создать с подтверждённым именем',
'openapi.decision.new_version': 'Создать новую версию черновика',
'openapi.decision.target_label': 'Существующая операция',
'openapi.decision.target_placeholder': 'Выберите точную операцию',
'openapi.decision.confirmed_name_label': 'Подтверждённое имя',
'openapi.decision.confirmed_name_placeholder': 'Введите точное новое имя',
'openapi.plan.selected': 'Выбрано: {count}',
'openapi.plan.excluded': 'Исключено: {count}',
'openapi.plan.actionable': 'Можно применить: {count}',
'openapi.plan.blocked': 'Заблокировано: {count}',
'openapi.plan.versioning_new': 'Будет создана новая версия черновика. Опубликованная версия и история останутся без изменений.',
'openapi.plan.action.create': 'Создать черновик',
'openapi.plan.action.new_version': 'Создать новую версию черновика',
'openapi.plan.action.rename': 'Создать отдельный черновик с подтверждённым именем',
'openapi.plan.action.skip': 'Оставить существующую операцию без изменений',
'openapi.plan.action.excluded': 'Исключено из частичного импорта',
'openapi.plan.action.blocked': 'Заблокировано и не будет применено',
'openapi.plan.result_title': 'Результат плана импорта',
'openapi.plan.outcome.created': 'Создано',
'openapi.plan.outcome.versioned': 'Новая версия черновика',
'openapi.plan.outcome.renamed': 'Создано с подтверждённым именем',
'openapi.plan.outcome.skipped': 'Пропущено',
'openapi.plan.outcome.excluded': 'Исключено',
'openapi.plan.outcome.rejected': 'Отклонено',
'openapi.plan.summary': 'Применено: {applied}; пропущено: {skipped}; исключено: {excluded}; отклонено: {rejected}.',
'openapi.plan.repreview': 'План устарел или не прошёл проверку. Создайте новый предпросмотр и проверьте новый план.',
'openapi.plan.resolve_conflict': 'Проверьте решение конфликта и создайте новый план перед повторным применением.',
'openapi.plan.retry_unknown': 'Результат применения неизвестен. Повтор отправит те же ссылку, digest и ключ идемпотентности.',
'openapi.status.planning': 'Подготавливаю план импорта…',
'openapi.status.plan_ready': 'Проверьте план сервера и подтвердите его применение.',
'openapi.status.applying': 'Применяю план импорта…',
'openapi.status.applied': 'План импорта применён.',
'openapi.error.plan': 'Не удалось создать план импорта.',
'openapi.error.apply': 'Не удалось применить план импорта.',
'openapi.error.operations_unavailable': 'Не удалось загрузить операции workspace. Повторите предпросмотр перед созданием плана.',
'openapi.error.decision_target': 'Выберите точную существующую операцию для этого решения.',
'openapi.error.confirmed_name': 'Введите точное подтверждённое имя для переименования.',
'openapi.error.decision_action': 'Выберите допустимое решение для импорта.',
'openapi.status.loading_operations': 'Проверяю существующие операции workspace…',
'openapi.selection.empty': 'Выбрано: 0',
'openapi.selection': 'Выбрано: {selected} из {total}, показано: {visible}',
'openapi.group.selection': 'выбрано {selected} из {total}, показано {visible}',
'openapi.group.select': 'Выбрать группу',
'openapi.group.select': 'Выбрать группу на этой странице',
'openapi.operation.fields': 'входов: {input} · выходов: {output}',
'openapi.operation.readiness_actionable': 'Можно импортировать',
'openapi.operation.readiness_blocked': 'Заблокировано',
'openapi.operation.readiness_unresolved': 'Требуется авторизация',
'openapi.mapping.path': 'Path',
'openapi.mapping.query': 'Query',
'openapi.mapping.header': 'Header',
@@ -2222,6 +2419,8 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.source.summary': '{name} · {size} · методов: {count}',
'openapi.status.file_ready': 'Файл готов к разбору.',
'openapi.status.previewing': 'Загружаю и разбираю документ…',
'openapi.status.uploading': 'Загружаю документ…',
'openapi.status.parsing': 'Разбираю документ OpenAPI…',
'openapi.status.preview_ready': 'Документ готов. Выберите методы для импорта.',
'openapi.status.creating': 'Создаю черновики…',
'openapi.status.created': 'Создано: {created}; пропущено: {skipped}.',
@@ -2266,7 +2465,21 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.result.fix': 'Исправить в мастере',
'openapi.result.open': 'Открыть в мастере',
'openapi.result.skipped': 'Пропущено',
'openapi.result.skipped_count': 'Пропущено кандидатов: {count}',
'openapi.blockers.summary': 'Заблокированные операции: {count}',
'onboarding.openapi_path': 'Начать с документа OpenAPI',
'onboarding.openapi_hint': 'Используйте канонический импорт OpenAPI: предпросмотр, проверка точного плана и атомарное применение.',
'onboarding.import.choose_draft': 'Выберите один черновик для продолжения тестирования и публикации',
'onboarding.import.report_title': 'Отчёт OpenAPI и выбор черновика',
'onboarding.import.continue': 'Продолжить с этим черновиком',
'onboarding.import.selected': 'Выбран для onboarding',
'onboarding.import.drift': 'Выбранный черновик изменился или недоступен. Проверьте отчёт и явно выберите доступный черновик.',
'onboarding.import.registration_pending': 'Отчёт импорта регистрируется. Обновите onboarding перед выбором.',
'onboarding.import.registration_failed': 'Импорт применён, но его контекст onboarding не подтверждён. Обновите страницу, чтобы восстановить отчёт.',
'onboarding.import.selection_failed': 'Не удалось выбрать этот черновик. Обновите отчёт и проверьте актуальные варианты.',
'onboarding.import.conflict_reload': 'Состояние onboarding изменилось. Загружен актуальный отчёт; проверьте его перед новой попыткой.',
'onboarding.import.retry_registration': 'Повторить восстановление отчёта',
'onboarding.import.view_report': 'Открыть полный отчёт импорта',
});
+243 -1
View File
@@ -12,6 +12,7 @@
refreshPromise: null,
refreshQueued: false,
startedRequested: false,
importError: null,
};
var channel = null;
var trigger = null;
@@ -79,7 +80,7 @@
function actionLabel(id) { return tKey('onboarding.action.' + id); }
function deepLink(step) {
var snapshot = state.snapshot || {};
var returnTo = encodeURIComponent(window.location.pathname + window.location.search);
var returnTo = encodeURIComponent(boundedReturnContext());
if (step.id === 'operation') return '/wizard/?onboarding=1&return=' + returnTo;
if (step.id === 'test' || step.id === 'publish_operation') {
if (!snapshot.operation_id) return '/wizard/?onboarding=1&return=' + returnTo;
@@ -100,6 +101,220 @@
return '/logs?agent_id=' + encodeURIComponent(snapshot.agent_id || '');
}
function navigate(step) { window.location.href = deepLink(step); }
function safeReturnContext(raw) {
if (typeof raw !== 'string' || raw.charAt(0) !== '/' || raw.indexOf('//') === 0
|| /[\u0000-\u001f\\]/.test(raw) || raw.length > 2048) return null;
var url;
try { url = new URL(raw, window.location.origin); } catch (_error) { return null; }
if (url.origin !== window.location.origin) return null;
var allowed = {
'/': [],
'/agents': ['onboarding', 'action', 'operationId', 'operationVersion'],
'/api-keys': ['onboarding', 'action', 'agentId', 'agentRevision'],
'/logs': ['log_id', 'agent_id', 'operation_id'],
'/secrets': [],
'/settings': [],
'/usage': [],
'/workspace-setup': [],
'/wizard/': ['mode', 'operationId', 'step', 'onboarding'],
};
var keys = allowed[url.pathname];
if (!keys) return null;
var safe = new URLSearchParams();
url.searchParams.forEach(function(value, key) {
if (keys.indexOf(key) < 0) return;
if (key === 'onboarding' && value === '1') safe.set(key, value);
else if (key === 'action' && value === 'create') safe.set(key, value);
else if (key === 'mode' && (value === 'create' || value === 'edit')) safe.set(key, value);
else if ((key === 'operationVersion' || key === 'agentRevision' || key === 'step')
&& /^[0-9]{1,16}$/.test(value)) safe.set(key, value);
else if (/^(?:operationId|agentId|log_id|agent_id|operation_id)$/.test(key)
&& /^[A-Za-z0-9_-]{1,128}$/.test(value)) safe.set(key, value);
});
var context = url.pathname + (safe.size ? '?' + safe.toString() : '');
return context.length <= 256 ? context : url.pathname;
}
function boundedReturnContext() {
return safeReturnContext(window.location.pathname + window.location.search) || '/';
}
function returnContextFromQuery() {
var candidate = new URLSearchParams(window.location.search).get('return');
return safeReturnContext(candidate) || boundedReturnContext();
}
function openOpenApiPath() {
if (!window.CrankOpenApiImport || typeof window.CrankOpenApiImport.open !== 'function') {
window.location.href = '/?onboarding_openapi=1&return=' + encodeURIComponent(boundedReturnContext());
return;
}
window.CrankOpenApiImport.open({
workspaceId: state.workspaceId,
onboarding: true,
returnContext: returnContextFromQuery(),
importContext: state.snapshot && state.snapshot.import_context,
onImported: function(identity) { return registerImportedApplication(identity); },
onSelectDraft: function(operationId, version, identity) { return selectImportedDraft(operationId, version, identity); },
});
}
async function registerImportedApplication(identity) {
var workspaceId = state.workspaceId;
var epoch = state.epoch;
if (!identity || !identity.applicationIdempotencyKey || !identity.planDigest
|| !window.CrankApi || typeof window.CrankApi.registerOnboardingImportContext !== 'function') {
throw new Error(tKey('onboarding.import.registration_failed'));
}
try {
var authoritative = await window.CrankApi.getOnboarding(workspaceId);
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
throw new Error(tKey('onboarding.import.registration_failed'));
}
state.snapshot = authoritative;
render();
var response = await window.CrankApi.registerOnboardingImportContext(workspaceId, {
application_idempotency_key: identity.applicationIdempotencyKey,
plan_digest: identity.planDigest,
expected_revision: Number(authoritative && authoritative.revision || 0),
});
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
throw new Error(tKey('onboarding.import.registration_failed'));
}
var current = response && response.onboarding ? response.onboarding : response;
if (!current || !current.import_context) throw new Error(tKey('onboarding.import.registration_failed'));
state.snapshot = current;
render();
return current;
} catch (error) {
if (epoch === state.epoch && workspaceId === state.workspaceId) {
await refresh();
var recovered = state.snapshot && state.snapshot.import_context;
if (recovered
&& recovered.application_idempotency_key === identity.applicationIdempotencyKey
&& recovered.plan_digest === identity.planDigest) return state.snapshot;
}
throw error;
}
}
async function selectImportedDraft(operationId, version, identity) {
if (!operationId || !window.CrankApi || typeof window.CrankApi.selectOnboardingImportDraft !== 'function') return null;
var workspaceId = state.workspaceId;
var epoch = state.epoch;
var context = state.snapshot && state.snapshot.import_context;
var applicationKey = identity && identity.applicationIdempotencyKey || (context && context.application_idempotency_key);
var digest = identity && identity.planDigest || (context && context.plan_digest);
if (!applicationKey || !digest || !Number.isInteger(version) || version < 1) {
throw new Error(tKey('onboarding.import.selection_failed'));
}
try {
var response = await window.CrankApi.selectOnboardingImportDraft(workspaceId, {
application_idempotency_key: applicationKey,
plan_digest: digest,
operation_id: operationId,
operation_version: version,
expected_revision: Number(state.snapshot && state.snapshot.revision || 0),
});
var current = response && response.onboarding ? response.onboarding : response;
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
throw new Error(tKey('onboarding.import.selection_failed'));
}
if (!current || !current.import_context
|| current.import_context.selected_operation_id !== operationId
|| Number(current.import_context.selected_operation_version) !== version) {
throw new Error(tKey('onboarding.import.selection_failed'));
}
if (current && typeof current === 'object' && 'revision' in current) {
state.snapshot = current;
render();
}
return response;
} catch (error) {
if (error && error.status === 409 && epoch === state.epoch && workspaceId === state.workspaceId) {
await refresh();
}
throw error;
}
}
function renderOpenApiPath() {
var section = document.createElement('div');
section.className = 'onboarding-openapi-path';
var hint = document.createElement('p');
hint.className = 'onboarding-openapi-hint';
hint.textContent = tKey('onboarding.openapi_hint');
var openButton = button(tKey('onboarding.openapi_path'), 'onboarding-openapi-path', openOpenApiPath, 'onboarding-step-action');
section.appendChild(hint);
section.appendChild(openButton);
return section;
}
async function continueWithImportedDraft(choice) {
var context = state.snapshot && state.snapshot.import_context;
if (!context || !choice || choice.selectable !== true) return;
state.importError = null;
render();
try {
await selectImportedDraft(choice.operation_id, choice.version, null);
window.location.href = '/wizard/?mode=edit&operationId=' + encodeURIComponent(choice.operation_id)
+ '&operationVersion=' + encodeURIComponent(choice.version) + '&onboarding=1'
+ '&return=' + encodeURIComponent(boundedReturnContext());
} catch (_error) {
state.importError = tKey('onboarding.import.selection_failed');
render();
}
}
function renderImportContext() {
var context = state.snapshot && state.snapshot.import_context;
if (!context) return null;
var section = document.createElement('section');
section.className = 'onboarding-import-report';
section.dataset.testid = 'onboarding-import-context';
var title = document.createElement('h3');
title.textContent = tKey('onboarding.import.report_title');
section.appendChild(title);
if (context.drift) {
var drift = document.createElement('p');
drift.className = 'onboarding-import-drift';
drift.setAttribute('role', 'alert');
drift.textContent = tKey('onboarding.import.drift');
section.appendChild(drift);
}
if (state.importError) {
var error = document.createElement('p');
error.className = 'onboarding-import-error';
error.setAttribute('role', 'alert');
error.textContent = state.importError;
section.appendChild(error);
}
var choices = Array.isArray(context.choices) ? context.choices : [];
function outcomeLabel(outcome) {
var key = 'openapi.plan.outcome.' + String(outcome || '');
return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key);
}
function reasonLabel(reason) {
if (!reason) return '';
return window.CrankOpenApiImport && typeof window.CrankOpenApiImport.describeFinding === 'function'
? window.CrankOpenApiImport.describeFinding(reason)
: tKey('openapi.finding.generic');
}
var list = document.createElement('ul');
list.className = 'onboarding-import-report-list';
choices.forEach(function(choice) {
var item = document.createElement('li');
item.className = 'onboarding-import-report-item';
var summary = document.createElement('span');
summary.textContent = [choice.name || choice.key || '', outcomeLabel(choice.outcome), choice.version ? 'v' + choice.version : '', reasonLabel(choice.reason)]
.filter(Boolean).join(' · ');
item.appendChild(summary);
if (choice.selectable === true && (!context.selected_operation_id || context.drift)) {
item.appendChild(button(tKey('onboarding.import.continue'), null, function() { continueWithImportedDraft(choice); }, 'onboarding-step-action'));
} else if (choice.operation_id === context.selected_operation_id && Number(choice.version) === Number(context.selected_operation_version)) {
var selected = document.createElement('span');
selected.className = 'onboarding-import-selected';
selected.textContent = tKey('onboarding.import.selected');
item.appendChild(selected);
}
list.appendChild(item);
});
section.appendChild(list);
section.appendChild(button(tKey('onboarding.import.view_report'), null, openOpenApiPath, 'onboarding-link-button'));
return section;
}
function recordStarted() {
if (state.startedRequested || !state.snapshot || state.snapshot.completed) return;
state.startedRequested = true;
@@ -240,6 +455,17 @@
});
body.appendChild(list);
}
var returnContext = document.createElement('span');
returnContext.className = 'onboarding-return-context';
returnContext.dataset.testid = 'onboarding-return-context';
returnContext.hidden = true;
returnContext.textContent = returnContextFromQuery();
body.appendChild(returnContext);
if (!state.snapshot.completed) {
body.appendChild(renderOpenApiPath());
}
var importReport = renderImportContext();
if (importReport) body.appendChild(importReport);
var footer = document.createElement('div');
footer.className = 'onboarding-footer';
footer.appendChild(button(tKey('onboarding.refresh'), 'onboarding-refresh', refresh, 'onboarding-link-button'));
@@ -295,6 +521,7 @@
var snapshot = await window.CrankApi.getOnboarding(workspaceId);
if (epoch !== state.epoch || workspaceId !== (currentWorkspace() && currentWorkspace().id)) return;
state.snapshot = snapshot;
state.importError = null;
var preference = safePreference();
if (window.location.pathname === '/'
&& !preference.opened
@@ -304,6 +531,21 @@
setOpen(true);
}
renderDeepLinkRecovery(snapshot);
if (window.location.pathname === '/' && new URLSearchParams(window.location.search).get('onboarding_openapi') === '1'
&& window.CrankOpenApiImport && typeof window.CrankOpenApiImport.open === 'function') {
var openUrl = new URL(window.location.href);
openUrl.searchParams.delete('onboarding_openapi');
window.history.replaceState(window.history.state, '', openUrl.pathname + openUrl.search + openUrl.hash);
window.CrankOpenApiImport.open({
workspaceId: workspaceId,
onboarding: true,
returnContext: returnContextFromQuery(),
importContext: snapshot.import_context || null,
onImported: function(identity) { return registerImportedApplication(identity); },
onSelectDraft: function(operationId, version, identity) { return selectImportedDraft(operationId, version, identity); },
});
}
return snapshot;
} catch (error) {
if (epoch !== state.epoch) return;
state.error = error;
+1789 -183
View File
File diff suppressed because it is too large. Load diff
+81
View File
@@ -1,6 +1,8 @@
var wizardOperationLoadGeneration = 0;
var wizardLifecycleActionBusy = false;
var wizardTestConfirmationToken = null;
var wizardSavedDraftPayload = null;
var wizardPinnedVersionStale = false;
function operationErrorCode(error) {
return error && error.payload && error.payload.error
@@ -130,12 +132,33 @@ async function saveOperation(stayOnPage) {
async function loadOperationForEdit() {
if (!wizardWorkspaceId || !wizardEditId) return;
var generation = ++wizardOperationLoadGeneration;
wizardCurrentOperation = null;
wizardCurrentVersion = null;
wizardSavedDraftPayload = null;
wizardPinnedVersionStale = false;
var pinnedVersionValue = new URLSearchParams(window.location.search).get('operationVersion');
var pinnedVersion = null;
if (pinnedVersionValue !== null) {
pinnedVersion = Number(pinnedVersionValue);
if (!/^[0-9]{1,10}$/.test(pinnedVersionValue) || !Number.isSafeInteger(pinnedVersion) || pinnedVersion < 1) {
wizardPinnedVersionStale = true;
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
return;
}
}
var requestedWorkspaceId = wizardWorkspaceId;
var requestedOperationId = wizardEditId;
var detail = await window.CrankApi.getOperation(requestedWorkspaceId, requestedOperationId);
if (generation !== wizardOperationLoadGeneration
|| requestedWorkspaceId !== wizardWorkspaceId
|| requestedOperationId !== wizardEditId) return;
var detailDraftVersion = Number(detail.draft_version_ref && detail.draft_version_ref.version
|| detail.current_draft_version);
if (pinnedVersion !== null && detailDraftVersion !== pinnedVersion) {
wizardPinnedVersionStale = true;
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
return;
}
wizardProtocol = detail.protocol || 'rest';
await loadWizardPanels([3]);
var draftVersion = await window.CrankApi.getOperationVersion(
@@ -146,9 +169,24 @@ async function loadOperationForEdit() {
if (generation !== wizardOperationLoadGeneration
|| requestedWorkspaceId !== wizardWorkspaceId
|| requestedOperationId !== wizardEditId) return;
if (pinnedVersion !== null) {
var currentDetail = await window.CrankApi.getOperation(requestedWorkspaceId, requestedOperationId);
if (generation !== wizardOperationLoadGeneration
|| requestedWorkspaceId !== wizardWorkspaceId
|| requestedOperationId !== wizardEditId) return;
var currentDraftVersion = Number(currentDetail.draft_version_ref && currentDetail.draft_version_ref.version
|| currentDetail.current_draft_version);
if (currentDraftVersion !== pinnedVersion) {
wizardPinnedVersionStale = true;
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
return;
}
detail = currentDetail;
}
wizardCurrentOperation = detail;
wizardCurrentVersion = draftVersion;
prefillWizardFromEdit(detail, draftVersion);
wizardSavedDraftPayload = updateOperationPayload(collectWizardPayload());
renderAgentFacingPreview();
renderImportQualityFindings(draftVersion);
}
@@ -375,6 +413,27 @@ function updateOperationPayload(payload) {
};
}
function canonicalDraftPayload(payload) {
var editablePayload = updateOperationPayload(payload);
delete editablePayload.category;
function sortKeys(value) {
if (Array.isArray(value)) return value.map(sortKeys);
if (!value || typeof value !== 'object') return value;
return Object.keys(value).sort().reduce(function(sorted, key) {
sorted[key] = sortKeys(value[key]);
return sorted;
}, {});
}
return JSON.stringify(sortKeys(editablePayload));
}
function draftPayloadMatchesBaseline(payload) {
return wizardSavedDraftPayload !== null
&& canonicalDraftPayload(payload) === canonicalDraftPayload(wizardSavedDraftPayload);
}
async function refreshCurrentOperationState() {
if (!wizardWorkspaceId || !wizardEditId) return null;
var detail = await window.CrankApi.getOperation(wizardWorkspaceId, wizardEditId);
@@ -396,6 +455,9 @@ async function refreshCurrentOperationState() {
}
async function persistCurrentDraft(stayOnPage) {
if (wizardPinnedVersionStale) {
throw new Error(tKey('wizard.stale.body'));
}
if (!wizardWorkspaceId) {
throw new Error(tKey('wizard.error.no_workspace'));
}
@@ -405,14 +467,33 @@ async function persistCurrentDraft(stayOnPage) {
var createdNow = false;
if (wizardMode === 'edit' && wizardEditId) {
if (draftPayloadMatchesBaseline(payload)) {
if (stayOnPage) {
var unchangedSaveDraftBtn = document.querySelector('.btn-save-draft');
if (unchangedSaveDraftBtn) {
var unchangedLabel = unchangedSaveDraftBtn.textContent;
unchangedSaveDraftBtn.textContent = tKey('wizard.save.saved');
setTimeout(function() {
unchangedSaveDraftBtn.textContent = unchangedLabel;
}, 1400);
}
}
return {
operation_id: wizardEditId,
version: currentDraftVersion(),
status: 'draft',
};
}
response = await window.CrankApi.updateOperation(
wizardWorkspaceId,
wizardEditId,
updateOperationPayload(payload)
);
wizardSavedDraftPayload = updateOperationPayload(payload);
} else {
response = await window.CrankApi.createOperation(wizardWorkspaceId, payload);
createdNow = true;
wizardSavedDraftPayload = updateOperationPayload(payload);
wizardEditId = response.operation_id;
wizardMode = 'edit';
history.replaceState(
+2 -2
View File
@@ -253,7 +253,7 @@
var source = mappingEntrySource(parsed[outputField]);
return {
output: outputField,
responsePath: responseSourceToPath(source) || outputField,
responsePath: responseSourceToPath(source),
};
});
}
@@ -492,7 +492,7 @@
responseRows.forEach(function(row) {
var responsePath = valueIn(row, 'responsePath');
var output = valueIn(row, 'output') || outputNameFromPath(responsePath);
if (!responsePath || !output) return;
if (!output) return;
responseMapping[output] = joinJsonPath('$.response.body', responsePath);
});
writeText('tool-output-mapping', dumpYaml(responseMapping));
+1 -1
View File
@@ -371,7 +371,7 @@ function startNewUpstream() {
setValue('new-auth-profile-password-secret', '');
updateUpstreamAuthUi();
var first = form.querySelector('input');
if (first) setTimeout(function() { first.focus(); }, 50);
if (first) first.focus();
}
}
+10
View File
@@ -21,6 +21,16 @@ server {
return 302 /;
}
location ~ ^/api/admin/workspaces/[^/]+/imports/openapi/[^/]+/plans$ {
client_max_body_size 16m;
proxy_pass http://admin-api:3001;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api/ {
proxy_pass http://admin-api:3001;
proxy_http_version 1.1;
+59 -2
View File
@@ -133,6 +133,59 @@ test('optional Getting Started checklist is server-derived, resumable, bilingual
await expect(page.getByTestId('onboarding-checklist')).toHaveCSS('scroll-behavior', 'auto');
});
test('onboarding return context drops unknown query secrets and bounds allowlisted navigation context', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
await routeOnboarding(page, async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(onboardingSnapshot(workspace.id)),
});
});
await page.goto('/agents?onboarding=1&token=crk_return_secret_canary');
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
const returnContext = page.getByTestId('onboarding-return-context');
await expect(returnContext).toHaveText('/agents?onboarding=1');
await expect(returnContext).not.toContainText('crk_return_secret_canary');
await page.goto('/logs?log_id=' + 'a'.repeat(128) + '&agent_id=' + 'b'.repeat(128) + '&operation_id=' + 'c'.repeat(128));
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-return-context')).toHaveText('/logs');
await page.goto('/secrets?token=crk_return_secret_canary');
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-return-context')).toHaveText('/secrets');
});
test('a stale onboarding-pinned wizard version is rejected before loading or saving another Draft', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operationId = 'op_pinned';
let versionReads = 0;
let writes = 0;
await page.route(`**/workspaces/${workspace.id}/operations/${operationId}`, async (route) => {
if (route.request().method() !== 'GET') writes += 1;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({
id: operationId, protocol: 'rest', current_draft_version: 3,
draft_version_ref: { version: 3 },
}) });
});
await page.route(`**/operations/${operationId}/versions/*`, async (route) => {
versionReads += 1;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ version: 3 }) });
});
await page.goto(`/wizard/?mode=edit&operationId=${operationId}&operationVersion=2`);
await page.waitForFunction(() => window.CrankWizardReady === true);
await expect(page.locator('#wizard-live-status')).toBeVisible();
await expect(page.locator('#tool-name')).not.toHaveValue('wrong newer Draft');
await page.locator('.btn-save-draft').click();
expect(versionReads).toBe(0);
expect(writes).toBe(0);
expect(await page.evaluate(() => window.wizardCurrentOperation)).toBeNull();
});
test('onboarding error exposes safe support correlation and retries without a client completion bypass', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
@@ -156,6 +209,7 @@ test('onboarding error exposes safe support correlation and retries without a cl
});
await page.goto('/');
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
@@ -183,7 +237,7 @@ test('validation, upstream and compatibility errors recover from the last author
];
let failureIndex = -1;
await routeOnboarding(page, async (route) => {
if (failureIndex >= 0) {
if (failureIndex >= 0 && route.request().method() === 'GET') {
const failure = failures[failureIndex];
await route.fulfill({
status: failure.status,
@@ -201,6 +255,7 @@ test('validation, upstream and compatibility errors recover from the last author
});
await page.goto('/');
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
@@ -237,7 +292,9 @@ test('authentication recovery returns to an incomplete authoritative onboarding
});
await page.goto('/');
await page.getByTestId('onboarding-trigger').click();
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
rejectOnce = true;
await page.getByTestId('onboarding-refresh').click();
await expect(page).toHaveURL(/\/login/);
@@ -0,0 +1,279 @@
const { test, expect } = require('@playwright/test');
const { login, localized, uniqueName } = require('./helpers');
async function dismissOnboardingIfOpen(page) {
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
await page.evaluate(() => {
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
if (dismiss) dismiss.click();
});
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function importDocument(prefix) {
return [
'openapi: 3.0.3',
'info: { title: ImportPlan UI test, version: \'1\' }',
'paths:',
' /' + prefix + '-selected:',
' get:',
' operationId: ' + prefix + '_selected',
' responses:',
' \'200\': { description: OK }',
' /' + prefix + '-excluded:',
' get:',
' operationId: ' + prefix + '_excluded',
' responses:',
' \'200\': { description: OK }',
].join('\n');
}
function planResponse(prefix) {
return {
plan_reference: 'plan_e2e_importplan_213',
plan_digest: 'a'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: 'partial',
counts: { selected: 1, excluded: 1, actionable: 1, blocked: 0 },
candidates: [
{
key: 'GET /' + prefix + '-selected',
name: 'selected_operation',
state: 'actionable',
action: 'new_version',
target_operation_id: 'op_existing_target',
confirmed_name: null,
auth_profile_id: null,
reason: null,
},
{
key: 'GET /' + prefix + '-excluded',
name: 'excluded_operation',
state: 'excluded',
action: null,
target_operation_id: null,
confirmed_name: null,
auth_profile_id: null,
reason: 'not_selected',
},
],
};
}
async function preparePlanFlow(page, locale) {
const planCalls = [];
const applyCalls = [];
const prefix = uniqueName('plan_apply');
let releaseApplyResponse;
const applyResponseHeld = new Promise((resolve) => {
releaseApplyResponse = resolve;
});
// Keep this mock aligned with the public CreatePlan response shape.
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
planCalls.push({
url: route.request().url(),
payload: route.request().postDataJSON(),
});
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(planResponse(prefix)),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/apply$/, async (route) => {
applyCalls.push({
url: route.request().url(),
payload: route.request().postDataJSON(),
});
// Keep the request pending until the test has checked the duplicate guard.
await applyResponseHeld;
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
plan_digest: 'a'.repeat(64),
counts: { selected: 1, excluded: 1, created: 0, versioned: 1 },
outcomes: [{ status: 'versioned' }],
}),
});
});
// Contain the legacy path so this red-phase test cannot mutate the E2E DB.
await page.route(/\/imports\/openapi\/[^/]+\/create$/, async (route) => {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ message: 'ImportPlan flow required' }),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.evaluate((language) => window.setLang(language), locale);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.locator('#openapi-import-file').setInputFiles({
name: 'import-plan.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(importDocument(prefix)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await page.locator('#openapi-import-preview').click();
await previewResponse;
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
// The existing preview action becomes Plan creation followed by confirmation.
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect.poll(() => planCalls.length).toBe(1);
return { planCalls, applyCalls, prefix, releaseApplyResponse };
}
async function assertConfirmation(page, prefix) {
const confirmation = page.locator('[data-testid="openapi-import-apply-confirmation"]');
const counts = page.locator('[data-testid="openapi-import-apply-counts"]');
const versioning = page.locator('[data-testid="openapi-import-versioning-consequences"]');
await expect(counts).toContainText(localized('Selected: 1', 'Выбрано: 1'));
await expect(counts).toContainText(localized('Excluded: 1', 'Исключено: 1'));
await expect(counts).toContainText(localized('Actionable: 1', 'Можно применить: 1'));
await expect(counts).toContainText(localized('Blocked: 0', 'Заблокировано: 0'));
await expect(versioning).toContainText(localized('new Draft Version', 'новая версия черновика'));
await expect(versioning).toContainText(
localized('Published Version and history remain unchanged', 'Опубликованная версия и история останутся без изменений'),
);
await expect(confirmation).toContainText('GET /' + prefix + '-selected');
await expect(confirmation).toContainText('GET /' + prefix + '-excluded');
await expect(confirmation).toContainText('op_existing_target');
}
test('[P1] AC-13 renders server-confirmed partial and new_version consequences in RU and EN', async ({ page }) => {
// This test covers rendering of a stored server plan only. It does not
// specify how UI controls compose selection/decision request fields.
const { planCalls, prefix } = await preparePlanFlow(page, 'ru');
for (const locale of ['ru', 'en']) {
await test.step('confirmation in ' + locale, async () => {
await page.evaluate((language) => window.setLang(language), locale);
await assertConfirmation(page, prefix);
});
}
expect(planCalls).toHaveLength(1);
expect(planCalls[0].url).toMatch(/\/imports\/openapi\/[^/]+\/plans$/);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
})).toBeVisible();
});
test('[P1] AC-13 double-click sends one Apply with the stored reference, digest and idempotency key', async ({ page }) => {
const { applyCalls, releaseApplyResponse } = await preparePlanFlow(page, 'en');
const applyButton = page.getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
});
await applyButton.dblclick();
await expect.poll(() => applyCalls.length).toBe(1);
await expect(applyButton).toBeDisabled();
releaseApplyResponse();
await expect(page.locator('[data-testid="openapi-import-apply-result"]')).toBeVisible();
expect(applyCalls).toHaveLength(1);
expect(applyCalls[0].url).toMatch(/\/imports\/openapi\/plan_e2e_importplan_213\/apply$/);
expect(applyCalls[0].payload).toMatchObject({
plan_digest: 'a'.repeat(64),
});
expect(typeof applyCalls[0].payload.idempotency_key).toBe('string');
expect(applyCalls[0].payload.idempotency_key.length).toBeGreaterThan(0);
});
test('[P1] AC-13 submits the confirmed new_version decision for the exact existing operation', async ({ page }) => {
const prefix = uniqueName('plan_version');
const targetOperationId = 'op_exact_importplan_target';
const planCalls = [];
const expectedName = prefix + '_selected';
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
items: [{ id: targetOperationId, name: expectedName, protocol: 'rest', status: 'draft' }],
page: 1,
page_size: 1,
total: 1,
}),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
const payload = route.request().postDataJSON();
planCalls.push(payload);
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_e2e_importplan_decision',
plan_digest: 'b'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: payload.selection_mode,
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
candidates: [{
key: payload.decisions[0].operation_key,
name: expectedName,
state: 'actionable',
action: 'new_version',
target_operation_id: targetOperationId,
confirmed_name: null,
auth_profile_id: null,
reason: null,
}],
}),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'import-plan-decision.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(importDocument(prefix)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'),
);
await page.locator('#openapi-import-preview').click();
await previewResponse;
const operationRow = page.locator('.openapi-import-operation').filter({ hasText: expectedName });
const operationCheckbox = operationRow.locator('[data-openapi-operation]');
await expect(operationCheckbox).toBeVisible();
const operationKey = await operationCheckbox.inputValue();
await page.locator('#openapi-import-partial-mode').check();
for (const checkbox of await page.locator('[data-openapi-operation]').all()) {
if (await checkbox.inputValue() !== operationKey) await checkbox.uncheck();
}
await expect(operationRow.locator('.openapi-import-operation-meta')).toContainText(expectedName);
const action = operationRow.locator('[data-openapi-decision-action]');
await expect(action.locator('option[value="new_version"]')).toBeEnabled();
await action.selectOption('new_version');
await expect(operationRow.locator('[data-openapi-decision-target]')).toHaveValue(targetOperationId);
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(targetOperationId);
expect(planCalls).toHaveLength(1);
expect(planCalls[0].selection_mode).toBe('partial');
expect(planCalls[0].selected_operation_keys).toEqual([operationKey]);
expect(planCalls[0].decisions).toEqual([{
operation_key: operationKey,
action: 'new_version',
target_operation_id: targetOperationId,
}]);
});
@@ -0,0 +1,943 @@
// Story 2.15 browser acceptance: OpenAPI branch in the guided onboarding.
//
// STATUS: ACTIVE. All leaves are activated and assert the behavior promised by the
// approved spec `_bmad-output/implementation-artifacts/spec-2-15-openapi-guided-onboarding.md`.
//
// Backend authority (immutable ImportPlan apply/replay, onboarding selection and
// event rollups, migration/schema guards) is covered by the Rust integration
// suites mapped in
// `_bmad-output/test-artifacts/atdd-checklist-2-15-openapi-guided-onboarding.md`.
// This file only covers user-observable browser behavior.
const { test, expect } = require('@playwright/test');
const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
const SECRET_CANARY = 'crk_onboarding_raw_secret_canary';
const REPRESENTATIVE_OPENAPI = [
'openapi: 3.0.3',
"info: { title: 'Onboarding representative document', version: '1' }",
'servers: [{ url: http://127.0.0.1:3310 }]',
'paths:',
' /rates:',
' get:',
' operationId: listRates',
' responses:',
" '200':",
' description: JSON exchange rates',
' content:',
' application/json:',
' schema:',
' type: object',
' properties:',
' amount: { type: number }',
' base: { type: string }',
' date: { type: string }',
' rates:',
' type: object',
' properties:',
' EUR: { type: number }',
' /health:',
' get:',
' operationId: getHealth',
' responses:',
" '200':",
' description: JSON service health',
' content:',
' application/json:',
' schema:',
' type: object',
' properties:',
' status: { type: string }',
'',
].join('\n');
function representativeOpenApi(suffix) {
const safeSuffix = suffix.replace(/[^a-zA-Z0-9_]/g, '_');
return REPRESENTATIVE_OPENAPI
.replace('operationId: listRates', `operationId: listRates_${safeSuffix}`)
.replace('operationId: getHealth', `operationId: getHealth_${safeSuffix}`);
}
function importContext(report, overrides = {}) {
return Object.assign({
application_idempotency_key: report.idempotency_key,
plan_digest: report.plan_digest,
report,
choices: report.outcomes.map((outcome) => ({
key: outcome.key,
name: outcome.name,
outcome: outcome.outcome,
operation_id: outcome.operation_id,
version: outcome.version,
reason: outcome.reason,
selectable: ['created', 'versioned', 'renamed'].includes(outcome.outcome),
})),
selected_operation_id: null,
selected_operation_version: null,
drift: null,
}, overrides);
}
function registeredResponse(snapshot, context) {
return Object.assign({}, snapshot, {
registered: true,
revision: snapshot.revision + 1,
import_context: context,
});
}
function selectedResponse(snapshot, context, operationId, version) {
return Object.assign({}, snapshot, {
selected: true,
revision: snapshot.revision + 1,
operation_id: operationId,
operation_version: version,
import_context: Object.assign({}, context, {
selected_operation_id: operationId,
selected_operation_version: version,
}),
});
}
function onboardingSnapshot(workspaceId, overrides = {}) {
return {
schema_version: 1,
workspace_id: workspaceId,
revision: 7,
status: 'in_progress',
completed: false,
eligible_since: '2026-10-03T08:00:00Z',
steps: [
{ id: 'operation', completed: false, status: 'current', action_code: 'create_operation', reason_code: 'authoritative_evidence_missing' },
{ id: 'test', completed: false, status: 'pending', action_code: 'test_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'publish_operation', completed: false, status: 'pending', action_code: 'publish_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'agent', completed: false, status: 'pending', action_code: 'publish_agent', reason_code: 'prerequisite_incomplete' },
{ id: 'key', completed: false, status: 'pending', action_code: 'create_mcp_key', reason_code: 'prerequisite_incomplete' },
{ id: 'mcp_connection', completed: false, status: 'pending', action_code: 'connect_mcp_client', reason_code: 'prerequisite_incomplete' },
{ id: 'first_call', completed: false, status: 'pending', action_code: 'call_tool', reason_code: 'prerequisite_incomplete' },
],
operation_id: null,
operation_version: null,
agent_id: null,
catalog_revision: null,
platform_api_key_id: null,
mcp_endpoint: 'http://127.0.0.1:3302/mcp',
first_call: null,
...overrides,
};
}
function candidate(name, overrides = {}) {
const draft = {
name,
display_name: name,
category: 'default',
target: { method: 'GET', path: '/' + name, server_url: 'https://api.example.test' },
input_schema: { type: 'object', properties: {} },
output_schema: { type: 'object', properties: {} },
input_mapping: [],
output_mapping: [],
tool_description: {},
wizard_state: null,
};
return Object.assign(
{
key: 'GET /' + name,
method: 'GET',
path: '/' + name,
status: 'actionable',
operation_id: null,
suggested_name: name,
suggested_display_name: name,
description: 'ATDD candidate',
category: 'default',
input_fields: 0,
output_fields: 1,
server_urls: ['https://api.example.test'],
source_location: { pointer: '/paths/~1' + name + '/get' },
findings: [],
security_requirements: { source: 'none', alternatives: [] },
security_schemes: {},
draft,
},
overrides,
);
}
function previewResponse(operations, extra = {}) {
const base = {
job_id: 'imp_e2e_onboarding_215',
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
preview: {
source: { format: 'openapi', version: '3.0.3', title: 'Onboarding ATDD', servers: ['https://api.example.test'] },
groups: [{ key: 'default', title: 'Default', operations }],
findings: [],
conflicts: [],
},
security_profile_choices: [],
};
return Object.assign(base, extra, {
preview: Object.assign(base.preview, extra.preview || {}),
});
}
function planResponse(candidates, overrides = {}) {
return Object.assign(
{
plan_reference: 'plan_e2e_onboarding_215',
plan_digest: 'a'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: 'full',
counts: { selected: candidates.length, excluded: 0, actionable: candidates.length, blocked: 0 },
candidates,
},
overrides,
);
}
function applyReport(outcomes, overrides = {}) {
return Object.assign(
{
schema_version: 'import-plan-apply-report-v1',
status: 'applied',
plan_id: 'plan_e2e_onboarding_215',
plan_digest: 'a'.repeat(64),
job_id: 'imp_e2e_onboarding_215',
idempotency_key: 'onboarding:apply:1',
source_id: 'src_e2e_onboarding',
source_digest: 'b'.repeat(64),
dependencies: [],
counts: { created: outcomes.length, versioned: 0, renamed: 0, skipped: 0, excluded: 0, rejected: 0 },
outcomes,
summary: 'Plan applied',
recovery: 'none',
applied_at: '2026-10-03T08:05:00Z',
},
overrides,
);
}
async function routeOnboarding(page, snapshot) {
await page.route(
/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\/events|\/reset-selection)?(?:\?.*)?$/,
async (route) => {
if (route.request().method() === 'GET') {
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(snapshot) });
return;
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(Object.assign({ accepted: true }, snapshot)),
});
},
);
}
async function routePreview(page, body, status = 200) {
await page.route(/\/imports\/openapi\/preview(?:\?.*)?$/, (route) => route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body),
}));
}
async function routePlanCreate(page, body, status = 200) {
await page.route(/\/imports\/openapi\/[^/]+\/plans(?:\?.*)?$/, (route) => route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body),
}));
}
async function routeApply(page, body, status = 200) {
await page.route(/\/imports\/openapi\/[^/]+\/apply(?:\?.*)?$/, async (route) => {
const requestBody = route.request().postDataJSON();
const responseBody = typeof body === 'function' ? body(requestBody) : body;
await route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(responseBody) });
});
}
async function openOnboarding(page) {
await login(page);
const workspace = await getCurrentWorkspace(page);
await routeOnboarding(page, onboardingSnapshot(workspace.id));
await page.goto('/?onboarding=1');
const checklist = page.getByTestId('onboarding-checklist');
if (!(await checklist.isVisible())) {
await page.getByTestId('onboarding-trigger').click();
}
await expect(checklist).toBeVisible();
return workspace;
}
async function chooseOpenApiPath(page) {
await page.getByTestId('onboarding-openapi-path').click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
}
async function uploadPreview(page, document = REPRESENTATIVE_OPENAPI) {
await page.locator('#openapi-import-file').setInputFiles({
name: 'openapi.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(document),
});
await page.locator('#openapi-import-preview').click();
}
function parseMcpResponse(response) {
return response.text().then((text) => {
const dataLine = text.split(/\r?\n/).find((line) => line.startsWith('data:'));
return JSON.parse(dataLine ? dataLine.slice(5).trim() : text);
});
}
async function mcpPost(request, endpoint, key, payload, sessionId) {
const headers = {
Authorization: `Bearer ${key}`,
Accept: 'application/json, text/event-stream',
'Content-Type': 'application/json',
};
if (sessionId) {
headers['MCP-Session-Id'] = sessionId;
headers['MCP-Protocol-Version'] = '2025-06-18';
}
return request.post(endpoint, { headers, data: payload });
}
test.describe('Story 2.15 OpenAPI guided onboarding acceptance', () => {
test('[P1] AC-1 a protected non-Operations entry safely routes to canonical OpenAPI and preserves same-origin return context', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
await routeOnboarding(page, onboardingSnapshot(workspace.id));
await page.goto('/agents?onboarding=1');
const trigger = page.getByTestId('onboarding-trigger');
if (!await trigger.isVisible()) await expect(trigger).toBeVisible();
if (!await page.getByTestId('onboarding-checklist').isVisible()) await trigger.click();
await expect(page.getByTestId('onboarding-openapi-path')).toBeVisible();
expect(await page.evaluate(() => Boolean(window.CrankOpenApiImport))).toBe(false);
// Without the Operations importer bundle, the visible onboarding entry
// routes to Operations with a bounded, same-origin return hint.
const operationsNavigation = page.waitForRequest((request) => {
const url = new URL(request.url());
return request.isNavigationRequest()
&& url.pathname === '/'
&& url.searchParams.get('onboarding_openapi') === '1';
});
await page.getByTestId('onboarding-openapi-path').click();
const navigation = await operationsNavigation;
expect(new URL(navigation.url()).origin).toBe(new URL(process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3300').origin);
expect(new URL(page.url()).pathname).toBe('/');
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(page.locator('#openapi-import-file')).toBeAttached();
const returnHint = new URL(page.url()).searchParams.get('return');
expect(returnHint).toBe('/agents?onboarding=1');
expect(returnHint.length).toBeLessThanOrEqual(256);
const returnContext = await page.getByTestId('onboarding-return-context').textContent();
expect(returnContext).toBe('/agents?onboarding=1');
expect(returnContext).not.toContain('://');
expect(new URL(page.url()).origin).toBe(new URL(process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3300').origin);
});
test('[P1] AC-2 guided preview shows methods, findings, the exact proposed Operation and apply consequences without hiding blockers', async ({ page }) => {
await openOnboarding(page);
const actionable = candidate('onboarding-rates');
const blocked = candidate('onboarding-blocked', {
status: 'blocked',
findings: [{ code: 'unsupported_xml_body', severity: 'Error', message: 'XML bodies are unsupported', operation_key: 'GET /onboarding-blocked', source_location: { pointer: '/paths/~1onboarding-blocked/post' } }],
});
await routePreview(page, previewResponse([actionable, blocked], {
preview: { findings: [{ code: 'unsupported_xml_body', severity: 'Error', message: 'XML bodies are unsupported', operation_key: blocked.key, source_location: { pointer: '/paths/~1onboarding-blocked/post' } }] },
}));
await chooseOpenApiPath(page);
await uploadPreview(page);
// Criterion-defining assertion: the exact proposed Operation is visible for the selected candidate.
await expect(page.locator('#openapi-import-groups')).toContainText(actionable.suggested_name);
await expect(page.locator('#openapi-import-groups')).toContainText('GET');
await expect(page.locator('[data-testid="openapi-import-finding-code"]')).toContainText('unsupported_xml_body');
// A blocker cannot be hidden to continue: the blocker summary is shown and
// creation stays unavailable until the finding is resolved.
await expect(page.locator('[data-testid="openapi-import-blockers"]')).toBeVisible();
await expect(page.locator('#openapi-import-create')).toBeDisabled();
});
test('[P1] AC-3 security mapping requires only a canonical Auth Profile reference and never stores a raw credential', async ({ page }) => {
await openOnboarding(page);
const workspace = await getCurrentWorkspace(page);
const profileName = uniqueName('onboarding_auth_profile');
const secretValue = SECRET_CANARY + '_' + uniqueName('value');
const secret = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`,
{ name: uniqueName('onboarding_secret'), kind: 'token', value: secretValue },
);
const profile = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`,
{
name: profileName,
kind: 'bearer',
config: { bearer: { header_name: 'Authorization', secret_id: secret.id } },
},
);
await chooseOpenApiPath(page);
await page.locator('#openapi-import-file').setInputFiles({
name: 'onboarding-security.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from([
'openapi: 3.0.3',
`info: { title: ${profileName}, version: "1" }`,
'servers: [{ url: "http://127.0.0.1:3310" }]',
'paths:',
' /rates:',
' get:',
' operationId: onboarding_secured_rates',
' security:',
' - bearerAuth: []',
' responses:',
" '200': { description: OK }",
'components:',
' securitySchemes:',
' bearerAuth: { type: http, scheme: bearer }',
].join('\n')),
});
const previewResponsePromise = page.waitForResponse((response) => response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
const previewResponseReal = await previewResponsePromise;
expect(previewResponseReal.status()).toBe(200);
const previewArtifact = await previewResponseReal.json();
expect(JSON.stringify(previewArtifact)).not.toContain(secretValue);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
// Criterion-defining assertion: the canonical Auth Profile picker is shown.
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' });
await bearerOption.waitFor({ state: 'attached' });
const bearerIndex = await bearerOption.getAttribute('value');
expect(bearerIndex).toMatch(/^\d+$/);
await alternative.selectOption(bearerIndex);
const profilePicker = page.locator('#openapi-import-groups [data-openapi-security-profile]').first();
await expect(profilePicker).toBeVisible();
await profilePicker.selectOption(profile.id);
const planRequest = page.waitForRequest((request) => request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()));
await page.locator('#openapi-import-create').click();
const sentPlanRequest = await planRequest;
const planPayload = sentPlanRequest.postDataJSON();
expect(planPayload.decisions[0]).toMatchObject({ auth_profile_id: profile.id });
expect(planPayload.decisions[0].security_alternative_index).toEqual(expect.any(Number));
const planResponseReal = await sentPlanRequest.response();
expect(planResponseReal.ok(), await planResponseReal.text()).toBe(true);
const planArtifact = await planResponseReal.json();
expect(JSON.stringify(planPayload)).not.toContain(secretValue);
// The canonical artifact, onboarding projection and browser state carry the
// typed reference only. Secret material remains server-side.
const onboarding = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
const browserState = await page.evaluate(() => JSON.stringify({
local: Object.values(localStorage),
session: Object.values(sessionStorage),
url: location.href,
body: document.body.innerText,
}));
for (const value of [JSON.stringify(previewArtifact), JSON.stringify(planArtifact), JSON.stringify(onboarding), browserState, JSON.stringify(planPayload)]) {
expect(value).not.toContain(secretValue);
}
expect(JSON.stringify(planPayload)).toContain(profile.id);
expect(JSON.stringify(planArtifact)).toContain(profile.id);
await expect(page.locator('body')).not.toContainText(secretValue);
});
test('[P1] AC-4 after atomic apply of multiple Drafts the onboarding explicitly selects one actionable Draft and never auto-publishes', async ({ page }) => {
await openOnboarding(page);
const first = candidate('onboarding-rates');
const second = candidate('onboarding-currencies');
await routePreview(page, previewResponse([first, second]));
await routePlanCreate(page, planResponse([
{ key: first.key, name: first.suggested_name, state: 'actionable', action: 'create' },
{ key: second.key, name: second.suggested_name, state: 'actionable', action: 'create' },
]));
const outcomes = [
{ key: first.key, name: first.suggested_name, outcome: 'created', operation_id: 'op_onboarding_rates', version: 1, reason: null },
{ key: second.key, name: second.suggested_name, outcome: 'created', operation_id: 'op_onboarding_currencies', version: 1, reason: null },
];
let report;
const initial = onboardingSnapshot((await getCurrentWorkspace(page)).id);
let context;
const registrationRequests = [];
const selectionRequests = [];
let latestOnboarding = initial;
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\?.*)?$/, async (route) => {
if (route.request().method() !== 'GET') return route.fallback();
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(latestOnboarding) });
});
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/import-context$/, async (route) => {
registrationRequests.push(route.request().postDataJSON());
context = importContext(report);
const response = registeredResponse(initial, context);
latestOnboarding = response;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
});
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/select-draft$/, async (route) => {
const payload = route.request().postDataJSON();
selectionRequests.push(payload);
const response = selectedResponse(latestOnboarding, context, payload.operation_id, payload.operation_version);
latestOnboarding = response;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
});
await routeApply(page, (payload) => {
report = applyReport(outcomes, {
idempotency_key: payload.idempotency_key,
plan_digest: payload.plan_digest,
});
return report;
});
const publishRequests = [];
page.on('request', (request) => {
if (/\/publish(?:es)?(?:\?|$)/.test(new URL(request.url()).pathname)) publishRequests.push(request.url());
});
await chooseOpenApiPath(page);
await uploadPreview(page);
await page.locator('#openapi-import-create').click();
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
// Criterion-defining assertion: an explicit Draft chooser lists the created Drafts.
const chooser = page.getByTestId('onboarding-import-draft-choice');
await expect(chooser).toBeVisible();
await expect(chooser).toContainText(first.suggested_name);
await expect(chooser).toContainText(second.suggested_name);
// The full import report remains available and nothing is auto-published.
await expect(page.locator('#openapi-import-result')).toBeVisible();
expect(publishRequests).toEqual([]);
await expect.poll(() => registrationRequests.length).toBe(1);
expect(registrationRequests[0]).toEqual({
application_idempotency_key: report.idempotency_key,
plan_digest: report.plan_digest,
expected_revision: initial.revision,
});
expect(context.report).toEqual(report);
const chosen = page.waitForRequest((request) => request.method() === 'POST' && /\/onboarding\/select-draft$/.test(request.url()));
const firstChoice = chooser.locator('.onboarding-import-draft-option-row')
.filter({ hasText: first.suggested_name }).getByRole('button');
await firstChoice.click();
const selectedRequest = await chosen;
expect(selectedRequest.postDataJSON()).toEqual({
application_idempotency_key: report.idempotency_key,
plan_digest: report.plan_digest,
operation_id: 'op_onboarding_rates',
operation_version: 1,
expected_revision: initial.revision + 1,
});
});
test('[P1] AC-5 refresh or source correction restores the checklist from authoritative state without duplicating a version and requires a new preview for a changed digest', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const pendingReport = applyReport([
{ key: 'GET /onboarding-rates', name: 'onboarding_rates', outcome: 'created', operation_id: 'op_imported_rates', version: 1, reason: null },
{ key: 'GET /onboarding-blocked', name: 'onboarding_blocked', outcome: 'rejected', operation_id: null, version: null, reason: 'unsupported_xml_body' },
], {
idempotency_key: 'ws_default:apply:openapi_onboarding:v1',
counts: { created: 1, versioned: 0, renamed: 0, skipped: 0, excluded: 0, rejected: 1 },
});
const imported = onboardingSnapshot(workspace.id, {
revision: 9,
operation_id: null,
operation_version: null,
import_context: importContext(pendingReport),
steps: [
{ id: 'operation', completed: false, status: 'current', action_code: 'create_operation', reason_code: 'authoritative_evidence_missing' },
{ id: 'test', completed: false, status: 'pending', action_code: 'test_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'publish_operation', completed: false, status: 'pending', action_code: 'publish_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'agent', completed: false, status: 'pending', action_code: 'publish_agent', reason_code: 'prerequisite_incomplete' },
{ id: 'key', completed: false, status: 'pending', action_code: 'create_mcp_key', reason_code: 'prerequisite_incomplete' },
{ id: 'mcp_connection', completed: false, status: 'pending', action_code: 'connect_mcp_client', reason_code: 'prerequisite_incomplete' },
{ id: 'first_call', completed: false, status: 'pending', action_code: 'call_tool', reason_code: 'prerequisite_incomplete' },
],
});
await routeOnboarding(page, imported);
await page.goto('/?onboarding=1');
const checklist = page.getByTestId('onboarding-checklist');
if (!(await checklist.isVisible())) await page.getByTestId('onboarding-trigger').click();
await expect(checklist.locator('[aria-current="step"]')).toContainText(localized('Create an Operation', 'Создать операцию'));
await expect(page.getByTestId('onboarding-import-context')).toContainText('onboarding_rates');
// A full page refresh must recover the pending report and every outcome
// from the authoritative onboarding projection before explicit selection.
await page.reload();
const resumed = page.getByTestId('onboarding-checklist');
if (!(await resumed.isVisible())) await page.getByTestId('onboarding-trigger').click();
await expect(resumed.locator('[aria-current="step"]')).toContainText(localized('Create an Operation', 'Создать операцию'));
await page.getByTestId('onboarding-openapi-path').click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(page.locator('#openapi-import-result')).toBeVisible();
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcome[data-outcome="created"]')).toContainText('onboarding_rates');
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcome[data-outcome="rejected"]')).toContainText('onboarding_blocked');
const restoredChooser = page.getByTestId('onboarding-import-draft-choice');
await expect(restoredChooser).toContainText('onboarding_rates');
await expect(restoredChooser).toContainText(localized(
'This imported item needs review in the wizard.',
'Этот импортированный элемент нужно проверить в мастере.',
));
// A changed source digest yields visible 409 recovery and disables Apply
// until a fresh preview/confirmation is created.
const resumeCandidate = candidate('onboarding-rates');
await page.locator('[data-openapi-close]').last().click();
await page.getByTestId('onboarding-openapi-path').click();
await routePreview(page, previewResponse([resumeCandidate]));
await uploadPreview(page);
await routePlanCreate(page, planResponse([
{ key: resumeCandidate.key, name: resumeCandidate.suggested_name, state: 'actionable', action: 'create' },
], { plan_reference: 'plan_e2e_onboarding_215_fresh', plan_digest: 'c'.repeat(64) }));
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(resumeCandidate.suggested_name);
await page.route(/\/imports\/openapi\/plans\/[^/]+(?:\?.*)?$/, (route) => route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'import_plan_stale', message: 'Import source changed', context: { recovery: 'preview', reason: 'source_digest_changed' } } }),
}));
await page.locator('[data-testid="openapi-import-plan-reopen"]').click();
await expect(page.locator('[data-testid="openapi-import-plan-stale"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-plan-apply"]')).toBeDisabled();
await expect(page.locator('#openapi-import-status')).not.toHaveText('');
await page.locator('[data-openapi-close]').last().click();
await page.getByTestId('onboarding-openapi-path').click();
await routePreview(page, previewResponse([resumeCandidate], { job_id: 'imp_e2e_onboarding_215_recovered' }));
await uploadPreview(page);
await routePlanCreate(page, planResponse([
{ key: resumeCandidate.key, name: resumeCandidate.suggested_name, state: 'actionable', action: 'create' },
], { plan_reference: 'plan_e2e_onboarding_215_recovered', plan_digest: 'd'.repeat(64) }));
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(resumeCandidate.suggested_name);
await page.locator('[data-openapi-close]').last().click();
await page.getByTestId('onboarding-openapi-path').click();
const selectionRequests = [];
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/select-draft$/, async (route) => {
const payload = route.request().postDataJSON();
selectionRequests.push(payload);
if (selectionRequests.length === 1) {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'onboarding_stale_revision', message: 'Reload required', context: { recovery: 'reload' } } }),
});
return;
}
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(selectedResponse(imported, importContext(pendingReport), payload.operation_id, payload.operation_version)) });
});
const continueButton = page.getByTestId('onboarding-import-draft-choice').getByRole('button').first();
await continueButton.click();
await expect(page.locator('#openapi-import-status')).toContainText(/reload|latest report|state changed|обнов|измен/i);
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(continueButton).toBeVisible();
await continueButton.click();
await page.waitForURL(/\/wizard\/\?mode=edit/);
expect(selectionRequests).toHaveLength(2);
for (const payload of selectionRequests) {
expect(payload).toEqual({
application_idempotency_key: pendingReport.idempotency_key,
plan_digest: pendingReport.plan_digest,
operation_id: 'op_imported_rates',
operation_version: 1,
expected_revision: imported.revision,
});
}
});
test('[P1] AC-6 presentation event requests carry only the bounded client contract and make no external calls', async ({ page }) => {
const requests = [];
page.on('request', (request) => requests.push({ url: request.url(), postData: request.postData() }));
const workspace = await openOnboarding(page);
const actionable = candidate('onboarding-rates');
await routePreview(page, previewResponse([actionable]));
await routePlanCreate(page, planResponse([{ key: actionable.key, name: actionable.suggested_name, state: 'actionable', action: 'create' }]));
let report;
await routeApply(page, (payload) => {
report = applyReport([
{ key: actionable.key, name: actionable.suggested_name, outcome: 'created', operation_id: 'op_onboarding_rates', version: 1, reason: null },
], { idempotency_key: payload.idempotency_key, plan_digest: payload.plan_digest });
return report;
});
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/import-context$/, async (route) => {
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(registeredResponse(onboardingSnapshot(workspace.id), importContext(report))) });
});
await chooseOpenApiPath(page);
await uploadPreview(page);
await page.locator('#openapi-import-create').click();
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
// Presentation requests are client-owned UI signals with a closed payload.
const eventPosts = requests.filter((item) => /\/onboarding\/events(?:\?|$)/.test(item.url));
expect(eventPosts.length).toBeGreaterThan(0);
eventPosts.forEach((item) => {
const payload = JSON.parse(item.postData || '{}');
expect(Object.keys(payload).sort()).toEqual(['event', 'expected_revision', 'idempotency_key']);
expect(payload.event).toMatch(/^(started|resumed|dismissed|abandoned)$/);
expect(payload.idempotency_key).toMatch(/^ui:/);
expect(typeof payload.expected_revision).toBe('number');
expect(JSON.stringify(payload)).not.toContain('openapi: 3.0');
expect(JSON.stringify(payload)).not.toContain(SECRET_CANARY);
expect(Object.keys(payload)).not.toContain('user_id');
});
// ...and keep all telemetry local unless the operator opts in (no external egress).
const external = requests.filter((item) => !/^https?:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?\//.test(item.url));
expect(external).toEqual([]);
// Server-owned properties for all three funnel milestones, including the
// exact keys and raw-data exclusion, are asserted against stored PG rows by
// `crates/crank-registry/tests/integration/onboarding_import_selection.rs`.
});
for (const locale of ['ru', 'en']) {
test(`[P1] AC-7 ${locale} OpenAPI import reaches an authoritative public MCP call after selection reset`, async ({ page, request }) => {
test.setTimeout(180_000);
await login(page);
const workspace = await getCurrentWorkspace(page);
// The shared E2E admin workspace may have terminal evidence from an earlier
// suite. Reset only its canonical onboarding selection; every milestone
// below is recreated through the real import/UI/public endpoint journey.
let reset;
for (let attempt = 0; attempt < 5; attempt += 1) {
const prior = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
reset = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding/reset-selection`,
{ expected_revision: prior.revision },
[200, 409],
);
if (!reset.error) break;
expect(reset.error.code).toBe('onboarding_stale_revision');
}
expect(reset.error).toBeUndefined();
const resetProjection = reset.onboarding || reset;
expect(resetProjection.status).not.toBe('complete');
expect(resetProjection.import_context).toBeNull();
expect(resetProjection.first_call).toBeNull();
const suffix = uniqueName('openapi_onboarding').replace(/_/g, '-');
const agentSlug = `onboarding-${suffix}`.toLowerCase().replace(/[^a-z0-9-]/g, '-');
await page.goto('/?onboarding_openapi=1&return=%2F');
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.evaluate((language) => window.setLang(language), locale);
await expect(page.locator('#openapi-import-modal')).toContainText(locale === 'ru' ? 'Импорт OpenAPI' : 'Import OpenAPI');
await uploadPreview(page, representativeOpenApi(suffix));
// Import preview, atomic apply of multiple candidates, and full report are
// all exercised against the real import API.
await expect(page.locator('#openapi-import-groups')).toContainText(/list.?rates/i);
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
const importContextRequest = page.waitForRequest((r) => r.method() === 'POST' && /\/onboarding\/import-context$/.test(r.url()));
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
await expect(page.locator('#openapi-import-result')).toBeVisible();
const registration = await importContextRequest;
expect(registration.postDataJSON()).toMatchObject({
application_idempotency_key: expect.any(String),
plan_digest: expect.stringMatching(/^[a-f0-9]{64}$/),
expected_revision: expect.any(Number),
});
expect(await registration.response().then((response) => response.ok())).toBe(true);
// Reload while the import context is still pending, then recover the full
// immutable report and every selectable/non-selectable outcome from GET.
await page.reload();
const checklistAfterReload = page.getByTestId('onboarding-checklist');
if (!await checklistAfterReload.isVisible()) await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-import-context')).toContainText(/list.?rates/i);
await page.getByTestId('onboarding-openapi-path').click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(page.locator('#openapi-import-result')).toBeVisible();
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcomes')).toContainText(/list.?rates/i);
const pendingContext = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
expect(pendingContext.import_context.report.outcomes.length).toBeGreaterThan(1);
expect(pendingContext.import_context.selected_operation_id).toBeNull();
expect(pendingContext.import_context.selected_operation_version).toBeNull();
expect(pendingContext.import_context.choices).toHaveLength(2);
expect(pendingContext.import_context.choices.every((choice) => choice.selectable)).toBe(true);
expect(pendingContext.import_context.report.outcomes.map((outcome) => outcome.outcome).sort()).toEqual(['created', 'created']);
const selectedChoice = pendingContext.import_context.choices.find((choice) => /list.?rates/i.test(choice.name));
expect(selectedChoice).toBeTruthy();
const chooser = page.getByTestId('onboarding-import-draft-choice');
await expect(chooser).toBeVisible();
const draftChoice = chooser.locator('.onboarding-import-draft-choice-list .onboarding-import-draft-option-row')
.filter({ hasText: /list.?rates/i }).getByRole('button');
await expect(draftChoice).toBeVisible();
const selectDraftRequest = page.waitForRequest((r) => r.method() === 'POST' && /\/onboarding\/select-draft$/.test(r.url()));
const selectedVersionResponse = page.waitForResponse((r) => r.request().method() === 'GET'
&& r.url().includes(`/operations/${selectedChoice.operation_id}/versions/${selectedChoice.version}`));
await draftChoice.click();
const selection = await selectDraftRequest;
const loadedVersion = await selectedVersionResponse;
expect(loadedVersion.ok()).toBe(true);
const importedVersion = await loadedVersion.json();
expect(importedVersion.snapshot.target).toMatchObject({ kind: 'rest', method: 'GET', path_template: '/rates', base_url: 'http://127.0.0.1:3310' });
expect(selection.postDataJSON()).toMatchObject({
application_idempotency_key: registration.postDataJSON().application_idempotency_key,
plan_digest: registration.postDataJSON().plan_digest,
operation_id: expect.any(String),
operation_version: expect.any(Number),
expected_revision: expect.any(Number),
});
await page.waitForFunction(() => window.CrankWizardReady === true && window.currentStep === 1);
await expect(page.locator('[data-testid="wizard-protocol-rest"]')).toBeVisible();
const selectedOperationId = selection.postDataJSON().operation_id;
const selectedVersion = selection.postDataJSON().operation_version;
await expect(page).toHaveURL(new RegExp(`operationId=${selectedOperationId}`));
expect(new URL(page.url()).searchParams.get('operationVersion')).toBe(String(selectedVersion));
await expect(page.locator('#tool-name')).toHaveValue(/list.?rates/i);
const operationWrites = [];
page.on('request', (r) => {
const path = new URL(r.url()).pathname;
const createsOperation = r.method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/operations$/.test(path);
const updatesOperation = r.method() === 'PATCH' && /\/api\/admin\/workspaces\/[^/]+\/operations\/[^/]+$/.test(path);
const createsVersion = r.method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/operations\/[^/]+\/versions$/.test(path);
if (createsOperation || updatesOperation || createsVersion) operationWrites.push({ method: r.method(), url: r.url() });
});
// The selected imported Draft is edited in normal wizard edit mode. A
// no-op lifecycle save must retain its exact version without creating a
// duplicate, then test and publish that same version.
const testedVersions = [];
const publishedVersions = [];
page.on('request', (r) => {
if (r.method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/test-runs`)) {
testedVersions.push(r.postDataJSON().version);
}
if (r.method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/publish`)) {
publishedVersions.push(r.postDataJSON().version);
}
});
const testResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/test-runs`));
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
await page.locator('#wizard-run-test').click();
const tested = await testResponse;
expect(tested.ok(), await tested.text()).toBe(true);
const testResult = await tested.json();
expect(testResult.ok, JSON.stringify(testResult)).toBe(true);
await expect.poll(() => testedVersions).toEqual([selectedVersion]);
await expect(page.locator('#wizard-test-request-id')).not.toHaveText('');
page.once('dialog', (dialog) => dialog.accept());
const qualityResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes('/operations/analyze-quality'));
const publishResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/publish`));
await page.locator('#wizard-publish-operation').click();
const quality = await qualityResponse;
expect(quality.ok(), await quality.text()).toBe(true);
expect((await publishResponse).ok()).toBe(true);
await expect.poll(() => publishedVersions).toEqual([selectedVersion]);
expect(operationWrites).toEqual([]);
const agentPage = `/agents?onboarding=1&action=create&operationId=${encodeURIComponent(selectedOperationId)}&operationVersion=${selectedVersion}`;
await page.goto(agentPage);
await expect(page.locator('.drawer')).toHaveClass(/open/);
const identityInputs = page.locator('.drawer-section').first().locator('input.form-input');
await identityInputs.nth(0).fill('OpenAPI onboarding Agent');
await identityInputs.nth(1).fill(agentSlug);
await page.locator('.drawer-section').first().locator('textarea').fill('Agent created from an explicitly selected OpenAPI Draft.');
await expect(page.locator('.ops-picker-item.selected')).toContainText(/list.?rates/i);
const createAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/agents$/.test(r.url()));
const bindAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/agents\/[^/]+\/bindings$/.test(r.url()));
const publishAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/agents\/[^/]+\/publish$/.test(r.url()));
await page.locator('.drawer-footer .btn-primary-sm').click();
const agentResponse = await createAgentResponse;
expect(agentResponse.ok(), await agentResponse.text()).toBe(true);
expect((await bindAgentResponse).ok()).toBe(true);
expect((await publishAgentResponse).ok()).toBe(true);
const agentId = (await agentResponse.json()).agent_id;
await page.goto(`/api-keys?onboarding=1&action=create&agentId=${encodeURIComponent(agentId)}`);
await expect(page.locator('#agent-select')).toHaveValue(agentId);
await expect(page.locator('#modal-create')).toHaveClass(/open/);
await page.locator('#new-key-name').fill(uniqueName('openapi_onboarding_key'));
const keyResponsePromise = page.waitForResponse((r) => r.request().method() === 'POST' && /\/platform-api-keys$/.test(r.url()));
await page.locator('#modal-confirm-btn').click();
const keyResponse = await keyResponsePromise;
expect(keyResponse.ok(), await keyResponse.text()).toBe(true);
const keyBody = await keyResponse.json();
const rawKey = await page.locator('#reveal-key-value').textContent();
const keyId = keyBody.api_key.id || keyBody.api_key.api_key.id;
const endpoint = await page.locator('#onboarding-connection-clients > code').textContent();
expect(rawKey).toMatch(/^crk_/);
await expect(page.locator('body')).not.toContainText(SECRET_CANARY);
// An unauthorized public call must not advance the authoritative checklist.
const denied = await mcpPost(request, endpoint, SECRET_CANARY, {
jsonrpc: '2.0', id: 90, method: 'tools/call', params: { name: 'unavailable', arguments: {} },
});
expect([401, 403]).toContain(denied.status());
const beforeSuccessfulCall = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
expect(beforeSuccessfulCall.status).not.toBe('complete');
expect(beforeSuccessfulCall.first_call).toBeNull();
const initialize = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', id: 1, method: 'initialize', params: {
protocolVersion: '2025-06-18', capabilities: {},
clientInfo: { name: 'crank-openapi-onboarding-playwright', version: '1.0.0' },
},
});
const initializeBody = await parseMcpResponse(initialize);
expect(initialize.ok(), JSON.stringify(initializeBody)).toBe(true);
const sessionId = initialize.headers()['mcp-session-id'];
expect(sessionId).toBeTruthy();
const initialized = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', method: 'notifications/initialized', params: {},
}, sessionId);
expect([200, 202]).toContain(initialized.status());
const listed = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', id: 2, method: 'tools/list', params: {},
}, sessionId);
expect(listed.ok()).toBe(true);
const listedBody = await parseMcpResponse(listed);
const selectedTool = listedBody.result.tools.find((tool) => /list.?rates/i.test(tool.name));
expect(selectedTool).toBeTruthy();
const toolName = selectedTool.name;
const called = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: toolName, arguments: {} },
}, sessionId);
expect(called.ok()).toBe(true);
const calledBody = await parseMcpResponse(called);
expect(calledBody.error).toBeUndefined();
expect(calledBody.result.isError).not.toBe(true);
const progress = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
expect(progress.status).toBe('complete');
expect(progress.operation_id).toBe(selectedOperationId);
expect(progress.operation_version).toBe(selectedVersion);
expect(progress.agent_id).toBe(agentId);
expect(progress.platform_api_key_id).toBe(keyId);
expect(progress.first_call.agent_id).toBe(agentId);
expect(progress.first_call.key_id).toBe(keyId);
expect(progress.first_call.operation_id).toBe(selectedOperationId);
expect(progress.first_call.operation_version).toBe(selectedVersion);
expect(progress.first_call.tool_name).toBe(toolName);
expect(progress.first_call.request_id).toBeTruthy();
expect(progress.first_call.trace_id).toMatch(/^[0-9a-f]{32}$/);
await page.goto('/');
await expect(page.getByTestId('onboarding-trigger')).toContainText(/7\s*\/\s*7/);
await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-completion')).toContainText(toolName);
await expect(page.getByTestId('onboarding-completion')).toContainText(progress.first_call.request_id);
await page.evaluate((language) => window.setLang(language), locale);
await expect(page.getByTestId('onboarding-completion')).toBeVisible();
await page.reload();
await expect(page.getByTestId('onboarding-trigger')).toContainText(/7\s*\/\s*7/);
});
}
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,273 @@
// Operator-run AC-11 evidence against a Reference Deployment. This spec is
// intentionally separate from the local/mocked Playwright matrix.
const fs = require('node:fs');
const { test, expect } = require('@playwright/test');
const { localized, login } = require('./helpers');
// Remote operator credentials must not enter retry artifacts or failure captures.
test.use({ trace: 'off', video: 'off', screenshot: 'off' });
test.describe.configure({ retries: 0 });
const referenceBaseUrl = process.env.PLAYWRIGHT_BASE_URL;
const SAMPLE_COUNT = 20;
const OPERATION_COUNT = 2000;
const MAX_UPLOAD_BYTES = 256 * 1024;
const MAX_P95_MS = 2000;
function openApiDocument(operationCount) {
const lines = [
'openapi: 3.0.3',
'info:',
' title: Crank Reference Preview Benchmark',
' version: "1.0.0"',
'servers:',
' - url: https://api.example.test',
'paths:',
];
for (let index = 0; index < operationCount; index += 1) {
lines.push(` /op-${index}:`);
lines.push(' get:');
lines.push(' responses:');
lines.push(' "200":');
lines.push(' description: OK');
}
return Buffer.from(lines.join('\n') + '\n', 'utf8');
}
function percentile95(samples) {
const sorted = [...samples].sort((left, right) => left - right);
return sorted[Math.ceil(sorted.length * 0.95) - 1];
}
function safeReferenceOrigin(rawUrl) {
const url = new URL(rawUrl);
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error('PLAYWRIGHT_BASE_URL must use http or https');
}
if (url.username || url.password || url.search || url.hash) {
throw new Error('PLAYWRIGHT_BASE_URL must not contain credentials, query parameters, or fragments');
}
if (['localhost', '127.0.0.1', '::1'].includes(url.hostname)) {
throw new Error('AC-11 Reference benchmark requires a remote PLAYWRIGHT_BASE_URL');
}
return url.origin;
}
function readReferenceManifest(manifestPath) {
if (!manifestPath) {
throw new Error('CRANK_AC11_REFERENCE_ENV_JSON is required when PLAYWRIGHT_BASE_URL is set');
}
let manifest;
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (_error) {
throw new Error('CRANK_AC11_REFERENCE_ENV_JSON must point to a readable valid JSON manifest');
}
const deployment = manifest && manifest.deployment;
const loadGenerator = manifest && manifest.load_generator;
const browser = manifest && manifest.browser;
const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
const finiteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
const versionHasMajor = (value, major) => nonempty(value) && new RegExp(`^${major}(?:\\.|$)`).test(value.trim());
if (!deployment || !loadGenerator || !browser) {
throw new Error('Reference manifest requires deployment, load_generator, and browser objects');
}
for (const [name, host] of [['deployment', deployment], ['load_generator', loadGenerator], ['browser', browser]]) {
if (!nonempty(host.host_id)) throw new Error(`Reference manifest ${name}.host_id is required`);
}
if (deployment.host_id.trim() === loadGenerator.host_id.trim()
|| deployment.host_id.trim() === browser.host_id.trim()) {
throw new Error('Reference manifest requires deployment and load generator/browser on separate hosts');
}
if (!nonempty(deployment.cpu_model) || !nonempty(deployment.storage_type)
|| deployment.storage_type.trim().toLowerCase() !== 'ssd'
|| !finiteNumber(deployment.cpu_cores)
|| !finiteNumber(deployment.ram_gib) || !finiteNumber(deployment.ssd_iops)
|| !finiteNumber(deployment.ssd_throughput_mb_s) || !finiteNumber(deployment.ssd_capacity_gb)
|| !finiteNumber(deployment.lan_mbps)
|| !versionHasMajor(deployment.postgres_version, 16)
|| !versionHasMajor(deployment.valkey_version, 8)) {
throw new Error('Reference manifest is missing valid CPU, RAM, database, SSD, or LAN fields');
}
if (deployment.cpu_cores !== 4 || deployment.ram_gib !== 8
|| deployment.ssd_capacity_gb < 100 || deployment.ssd_iops < 3000
|| deployment.ssd_throughput_mb_s < 100
|| deployment.lan_mbps < 1000) {
throw new Error('Reference deployment must meet 4 CPU / 8 GiB RAM, SSD 3000 IOPS / 100 MB/s, and 1 Gbit LAN');
}
if (!finiteNumber(loadGenerator.cpu_cores) || !finiteNumber(loadGenerator.ram_gib)
|| loadGenerator.cpu_cores !== 4 || loadGenerator.ram_gib !== 8) {
throw new Error('Reference load_generator must have 4 CPU and 8 GiB RAM');
}
// Emit only the fields needed for benchmark interpretation. Do not copy
// arbitrary manifest keys (which could contain credentials) into reports.
return {
provenance: 'operator_manifest',
deployment: {
cpu_model: deployment.cpu_model.trim(),
cpu_cores: deployment.cpu_cores,
ram_gib: deployment.ram_gib,
postgres_version: deployment.postgres_version.trim(),
valkey_version: deployment.valkey_version.trim(),
storage_type: 'SSD',
ssd_capacity_gb: deployment.ssd_capacity_gb,
ssd_iops: deployment.ssd_iops,
ssd_throughput_mb_s: deployment.ssd_throughput_mb_s,
lan_mbps: deployment.lan_mbps,
},
load_generator: { cpu_cores: loadGenerator.cpu_cores, ram_gib: loadGenerator.ram_gib },
browser_host_separate_from_deployment: true,
};
}
test('[P1][reference] AC-11 measures 20 real 2000-operation preview round trips', async ({ page }, testInfo) => {
test.skip(!referenceBaseUrl, 'Set PLAYWRIGHT_BASE_URL to a Reference Deployment to run AC-11 evidence');
test.setTimeout(300_000);
expect(process.env.PLAYWRIGHT_SKIP_WEB_SERVER).toBe('1');
const referenceOrigin = safeReferenceOrigin(referenceBaseUrl);
const referenceManifest = readReferenceManifest(process.env.CRANK_AC11_REFERENCE_ENV_JSON);
const yaml = openApiDocument(OPERATION_COUNT);
expect(yaml.byteLength).toBeLessThan(MAX_UPLOAD_BYTES);
await login(page);
await page.waitForFunction(() => Boolean(document.querySelector('[data-testid="onboarding-dismiss"]')));
await page.locator('[data-testid="onboarding-dismiss"]').click();
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
await page.evaluate(() => window.setLang('en'));
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.locator('#openapi-import-file').setInputFiles({
name: 'reference-preview-2000.yaml',
mimeType: 'application/yaml',
buffer: yaml,
});
const previewButton = page.locator('#openapi-import-preview');
const createButton = page.locator('#openapi-import-create');
const rows = page.locator('.openapi-import-operation');
const samplesMs = [];
let browserEnvironment;
// Warm the preview once before timing. Warm-up still uses the real remote
// preview API.
const warmupResponsePromise = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await previewButton.click();
const warmupResponse = await warmupResponsePromise;
expect(warmupResponse.status(), 'warm-up preview status').toBe(200);
expect(new URL(warmupResponse.url()).origin).toBe(referenceOrigin);
await expect(page.locator('[data-testid="openapi-import-page-status"]')).toContainText('2000');
await expect(createButton).toBeEnabled();
const previewResponses = [];
page.on('response', (response) => {
if (response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview')) {
previewResponses.push({ status: response.status(), url: response.url() });
}
});
for (let sampleIndex = 0; sampleIndex < SAMPLE_COUNT; sampleIndex += 1) {
await expect(previewButton).toBeEnabled();
await page.evaluate((index) => {
const measurements = window.__ac11Measurements || (window.__ac11Measurements = []);
const sample = { start: null, elapsed: null };
measurements[index] = sample;
const ready = () => {
const panel = document.querySelector('#openapi-import-preview-panel');
const button = document.querySelector('#openapi-import-preview');
const status = document.querySelector('[data-testid="openapi-import-page-status"]');
const create = document.querySelector('#openapi-import-create');
const rowCount = document.querySelectorAll('.openapi-import-operation').length;
if (sample.start === null || !button || button.disabled || !panel || panel.hidden
|| !status || !status.textContent.includes('2000') || !create || create.disabled
|| rowCount < 1 || rowCount > 100) return;
sample.elapsed = Number((performance.now() - sample.start).toFixed(3));
observer.disconnect();
};
const observer = new MutationObserver(ready);
observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
document.addEventListener('click', (event) => {
if (event.target.closest('#openapi-import-preview')) sample.start = performance.now();
}, { capture: true, once: true });
}, sampleIndex);
const responsePromise = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await previewButton.click();
const previewResponse = await responsePromise;
expect(previewResponse.status(), `preview sample ${sampleIndex + 1} status`).toBe(200);
expect(new URL(previewResponse.url()).origin).toBe(referenceOrigin);
await page.waitForFunction((index) => {
const sample = window.__ac11Measurements && window.__ac11Measurements[index];
return sample && sample.elapsed !== null;
}, sampleIndex, { polling: 'raf' });
const elapsed = await page.evaluate((index) => window.__ac11Measurements[index].elapsed, sampleIndex);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-page-status"]')).toContainText('2000');
await expect(rows.first()).toBeVisible();
expect(await rows.count()).toBeGreaterThan(0);
expect(await rows.count()).toBeLessThanOrEqual(100);
await expect(createButton).toBeEnabled();
samplesMs.push(elapsed);
browserEnvironment = await page.evaluate(() => ({
user_agent: navigator.userAgent,
platform: navigator.platform,
language: navigator.language,
hardware_concurrency: navigator.hardwareConcurrency || null,
viewport: { width: innerWidth, height: innerHeight },
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}));
}
expect(previewResponses).toHaveLength(SAMPLE_COUNT);
expect(previewResponses.every((item) => item.status === 200)).toBe(true);
const p95Ms = percentile95(samplesMs);
const report = {
benchmark: 'story-2.12-ac-11-reference-preview',
generated_at: new Date().toISOString(),
result: { sample_count: samplesMs.length, p95_ms: p95Ms, threshold_ms: MAX_P95_MS },
workload: {
operations: OPERATION_COUNT,
yaml_bytes: yaml.byteLength,
max_yaml_bytes: MAX_UPLOAD_BYTES,
preview_http_statuses: previewResponses.map((item) => item.status),
rendered_operation_rows: await rows.count(),
max_rendered_operation_rows: 100,
enabled_interaction: 'Create button enabled after preview',
interaction_enabled: true,
measurement_scope: 'click through real HTTP request, parsing, populated first page, and enabled Create button',
},
samples_ms: samplesMs,
environment: {
reference_origin: referenceOrigin,
playwright_base_url_configured: true,
playwright_skip_web_server: process.env.PLAYWRIGHT_SKIP_WEB_SERVER === '1',
node_version: process.version,
os_platform: process.platform,
os_arch: process.arch,
browser: browserEnvironment,
reference_manifest: referenceManifest,
},
};
const rawReport = JSON.stringify(report, null, 2);
await testInfo.attach('ac11-reference-preview-report.json', {
body: Buffer.from(rawReport),
contentType: 'application/json',
});
console.log('AC11_REFERENCE_PREVIEW_REPORT ' + JSON.stringify(report));
expect(p95Ms, 'Reference preview p95 must be at most 2 seconds').toBeLessThanOrEqual(MAX_P95_MS);
});
@@ -0,0 +1,979 @@
const { test, expect } = require('@playwright/test');
const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
const operationKey = 'get:/protected';
const profileId = 'auth_profile_safe_bearer';
const secretCanary = 'SECRET_CANARY_do_not_render_or_store';
function securityPreview() {
return {
job_id: 'job_security_mapping_atdd',
expires_at: '2099-01-01T00:00:00Z',
preview: {
source: { servers: ['https://api.example.test'] },
findings: [],
groups: [{
title: 'protected operations',
operations: [{
key: operationKey,
method: 'GET',
path: '/protected',
suggested_name: 'protected_operation',
suggested_display_name: 'Protected operation',
input_fields: 0,
output_fields: 0,
draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } },
findings: [{
code: 'unsupported_security_scheme',
severity: 'warning',
message: 'Unsupported scheme details are intentionally opaque',
construct_id: 'security_scheme_unsupported',
location: { path: '/paths/~1protected/get/security' },
operation_key: operationKey,
}],
security_requirements: {
source: 'document',
alternatives: [
{ schemes: ['bearerAuth'], supported: true, findings: [] },
{ schemes: [], supported: true, findings: [] },
{ schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
],
},
}],
}],
},
security_profile_choices: [
{
operation_key: operationKey,
alternative_index: 0,
schemes: ['bearerAuth'],
profiles: [{ id: profileId, name: 'Production bearer', kind: 'bearer' }],
},
],
};
}
function protectedOperation(key, suggestedName, alternatives) {
return {
key,
method: 'GET',
path: '/' + key.split('/').pop(),
suggested_name: suggestedName,
suggested_display_name: suggestedName,
input_fields: 0,
output_fields: 0,
draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } },
findings: [],
security_requirements: { source: 'document', alternatives },
};
}
function previewWith(operations, choices) {
return {
job_id: 'job_security_multi_atdd',
expires_at: '2099-01-01T00:00:00Z',
preview: {
source: { servers: ['https://api.example.test'] },
findings: [],
groups: [{ title: 'protected operations', operations }],
},
security_profile_choices: choices,
};
}
async function dismissOnboardingIfOpen(page) {
// Same harness hygiene as openapi-import-plan.spec.js and operations.spec.js:
// the overlay intercepts pointer events on a fresh E2E stack.
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
await page.evaluate(() => {
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
if (dismiss) dismiss.click();
});
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
async function openSecurityPreview(page, locale = 'en', previewPayload = securityPreview()) {
// Register the preview boundary before navigation so the upload is deterministic.
await page.route('**/imports/openapi/preview', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(previewPayload),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.evaluate((language) => window.setLang(language), locale);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'security-mapping.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
});
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
}
function actionablePlan(decision) {
return {
plan_reference: 'plan_security_mapping_atdd',
plan_digest: 'c'.repeat(64),
expires_at: '2099-01-01T00:00:00Z',
selection_mode: 'full',
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
candidates: [{
key: operationKey,
name: 'protected_operation',
state: 'actionable',
action: decision.action,
target_operation_id: null,
confirmed_name: null,
auth_profile_id: decision.auth_profile_id || null,
security_alternative_index: decision.security_alternative_index,
reason: null,
}],
};
}
function containsCredentialField(value) {
if (!value || typeof value !== 'object') return false;
return Object.entries(value).some(([key, nested]) =>
/^(password|access_token|refresh_token|secret_value|credential_value|raw_credentials?)$/i.test(key)
|| containsCredentialField(nested));
}
test('[P1] AC-1 sends the selected OR alternative and Auth Profile, then renders API authority', async ({ page }) => {
// Given an OpenAPI preview with OR security choices and safe workspace profile metadata
const planRequests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
planRequests.push(payload);
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
});
await openSecurityPreview(page);
// When an administrator selects a supported alternative and its compatible profile
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
await page.locator('#openapi-import-create').click();
// Then the existing plan API receives only the typed profile reference and alternative index
await expect.poll(() => planRequests.length).toBe(1);
expect(planRequests[0].decisions[0]).toMatchObject({
operation_key: operationKey,
auth_profile_id: profileId,
security_alternative_index: 0,
});
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено'));
expect(JSON.stringify(planRequests[0])).not.toContain(secretCanary);
expect(containsCredentialField(planRequests[0])).toBe(false);
});
test('[P1] AC-2 replaces a prior resolved plan with a blocker after profile revalidation fails', async ({ page }) => {
// Given an API-confirmed resolved plan for a profile that becomes unavailable before revalidation
const planRequests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
planRequests.push(payload);
if (planRequests.length === 1) {
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
return;
}
await route.fulfill({
status: 422,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }),
});
});
await openSecurityPreview(page);
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
// When the API first confirms the selection and then rejects the stale profile
await page.locator('#openapi-import-create').click();
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено'));
await page.locator('#openapi-import-plan-back').click();
await page.locator('#openapi-import-create').click();
// Then the old resolved value is replaced by the exact API-authoritative blocker state
await expect.poll(() => planRequests.length).toBe(2);
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано'));
await expect(page.locator('body')).not.toContainText(secretCanary);
expect(planRequests[0].decisions[0]).toMatchObject({ auth_profile_id: profileId, security_alternative_index: 0 });
});
test('[P1] AC-3 shows safe security guidance in RU and EN without exposing error or secret canaries', async ({ page }) => {
// Given safe profile metadata and an unsupported AND alternative in the preview
let previewCalls = 0;
await page.route('**/imports/openapi/preview', async (route) => {
previewCalls += 1;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(securityPreview()) });
});
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
status: 422,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'import_plan_security_alternative_required', message: secretCanary } }),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.evaluate(() => window.setLang('ru'));
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'security-mapping.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
});
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
// When the administrator inspects both locales, the unsupported AND alternative is visible but disabled
// Native option elements are not visually visible inside a select; the safe
// metadata must be present and selectable.
await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).locator('option[value="' + profileId + '"]')).toBeAttached();
await expect(page.getByLabel(localized('Security alternative', 'Вариант безопасности')).locator('option[value="2"]')).toHaveAttribute('disabled', '');
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
await page.locator('#openapi-import-create').click();
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано'));
await expect(page.locator('body')).not.toContainText(secretCanary);
await page.evaluate(() => window.setLang('en'));
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await page.locator('#openapi-import-retry').click();
await expect.poll(() => previewCalls).toBe(2);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
// A fresh preview resets the selection, so the operation is required again,
// never a leftover unresolved/resolved binding from the rejected plan.
await expect(page.getByTestId('openapi-security-status')).toHaveText(
localized('Authentication required', 'Требуется аутентификация'),
);
await expect(page.locator('body')).not.toContainText(secretCanary);
const exposed = await page.evaluate(() => ({
html: document.documentElement.innerText,
local: JSON.stringify(localStorage),
session: JSON.stringify(sessionStorage),
}));
expect(JSON.stringify(exposed)).not.toContain(secretCanary);
});
/* ── Mandatory matrix branches (green phase) ─────────────────────────── */
test('[P1] anonymous alternative submits only the OR index, never an unrequested profile', async ({ page }) => {
const planRequests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
planRequests.push(payload);
const decision = payload.decisions[0];
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(actionablePlan({
action: decision.action,
auth_profile_id: decision.auth_profile_id || null,
security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index,
})),
});
});
await openSecurityPreview(page, 'en');
// The anonymous (empty-scheme) alternative is selectable; selecting it must
// keep the profile unbound.
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
await alternative.selectOption('1');
// The anonymous alternative must not offer any Auth Profile control.
await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0);
await page.locator('#openapi-import-create').click();
await expect.poll(() => planRequests.length).toBe(1);
const decision = planRequests[0].decisions[0];
expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 });
expect(decision).not.toHaveProperty('auth_profile_id');
// A confirmed anonymous alternative is no-auth, never a resolved auth binding.
await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication');
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации'));
expect(JSON.stringify(planRequests[0])).not.toContain(profileId);
});
test('[P1] changing the alternative clears the profile and invalidates a prior plan', async ({ page }) => {
const planRequests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
planRequests.push(payload);
const decision = payload.decisions[0];
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(actionablePlan({
action: decision.action,
auth_profile_id: decision.auth_profile_id || null,
security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index,
})),
});
});
await openSecurityPreview(page, 'en');
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
await alternative.selectOption('0');
await profile.selectOption(profileId);
// A confirmed plan exists for (alternative 0, profile).
await page.locator('#openapi-import-create').click();
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
// Back to editing: the selection survives, the plan does not.
await page.locator('#openapi-import-plan-back').click();
await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden();
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
// Switching the alternative drops the bound profile; the anonymous choice
// hides the profile control entirely and the new plan carries only the index.
await alternative.selectOption('1');
await expect(profile).toHaveCount(0);
await page.locator('#openapi-import-create').click();
await expect.poll(() => planRequests.length).toBe(2);
const decision = planRequests[1].decisions[0];
expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 });
expect(decision).not.toHaveProperty('auth_profile_id');
await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication');
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации'));
});
test('[P1] empty compatible-profile list keeps the selection safe and the API blocker authoritative', async ({ page }) => {
const emptyPreview = securityPreview();
emptyPreview.security_profile_choices = [];
const planRequests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
planRequests.push(route.request().postDataJSON());
// Actual public contract: a 200 plan whose candidate is blocked with the
// safe reason the API owns, not a synthesized top-level error code.
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_empty_profiles_atdd',
plan_digest: 'f'.repeat(64),
expires_at: '2099-01-01T00:00:00Z',
selection_mode: 'full',
counts: { selected: 1, excluded: 0, actionable: 0, blocked: 1 },
candidates: [{
key: operationKey,
name: 'protected_operation',
state: 'blocked',
action: 'create',
target_operation_id: null,
confirmed_name: null,
auth_profile_id: null,
security_alternative_index: 0,
reason: 'auth_profile_required',
}],
}),
});
});
await openSecurityPreview(page, 'en', emptyPreview);
// The empty compatible-profile list disables the profile control and shows
// safe localized guidance instead of offering an arbitrary error payload.
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
await expect(profileSelect.locator('option')).toHaveCount(1);
await alternative.selectOption('0');
await expect(profileSelect).toBeDisabled();
await expect(page.locator('.openapi-import-security-guidance')).toHaveText(
'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.');
await page.locator('#openapi-import-create').click();
await expect.poll(() => planRequests.length).toBe(1);
expect(planRequests[0].decisions[0]).toMatchObject({
operation_key: operationKey,
security_alternative_index: 0,
});
expect(planRequests[0].decisions[0]).not.toHaveProperty('auth_profile_id');
// The API candidate is authoritative: blocked, with safe translated guidance.
await expect(page.locator('.openapi-import-security-op-status')).toHaveText('Blocked');
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
await expect(page.locator('.openapi-import-plan-reason')).toHaveText(
'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.');
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
});
test('[P2] security controls keep accessible names, keyboard focus and a live status', async ({ page }) => {
await openSecurityPreview(page, 'en');
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
await expect(alternative).toBeEditable();
await expect(profile).toBeEditable();
// Keyboard-only selection: focus the native select and change it with keys,
// never programmatically.
await alternative.focus();
expect(await alternative.evaluate((el) => el === document.activeElement)).toBe(true);
await alternative.press('ArrowDown');
await expect(alternative).toHaveValue('0');
await profile.focus();
expect(await profile.evaluate((el) => el === document.activeElement)).toBe(true);
await profile.press('ArrowDown');
await expect(profile).toHaveValue(profileId);
const status = page.getByTestId('openapi-security-status');
await expect(status).toHaveAttribute('role', 'status');
await expect(status).toHaveAttribute('aria-live', 'polite');
const opStatus = page.locator('.openapi-import-security-op-status');
await expect(opStatus).toHaveAttribute('role', 'status');
await expect(opStatus).toHaveAttribute('aria-live', 'polite');
await page.locator('body').press('Escape');
await expect(page.locator('#openapi-import-modal')).toBeHidden();
});
test('[P1] a delayed preview response cannot restore state after the user cancelled', async ({ page }) => {
let releasePreview;
const previewReleased = new Promise((resolve) => {
releasePreview = resolve;
});
let previewFulfilled = false;
await page.route('**/imports/openapi/preview', async (route) => {
await previewReleased;
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(securityPreview()),
});
previewFulfilled = true;
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.evaluate(() => window.setLang('en'));
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'security-mapping.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
});
const previewRequest = page.waitForRequest((request) =>
request.method() === 'POST' && request.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
await previewRequest;
await page.locator('#openapi-import-cancel').click();
// Release the stale response and wait for the handler to settle instead of a
// fixed timeout, then prove it could not restore the panel.
releasePreview();
await expect.poll(() => previewFulfilled).toBe(true);
await expect(page.locator('#openapi-import-preview-panel')).toBeHidden();
await expect(page.locator('#openapi-import-cancel')).toBeHidden();
});
/* ── Per-operation authority and selection lifecycle ────────────────── */
test('[P1] offers only profiles compatible with the chosen OR alternative and hides them for anonymous', async ({ page }) => {
const key = 'get:/multi';
await openSecurityPreview(page, 'en', previewWith([
protectedOperation(key, 'multi_operation', [
{ schemes: ['bearerAuth'], supported: true, findings: [] },
{ schemes: ['basicAuth'], supported: true, findings: [] },
{ schemes: [], supported: true, findings: [] },
{ schemes: ['oauthAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
]),
], [
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] },
{ operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] },
]));
const row = page.locator('.openapi-import-operation').filter({ hasText: 'multi_operation' });
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
// Profile-first selection may offer the safe union while no alternative is chosen.
await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached();
await expect(profile.locator('option[value="prof_basic"]')).toBeAttached();
await expect(alternative.locator('option[value="3"]')).toHaveAttribute('disabled', '');
await alternative.selectOption('0');
await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached();
await expect(profile.locator('option[value="prof_basic"]')).toHaveCount(0);
await alternative.selectOption('1');
await expect(profile.locator('option[value="prof_basic"]')).toBeAttached();
await expect(profile.locator('option[value="prof_bearer"]')).toHaveCount(0);
// An anonymous alternative must offer no profile control at all.
await alternative.selectOption('2');
await expect(row.locator('.openapi-import-security-controls select')).toHaveCount(1);
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0);
});
test('[P1] reports per-operation resolved and blocked authority for a mixed plan', async ({ page }) => {
const keyA = 'get:/alpha';
const keyB = 'get:/beta';
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_multi_mixed_atdd',
plan_digest: 'd'.repeat(64),
expires_at: '2099-01-01T00:00:00Z',
selection_mode: 'full',
counts: { selected: 2, excluded: 0, actionable: 1, blocked: 1 },
candidates: [
{ key: keyA, name: 'alpha_operation', state: 'actionable', action: 'create', auth_profile_id: 'prof_a', security_alternative_index: 0, reason: null },
{ key: keyB, name: 'beta_operation', state: 'blocked', action: 'create', auth_profile_id: 'prof_b', security_alternative_index: 0, reason: 'auth_profile_required' },
],
}),
});
});
await openSecurityPreview(page, 'en', previewWith([
protectedOperation(keyA, 'alpha_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
protectedOperation(keyB, 'beta_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
], [
{ operation_key: keyA, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_a', name: 'A profile', kind: 'bearer' }] },
{ operation_key: keyB, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_b', name: 'B profile', kind: 'bearer' }] },
]));
// Before the plan both protected operations require an explicit binding.
await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required');
const rowA = page.locator('.openapi-import-operation').filter({ hasText: 'alpha_operation' });
const rowB = page.locator('.openapi-import-operation').filter({ hasText: 'beta_operation' });
await rowA.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await rowA.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_a');
await rowB.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await rowB.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_b');
await page.locator('#openapi-import-create').click();
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
await expect(page.locator('[data-openapi-security-op-status="' + keyA + '"]')).toHaveText('Resolved');
await expect(page.locator('[data-openapi-security-op-status="' + keyB + '"]')).toHaveText('Blocked');
// The summary must surface the blocked operation, not mask it behind a resolved one.
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
});
test('[P1] editing the alternative after an authoritative blocker clears the blocked authority', async ({ page }) => {
const key = 'get:/reset';
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
status: 422,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }),
});
});
await openSecurityPreview(page, 'en', previewWith([
protectedOperation(key, 'reset_operation', [
{ schemes: ['bearerAuth'], supported: true, findings: [] },
{ schemes: ['basicAuth'], supported: true, findings: [] },
]),
], [
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] },
{ operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] },
]));
const row = page.locator('.openapi-import-operation').filter({ hasText: 'reset_operation' });
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_bearer');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Blocked');
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
// Editing must void the blocked authority and clear the bound profile.
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('1');
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveValue('');
await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Authentication required');
await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required');
await expect(page.locator('body')).not.toContainText(secretCanary);
});
test('[P1] binding then choosing skip removes the auth fields from the plan payload', async ({ page }) => {
const suggestedName = 'protected_operation';
const planRequests = [];
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
items: [{ id: 'op_skip_target', name: suggestedName, protocol: 'rest', status: 'draft' }],
page: 1,
page_size: 1,
total: 1,
}),
});
});
await page.route('**/imports/openapi/*/plans', async (route) => {
planRequests.push(route.request().postDataJSON());
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_skip_atdd',
plan_digest: 'e'.repeat(64),
expires_at: '2099-01-01T00:00:00Z',
selection_mode: 'full',
counts: { selected: 1, excluded: 0, actionable: 0, blocked: 0 },
candidates: [{
key: operationKey,
name: suggestedName,
state: 'excluded',
action: 'skip',
target_operation_id: 'op_skip_target',
confirmed_name: null,
auth_profile_id: null,
security_alternative_index: null,
reason: 'skipped',
}],
}),
});
});
await openSecurityPreview(page, 'en');
const row = page.locator('.openapi-import-operation').filter({ hasText: suggestedName });
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
await row.locator('[data-openapi-decision-action]').selectOption('skip');
await expect(row.locator('.openapi-import-security-controls')).toHaveCount(0);
await page.locator('#openapi-import-create').click();
await expect.poll(() => planRequests.length).toBe(1);
const decision = planRequests[0].decisions[0];
expect(decision).toMatchObject({ operation_key: operationKey, action: 'skip', target_operation_id: 'op_skip_target' });
expect(decision).not.toHaveProperty('auth_profile_id');
expect(decision).not.toHaveProperty('security_alternative_index');
});
test('[P1] language change during a pending Apply keeps security controls disabled', async ({ page }) => {
let releaseApply;
const applyHeld = new Promise((resolve) => {
releaseApply = resolve;
});
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
});
await page.route('**/imports/openapi/*/apply', async (route) => {
await applyHeld;
try {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_digest: 'c'.repeat(64),
counts: { created: 1 },
outcomes: [{ key: operationKey, name: 'protected_operation', status: 'created' }],
}),
});
} catch (_error) {
// The context change aborts the request; it must not update the modal.
}
});
await openSecurityPreview(page, 'en');
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
await alternative.selectOption('0');
await profile.selectOption(profileId);
await page.locator('#openapi-import-create').click();
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
await page.locator('#openapi-import-plan-apply').click();
await expect(alternative).toBeDisabled();
// A language change while Apply is in flight must not re-render and re-enable
// the security controls.
await page.evaluate(() => window.setLang('ru'));
await expect(alternative).toBeDisabled();
await expect(profile).toBeDisabled();
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
releaseApply();
});
test('[P1] a rejected Apply clears a previously resolved security authority', async ({ page }) => {
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
});
await page.route('**/imports/openapi/*/apply', async (route) => {
await route.fulfill({
status: 422,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary }, recovery: 'repreview_required' }),
});
});
await openSecurityPreview(page, 'en');
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
await page.locator('#openapi-import-create').click();
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
await page.locator('#openapi-import-plan-apply').click();
// The rejected Apply must not retain the prior resolved authority.
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
await expect(page.locator('body')).not.toContainText(secretCanary);
});
test('[P1] a delayed plan response cannot restore authority after cancel', async ({ page }) => {
let releasePlan;
const planHeld = new Promise((resolve) => {
releasePlan = resolve;
});
let planFulfilled = false;
await page.route('**/imports/openapi/*/plans', async (route) => {
await planHeld;
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })),
});
planFulfilled = true;
});
await openSecurityPreview(page, 'en');
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
const planRequest = page.waitForRequest((request) =>
request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()));
await page.locator('#openapi-import-create').click();
await planRequest;
await page.locator('#openapi-import-cancel').click();
releasePlan();
await expect.poll(() => planFulfilled).toBe(true);
await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden();
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
});
test('[P1] a quoted or backslash operation key cannot break per-operation status', async ({ page }) => {
const key = 'get:/quoted"path\\segment';
const planRequests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
planRequests.push(route.request().postDataJSON());
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_quoted_key_atdd',
plan_digest: 'a'.repeat(64),
expires_at: '2099-01-01T00:00:00Z',
selection_mode: 'full',
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
candidates: [{
key,
name: 'quoted_operation',
state: 'actionable',
action: 'create',
target_operation_id: null,
confirmed_name: null,
auth_profile_id: profileId,
security_alternative_index: 0,
reason: null,
}],
}),
});
});
await openSecurityPreview(page, 'en', previewWith([
protectedOperation(key, 'quoted_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
], [
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: profileId, name: 'Bearer profile', kind: 'bearer' }] },
]));
// Rendering a CSS-hostile key must not throw and the preview must render.
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
const row = page.locator('.openapi-import-operation').filter({ hasText: 'quoted_operation' });
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
await page.locator('#openapi-import-create').click();
await expect.poll(() => planRequests.length).toBe(1);
expect(planRequests[0].decisions[0].operation_key).toBe(key);
// Status is matched by dataset value, never by interpolating the key into CSS.
await expect(row.locator('.openapi-import-security-op-status')).toHaveText('Resolved');
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
});
test('[P1] localizes unsupported findings and empty-profile guidance in RU and EN', async ({ page }) => {
const key = 'get:/locale';
await openSecurityPreview(page, 'ru', previewWith([
protectedOperation(key, 'locale_operation', [
{ schemes: ['bearerAuth'], supported: true, findings: [] },
{ schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
]),
], []));
const row = page.locator('.openapi-import-operation').filter({ hasText: 'locale_operation' });
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
// RU: exact unsupported finding copy and empty-profile guidance.
await expect(row.locator('.openapi-import-security-findings')).toContainText(
'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.');
await alternative.selectOption('0');
await expect(profile).toBeDisabled();
await expect(row.locator('.openapi-import-security-guidance')).toHaveText(
'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.');
const opStatus = row.locator('.openapi-import-security-op-status');
await expect(opStatus).toHaveAttribute('role', 'status');
await expect(opStatus).toHaveAttribute('aria-live', 'polite');
// EN: switching language invalidates an unconfirmed preview, so re-preview
// and assert the exact translated copy in the second locale.
await page.evaluate(() => window.setLang('en'));
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await expect(row.locator('.openapi-import-security-findings')).toContainText(
'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.');
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toBeDisabled();
await expect(row.locator('.openapi-import-security-guidance')).toHaveText(
'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.');
});
test('[P1] a stale security plan cannot restore authority after a language or workspace change', async ({ page }) => {
const releases = [];
let planReleased = 0;
await page.route('**/imports/openapi/*/plans', async (route) => {
await new Promise((resolve) => releases.push(resolve));
planReleased += 1;
try {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })),
});
} catch (_error) {
// The context change aborts the request; it must not update the modal.
}
});
await openSecurityPreview(page, 'en');
async function bindSelection() {
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
}
async function startPlan() {
const request = page.waitForRequest((r) => r.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(r.url()));
await page.locator('#openapi-import-create').click();
await request;
await expect.poll(() => releases.length).toBeGreaterThanOrEqual(1);
}
// 1) Language change while a security plan is pending.
await bindSelection();
await startPlan();
await page.evaluate(() => window.setLang('ru'));
releases.shift()();
await expect.poll(() => planReleased).toBeGreaterThanOrEqual(1);
await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено');
await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0);
// 2) Workspace change while a security plan is pending.
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await bindSelection();
await startPlan();
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'ws-stale-security' } }));
});
releases.shift()();
await expect.poll(() => planReleased).toBeGreaterThanOrEqual(2);
await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено');
await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0);
await expect(page.locator('#openapi-import-preview-panel')).toBeHidden();
});
/* ── Real API evidence ───────────────────────────────────────────────── */
test('[P1][api] real preview/plan round-trip resolves a typed reference (real secret + bearer profile)', async ({ page }) => {
await login(page);
await dismissOnboardingIfOpen(page);
await page.evaluate(() => window.setLang('en'));
const workspace = await getCurrentWorkspace(page);
const prefix = uniqueName('secmap');
const secretValue = 'secmap-bearer-' + prefix;
const secret = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`,
{ name: prefix + '_secret', kind: 'token', value: secretValue },
);
let profile = null;
try {
profile = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`,
{
name: prefix + '_profile',
kind: 'bearer',
config: { bearer: { header_name: 'Authorization', secret_id: secret.id } },
},
);
expect(String(profile.id)).toMatch(/^auth_/);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'security-mapping-real.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from([
'openapi: 3.0.3',
'info: { title: Security mapping real, version: "1" }',
'servers: [{ url: "https://api.example.test" }]',
'paths:',
' /' + prefix + ':',
' get:',
' operationId: ' + prefix + '_operation',
' security:',
' - bearerAuth: []',
' - {}',
' responses:',
' \'200\': { description: OK }',
'components:',
' securitySchemes:',
' bearerAuth: { type: http, scheme: bearer }',
].join('\n')),
});
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' });
await bearerOption.waitFor({ state: 'attached' });
const bearerIndex = await bearerOption.getAttribute('value');
expect(bearerIndex).toMatch(/^\d+$/); // option value, not the select's current value
await alternative.selectOption(bearerIndex);
const realProfileOption = profileSelect.locator('option[value="' + profile.id + '"]');
await expect(realProfileOption).toBeAttached();
await profileSelect.selectOption(profile.id);
const planRequest = page.waitForRequest((request) =>
request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()),
);
await page.locator('#openapi-import-create').click();
const sent = await planRequest;
const response = await sent.response();
// Happy path is deterministic: the created profile matches the bearer
// scheme, so the real API must accept the typed reference.
expect(response.status()).toBe(200);
const payload = await sent.postDataJSON();
const planDecision = (payload.decisions || [])[0];
expect(planDecision).toMatchObject({ auth_profile_id: profile.id, security_alternative_index: Number(bearerIndex) });
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
await expect(page.locator('body')).not.toContainText(secretValue);
} finally {
// Best-effort cleanup. The Secret is guarded (409) while the live profile
// references it; the referenced Auth Profile has no delete endpoint, so we
// only attempt to release the Secret and never widen the backend surface.
try {
await browserJson(
page,
'DELETE',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets/${encodeURIComponent(secret.id)}`,
[],
[404, 409],
);
} catch (_error) {}
}
});
+121 -39
View File
@@ -11,6 +11,48 @@ async function dismissOnboardingIfOpen(page) {
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function planResponse(payload, planReference) {
const decisions = payload.decisions || [];
return {
plan_reference: planReference,
plan_digest: 'c'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: payload.selection_mode,
counts: { selected: decisions.length, excluded: 0, actionable: decisions.length, blocked: 0 },
candidates: decisions.map((decision) => ({
key: decision.operation_key,
name: decision.confirmed_name || decision.operation_key,
state: 'actionable',
action: decision.action,
target_operation_id: decision.target_operation_id || null,
confirmed_name: decision.confirmed_name || null,
auth_profile_id: null,
reason: null,
})),
};
}
function applyResponse(payload, names) {
const outcomes = (payload.outcomes || []).map((outcome) => ({
key: outcome.key,
name: names && names[outcome.key] || outcome.name || outcome.key,
status: outcome.status || 'created',
}));
return {
counts: { created: outcomes.filter((outcome) => outcome.status === 'created').length },
outcomes,
};
}
async function mockEmptyOperationsList(page) {
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
});
});
}
test('operations page shows demo catalog and filter works', async ({ page }) => {
await login(page);
await expect(page.locator('.page-heading')).toHaveText(localized('Operations', 'Операции'));
@@ -100,7 +142,9 @@ paths:
const request = await previewRequest;
expect(request.headers()['content-type']).toMatch(/^multipart\/form-data; boundary=/i);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await expect(page.locator('.openapi-import-document-findings')).toContainText(/base URL/i);
const documentFindings = page.locator('.openapi-import-document-findings');
await documentFindings.locator('summary').click();
await expect(documentFindings).toContainText(/base URL/i);
await expect(page.locator('.openapi-import-group').filter({ hasText: 'currency' })).toBeVisible();
const importedOperation = page.locator('.openapi-import-operation').filter({ hasText: 'Получить курсы валют' });
await expect(importedOperation).toBeVisible();
@@ -118,6 +162,7 @@ paths:
await page.locator('#openapi-import-search').fill('status');
await expect(page.locator('.openapi-import-operation:visible')).toHaveCount(1);
await expect(page.locator('.openapi-import-operation:visible').filter({ hasText: 'Проверить статус' })).toBeVisible();
await page.locator('#openapi-import-partial-mode').check();
await page.locator('#openapi-import-clear-visible').click();
await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 1', 'Выбрано: 1'));
await page.locator('#openapi-import-search').fill('');
@@ -127,18 +172,21 @@ paths:
await page.locator('#openapi-import-method-filter').selectOption('');
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('#openapi-import-result')).toContainText(localized('Import result', 'Результат импорта'));
await expect(page.locator('.openapi-import-result-table')).toBeVisible();
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText('POST /v1/rates/{date}');
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText(localized('tool description is too short', 'Описание инструмента слишком короткое'));
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText(localized('Fix in wizard', 'Исправить в мастере'));
await expect(page.locator('.openapi-import-primary-result a')).toHaveAttribute(
'href',
/\/wizard\/\?mode=edit&operationId=op_/
);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect(page.locator('#openapi-import-result')).toBeVisible();
await expect(page.locator('#openapi-import-result')).toContainText(localized('Import plan result', 'Результат плана импорта'));
await expect(page.locator('.openapi-import-plan-outcomes')).toContainText(operationId);
await expect(page.locator('.openapi-import-plan-outcomes')).toContainText('POST /v1/rates/{date}');
const operationFindings = importedOperation.locator('.openapi-import-findings');
await operationFindings.locator('summary').click();
await expect(operationFindings).toContainText(localized('tool description is too short', 'Описание инструмента слишком короткое'));
await expect(page.locator('tbody')).toContainText(new RegExp(operationId, 'i'));
await expect(page.locator('tbody')).not.toContainText(new RegExp(statusOperationId, 'i'));
await expect(page.locator('body')).not.toContainText(sourceCanary);
await page.locator('[data-openapi-close]').last().click();
await page.locator('tbody tr').filter({ hasText: operationId }).locator('.row-btn-edit').click();
await expect(page).toHaveURL(/\/wizard\/\?mode=edit&operationId=op_/);
});
test('OpenAPI upload rejects invalid files locally and restores focus after Escape', async ({ page }) => {
@@ -230,7 +278,7 @@ test('OpenAPI upload recovers from pagehide and a preview server error', async (
buffer: Buffer.from('openapi: 3.0.3'),
});
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-status')).toContainText(localized('Uploading and parsing', 'Загружаю и разбираю'));
await expect(page.locator('#openapi-import-status')).toContainText(localized('Uploading the document', 'Загружаю документ'));
await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })));
await expect(page.locator('#openapi-import-status')).toHaveText('');
@@ -246,6 +294,7 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await mockEmptyOperationsList(page);
await page.route('**/imports/openapi/preview', async (route) => {
await route.fulfill({
@@ -269,11 +318,18 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
});
const requests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(planResponse(payload, 'plan_retry_same_authority')),
});
});
let releaseFirst;
const firstRequest = new Promise((resolve) => {
releaseFirst = resolve;
});
await page.route('**/imports/openapi/*/create', async (route) => {
await page.route('**/imports/openapi/*/apply', async (route) => {
requests.push({ url: route.request().url(), body: route.request().postData() });
if (requests.length === 1) await firstRequest;
if (requests.length === 3) {
@@ -287,12 +343,9 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
try {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
created: [{
operation_key: 'get:/retry', name: 'renamed_after_conflict', operation_id: 'op_retry', version: 1,
}],
skipped: [], findings: [],
}),
body: JSON.stringify(applyResponse({ outcomes: [{
key: 'get:/retry', name: 'renamed_after_conflict', status: 'created',
}] })),
});
} catch (_error) {
// The first request is deliberately aborted by the browser.
@@ -305,23 +358,25 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(() => requests.length).toBe(1);
await page.locator('#openapi-import-cancel').click();
await expect(page.locator('#openapi-import-status')).toContainText(localized('may have completed', 'мог завершиться'));
await expect(page.locator('#openapi-import-status')).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await page.locator('[data-openapi-close]').last().click();
await page.reload();
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await page.locator('#openapi-import-retry').click();
await expect(page.locator('#openapi-import-result')).toContainText('GET /retry');
await expect(page.locator('#openapi-import-result')).toContainText('get:/retry');
await expect.poll(() => requests.length).toBe(2);
// Let the cancelled first attempt answer after the retry. Its stale response
// must not overwrite or unlock the newer attempt's state.
releaseFirst();
await page.waitForTimeout(50);
await expect(page.locator('#openapi-import-result')).toContainText('GET /retry');
expect(requests[0].url).toContain('/imports/openapi/job_retry_same_authority/create');
await expect(page.locator('#openapi-import-result')).toContainText('get:/retry');
expect(requests[0].url).toContain('/imports/openapi/plan_retry_same_authority/apply');
expect(requests[1].url).toBe(requests[0].url);
expect(requests[1].body).toBe(requests[0].body);
@@ -334,17 +389,20 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(() => requests.length).toBe(3);
await expect(page.locator('#openapi-import-file-select')).toBeEnabled();
await expect(page.locator('#openapi-import-reset')).toBeEnabled();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
expect(await page.evaluate(() => sessionStorage.getItem('crank_openapi_apply_replay_v1'))).toBeNull();
expect(await page.evaluate(() => sessionStorage.getItem('crank_openapi_plan_apply_replay_v2'))).toBeNull();
});
test('OpenAPI apply preserves job authority after language or workspace changes', async ({ page }) => {
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await mockEmptyOperationsList(page);
await page.route('**/imports/openapi/preview', async (route) => {
await route.fulfill({
@@ -368,16 +426,21 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
});
const releases = [];
const applyRequests = [];
await page.route('**/imports/openapi/*/create', async (route) => {
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(planResponse(route.request().postDataJSON(), 'plan_active_apply')),
});
});
await page.route('**/imports/openapi/*/apply', async (route) => {
applyRequests.push({ url: route.request().url(), body: route.request().postData() });
await new Promise((resolve) => releases.push(resolve));
try {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
created: [{ operation_key: 'get:/active', name: 'active', operation_id: 'op_active', version: 1 }],
skipped: [], findings: [],
}),
body: JSON.stringify(applyResponse({ outcomes: [{
key: 'get:/active', name: 'active', status: 'created',
}] })),
});
} catch (_error) {
// The invalidation aborts a request that must not update the modal afterwards.
@@ -394,6 +457,8 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect(page.locator('#openapi-import-cancel')).toBeVisible();
await expect.poll(() => releases.length).toBeGreaterThan(0);
}
@@ -402,14 +467,14 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
// Exercise the actual UI language switcher path: it updates storage,
// re-renders translations and dispatches crank:langchange in one action.
await page.evaluate(() => window.setLang('en'));
await expect(page.locator('#openapi-import-status')).toContainText('may have completed');
await expect(page.locator('#openapi-import-status')).toContainText('Apply result is unknown');
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
releases.shift()();
await page.locator('#openapi-import-retry').click();
await expect.poll(() => releases.length).toBeGreaterThan(0);
releases.shift()();
await expect(page.locator('#openapi-import-result')).toContainText('GET /active');
await expect(page.locator('#openapi-import-result')).toContainText('get:/active');
expect(applyRequests[1].url).toBe(applyRequests[0].url);
expect(applyRequests[1].body).toBe(applyRequests[0].body);
@@ -419,7 +484,7 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'workspace-after-apply' } }));
});
await expect(page.locator('#openapi-import-status')).toContainText('may have completed');
await expect(page.locator('#openapi-import-status')).toContainText('Apply result is unknown');
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
releases.shift()();
@@ -516,6 +581,7 @@ test('OpenAPI upload ignores a stale failure and renders only correlation identi
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await mockEmptyOperationsList(page);
const sourceCanary = 'do-not-render-openapi-source-canary';
await page.locator('#openapi-import-file').setInputFiles({
name: 'safe.yaml',
@@ -590,14 +656,30 @@ test('OpenAPI upload ignores a stale failure and renders only correlation identi
});
await page.locator('#openapi-import-retry').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
let createRequests = 0;
await page.route('**/imports/openapi/*/create', async (route) => {
createRequests += 1;
await new Promise((resolve) => setTimeout(resolve, 100));
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ created: [], skipped: [], findings: [] }) });
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(planResponse(route.request().postDataJSON(), 'plan_ui_evidence')),
});
});
let applyRequests = 0;
let releaseApply;
const applyResponseHeld = new Promise((resolve) => { releaseApply = resolve; });
await page.route('**/imports/openapi/*/apply', async (route) => {
applyRequests += 1;
await applyResponseHeld;
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(applyResponse({ outcomes: [{ key: 'get:/health', name: 'health', status: 'created' }] })),
});
});
await page.locator('#openapi-import-create').click();
await page.locator('#openapi-import-create').evaluate((button) => button.click());
await expect(page.locator('#openapi-import-status')).toContainText('Created: 0; skipped: 0.');
expect(createRequests).toBe(1);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
const applyButton = page.locator('#openapi-import-plan-apply');
await applyButton.dblclick();
await expect.poll(() => applyRequests).toBe(1);
await expect(applyButton).toBeDisabled();
releaseApply();
await expect(page.locator('#openapi-import-status')).toContainText('Import plan applied.');
expect(applyRequests).toBe(1);
});
+41
View File
@@ -0,0 +1,41 @@
const { test, expect } = require('@playwright/test');
const { login } = require('./helpers');
test('delayed new-upstream autofocus must not steal focus from the URL field', async ({ page }) => {
await login(page);
await page.goto('/wizard/');
await page.waitForFunction(() => window.CrankWizardReady === true);
await page.locator('[data-testid="wizard-protocol-rest"]').click();
await page.locator('#btn-continue').click();
await expect(page.locator('#upstream-new-trigger')).toBeVisible();
// Take manual control of page time before the new-upstream form is opened so
// the deferred autofocus timer scheduled by startNewUpstream cannot fire on
// its own while Playwright fills the two fields.
const installTime = new Date('2026-05-01T12:00:00.000Z');
await page.clock.install({ time: installTime });
await page.clock.pauseAt(new Date(installTime.getTime() + 1000));
await page.locator('#upstream-new-trigger').click();
await page.locator('#new-upstream-name').fill('focus-red-upstream');
await page.locator('#new-upstream-url').fill('http://127.0.0.1:3310');
// Both values landed exactly and focus is explicitly on the URL field before
// the deferred autofocus runs.
await expect(page.locator('#new-upstream-name')).toHaveValue('focus-red-upstream');
await expect(page.locator('#new-upstream-url')).toHaveValue('http://127.0.0.1:3310');
await expect(page.locator('#new-upstream-url')).toBeFocused();
// Explicitly execute the old 50ms autofocus timer.
await page.clock.runFor(100);
// The delayed autofocus must not move focus back to the name field.
await expect(page.locator('#new-upstream-url')).toBeFocused();
// Correct field still receives text after the timer ran; no network mutation.
await page.keyboard.insertText('-probe');
await expect(page.locator('#new-upstream-url')).toHaveValue('http://127.0.0.1:3310-probe');
await expect(page.locator('#new-upstream-name')).toHaveValue('focus-red-upstream');
});
+165
View File
@@ -0,0 +1,165 @@
const { test, expect } = require('@playwright/test');
const { getCurrentWorkspace, login } = require('./helpers');
function draftSnapshot(operationId) {
return {
id: operationId,
name: operationId,
display_name: 'Imported rates',
category: 'general',
protocol: 'rest',
target: {
kind: 'rest',
base_url: 'https://api.example.test',
method: 'GET',
path_template: '/rates',
static_headers: {},
},
input_schema: {
type: 'object',
description: null,
required: false,
nullable: false,
default_value: null,
fields: {},
items: null,
enum_values: [],
variants: [],
},
output_schema: {
type: 'object',
description: null,
required: false,
nullable: false,
default_value: null,
fields: {},
items: null,
enum_values: [],
variants: [],
},
input_mapping: { rules: [] },
output_mapping: {
rules: [
{ source: '$.response.body', target: '$.output', required: true },
{ source: '$.response.body.rate', target: '$.output.rate', required: true },
],
},
execution_config: {
timeout_ms: 10000,
retry_policy: null,
auth_profile_ref: null,
headers: {},
approval_policy: null,
},
tool_description: { title: 'Imported rates', description: 'Get rates.', tags: [], examples: [] },
wizard_state: { input_sample: {}, output_sample: {}, test_input: {}, import_findings: [] },
};
}
test('edit wizard skips no-op saves and refreshes its baseline after a real edit', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operationId = 'imported_rates_noop';
const operationPath = `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/operations/${operationId}`;
const versionPath = `${operationPath}/versions/*`;
let version = 4;
let updateCount = 0;
const testedVersions = [];
const publishedVersions = [];
const analyzedPayloads = [];
await page.route(operationPath, async (route) => {
if (route.request().method() === 'PATCH') {
updateCount += 1;
version += 1;
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ operation_id: operationId, workspace_id: workspace.id, version, status: 'draft' }),
});
return;
}
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
id: operationId,
workspace_id: workspace.id,
name: operationId,
display_name: 'Imported rates',
category: 'general',
protocol: 'rest',
status: 'draft',
current_draft_version: version,
draft_version_ref: { version, status: 'draft' },
published_version_ref: null,
agent_refs: [],
}),
});
});
await page.route(versionPath, async (route) => {
const requestedVersion = Number(new URL(route.request().url()).pathname.split('/').pop());
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
operation_id: operationId,
workspace_id: workspace.id,
version: requestedVersion,
status: 'draft',
snapshot: draftSnapshot(operationId),
}),
});
});
await page.route(`**/operations/${operationId}/test-runs`, async (route) => {
testedVersions.push(route.request().postDataJSON().version);
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, errors: [] }) });
});
await page.route('**/operations/analyze-quality', async (route) => {
analyzedPayloads.push(route.request().postDataJSON());
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ blocking: false, findings: [] }) });
});
await page.route(`**/operations/${operationId}/publish`, async (route) => {
const payload = route.request().postDataJSON();
publishedVersions.push(payload.version);
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ published_version: payload.version }) });
});
page.on('dialog', (dialog) => dialog.accept());
await page.goto(`/wizard/?mode=edit&operationId=${operationId}`);
await expect(page.locator('#tool-display-name')).toHaveValue('Imported rates');
const loadedOutputMapping = await page.evaluate(() => (
window.jsyaml.load(document.getElementById('tool-output-mapping').value)
));
expect(loadedOutputMapping['$.output']).toBe('$.response.body');
expect(loadedOutputMapping.rate).toBe('$.response.body.rate');
expect(JSON.stringify(loadedOutputMapping)).not.toContain('$.response.body.$.output');
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
await page.locator('#wizard-run-test').click();
await expect.poll(() => testedVersions).toEqual([4]);
expect(updateCount).toBe(0);
await page.evaluate(() => window.CrankWizardShell.doGoToStep(4));
await page.locator('#tool-display-name').fill('Edited rates');
await page.locator('.btn-save-draft').click();
await expect.poll(() => updateCount).toBe(1);
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
await page.locator('#wizard-run-test').click();
await expect.poll(() => testedVersions).toEqual([4, 5]);
expect(updateCount).toBe(1);
await page.locator('#wizard-publish-operation').click();
await expect.poll(() => publishedVersions).toEqual([5]);
expect(updateCount).toBe(1);
const publishedRules = analyzedPayloads[analyzedPayloads.length - 1].output_mapping.rules;
expect(publishedRules).toEqual(expect.arrayContaining([
expect.objectContaining({ source: '$.response.body', target: '$.output' }),
expect.objectContaining({ source: '$.response.body.rate', target: '$.output.rate' }),
]));
expect(JSON.stringify(publishedRules)).not.toContain('$.response.body.$.output');
});
+4 -2
View File
@@ -193,7 +193,7 @@ test('wizard builds visual request mappings from JSON sample and path params', a
await page.goto('/wizard/');
await page.locator('[data-testid="wizard-protocol-rest"]').click();
await page.evaluate(() => window.CrankWizardShell.goToStep(2));
await page.locator('#btn-continue').click();
await expect(page.locator('#step-panel-2')).toBeVisible();
await page.locator('#endpoint-path').fill('/rates/{date}');
await page.evaluate(() => window.CrankWizardShell.goToStep(3));
@@ -881,10 +881,12 @@ test('wizard edit mode preserves explicit request mapping targets on save', asyn
await expect(page.locator('#approval-risk-level')).toHaveCount(0);
await expect(page.locator('#approval-ttl-seconds')).toHaveValue('180');
await expect(page.locator('#approval-payload-preview-mode')).toHaveCount(0);
await page.evaluate(() => window.CrankWizardShell.doGoToStep(4));
await page.locator('#tool-display-name').fill('Frankfurter latest rate edited');
await page.locator('.btn-save-draft').click();
await expect.poll(() => updatePayload).not.toBeNull();
expect(updatePayload.display_name).toBe('Frankfurter latest rate');
expect(updatePayload.display_name).toBe('Frankfurter latest rate edited');
expect(updatePayload.target).toEqual({
kind: 'rest',
base_url: 'https://api.frankfurter.app',