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

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

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

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

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

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

1172 lines
47 KiB
JavaScript

(function () {
'use strict';
var workspaceId = null;
var activePromptId = null;
var activeVersion = null;
var activeUpdatedAt = null;
var activeStatus = null;
var activePublishedVersion = null;
var definitionDirty = false;
var lastItems = [];
var loadGeneration = 0;
var previewGeneration = 0;
var publishedGeneration = 0;
var bindGeneration = 0;
var busy = false;
var form = document.getElementById('prompt-form');
var list = document.getElementById('prompt-list');
var pageStatus = document.getElementById('prompts-status');
var previewStatus = document.getElementById('prompt-preview-status');
var messagesHost = document.getElementById('prompt-preview-messages');
var dependenciesHost = document.getElementById('prompt-dependencies-provenance');
var effectiveSensitivityNode = document.getElementById('prompt-effective-sensitivity');
var compositionError = document.getElementById('prompt-composition-error');
var empty = document.getElementById('prompt-empty');
var saveButton = document.getElementById('prompt-save');
var previewButton = document.getElementById('prompt-preview-button');
var reloadButton = document.getElementById('prompt-reload');
var publishButton = document.getElementById('prompt-publish');
var archiveButton = document.getElementById('prompt-archive');
var viewPublishedButton = document.getElementById('prompt-view-published');
var publishedPanel = document.getElementById('prompt-published');
var publishedStatus = document.getElementById('prompt-published-status');
var publishedVersionNode = document.getElementById('prompt-published-version');
var publishedDefinition = document.getElementById('prompt-published-definition');
var bindAgentSelect = document.getElementById('prompt-bind-agent');
var bindButton = document.getElementById('prompt-bind-button');
var bindStatus = document.getElementById('prompt-bind-status');
var confirmDialog = document.getElementById('prompt-confirm');
var pendingConfirm = null;
var pendingSaveBody = null;
// Story 3.15: перенос шаблонов (export Draft/точная версия, import нового Draft).
var exportLink = document.getElementById('prompt-export');
var exportStatus = document.getElementById('prompt-export-status');
var importFile = document.getElementById('prompt-import-file');
var importSubmit = document.getElementById('prompt-import-submit');
var importPreviewHost = document.getElementById('prompt-import-preview-host');
var importConfirmHost = document.getElementById('prompt-import-confirm-host');
var importStatus = document.getElementById('prompt-import-status');
var importError = document.getElementById('prompt-import-error');
var importStaleHost = document.getElementById('prompt-import-stale-host');
var importBusy = false;
var pendingEnvelope = null;
function t(key, fallback) {
if (typeof window.t !== 'function') return fallback || key;
var value = window.t(key);
return value === key && fallback ? fallback : value;
}
function setStatus(node, key, fallback) {
if (node) node.textContent = key ? t(key, fallback) : '';
}
function basePath() {
return '/api/admin/workspaces/' + encodeURIComponent(workspaceId || '') + '/prompts';
}
async function readResponse(response) {
var text = await response.text();
var payload = null;
if (text) {
try { payload = JSON.parse(text); } catch (_error) { payload = null; }
}
return { status: response.status, ok: response.ok, payload: payload, headers: response.headers };
}
async function csrfToken() {
if (window.CrankAuth && typeof window.CrankAuth.ensureCsrf === 'function') {
return (await window.CrankAuth.ensureCsrf()) || '';
}
var token = window.CrankAuth && window.CrankAuth.getCsrfToken
? window.CrankAuth.getCsrfToken()
: '';
if (!token && window.CrankApi && window.CrankApi.refreshSessionCsrf) {
var result = await window.CrankApi.refreshSessionCsrf();
token = result && result.csrf_token ? result.csrf_token : '';
}
return token || '';
}
async function request(method, url, body, extraHeaders) {
var headers = { Accept: 'application/json' };
if (body != null) headers['Content-Type'] = 'application/json';
if (extraHeaders) {
Object.keys(extraHeaders).forEach(function (name) { headers[name] = extraHeaders[name]; });
}
if (method !== 'GET') {
var token = await csrfToken();
if (token && String(url).indexOf('/api/') === 0) headers['X-CSRF-Token'] = token;
}
var response = await fetch(url, {
method: method,
credentials: 'same-origin',
headers: headers,
body: body == null ? undefined : JSON.stringify(body),
});
return readResponse(response);
}
function parseJson(text) {
return JSON.parse(text);
}
function definitionFromForm() {
return {
name: document.getElementById('prompt-name').value.trim(),
description: document.getElementById('prompt-description').value.trim(),
arguments: parseJson(document.getElementById('prompt-arguments').value),
messages: parseJson(document.getElementById('prompt-messages').value),
dependencies: parseJson(dependenciesField().value || '[]'),
sensitivity: document.getElementById('prompt-sensitivity').value,
};
}
function dependenciesField() {
return document.getElementById('prompt-dependencies');
}
// Story 3.16: эффективная политика и provenance — данные ответа, не текст сообщений.
function sensitivityKey(value) {
return 'prompts.sensitivity.' + String(value || 'internal');
}
function setEffectiveSensitivity(value) {
if (!effectiveSensitivityNode) return;
if (!value) {
effectiveSensitivityNode.textContent = '—';
effectiveSensitivityNode.removeAttribute('data-i18n');
return;
}
var key = sensitivityKey(value);
effectiveSensitivityNode.setAttribute('data-i18n', key);
effectiveSensitivityNode.textContent = t(key, value);
}
function clearComposition() {
if (messagesHost) messagesHost.textContent = '';
if (dependenciesHost) dependenciesHost.textContent = '';
if (compositionError) {
compositionError.textContent = '';
compositionError.hidden = true;
}
setEffectiveSensitivity('');
}
function showCompositionError(payload) {
if (!compositionError) return;
var context = payload && payload.error && payload.error.context ? payload.error.context : {};
var code = (payload && payload.error && payload.error.code) || context.error_code || 'prompt_composition_failed';
var parts = [t('prompts.composition.error', 'Composed preview failed'), code];
if (context.source_path) parts.push(String(context.source_path));
compositionError.textContent = parts.join(': ');
compositionError.hidden = false;
}
function renderDependencies(dependencies) {
if (!dependenciesHost) return;
dependenciesHost.textContent = '';
(dependencies || []).forEach(function (dependency) {
var row = document.createElement('li');
row.setAttribute('data-testid', 'prompt-dependency');
var version = document.createElement('span');
version.setAttribute('data-testid', 'prompt-dependency-version');
version.textContent = 'v' + dependency.version;
var sourceClass = document.createElement('span');
sourceClass.setAttribute('data-testid', 'prompt-dependency-source-class');
sourceClass.textContent = dependency.source_class;
var digest = document.createElement('span');
digest.setAttribute('data-testid', 'prompt-dependency-digest');
digest.textContent = dependency.digest || '';
var sensitivity = document.createElement('span');
sensitivity.className = 'prompt-dependency-sensitivity';
var key = sensitivityKey(dependency.sensitivity);
sensitivity.setAttribute('data-i18n', key);
sensitivity.textContent = t(key, dependency.sensitivity || '');
var untrusted = document.createElement('span');
untrusted.setAttribute('data-testid', 'prompt-dependency-untrusted');
untrusted.setAttribute('data-i18n', 'prompts.dependency.untrusted');
untrusted.textContent = t('prompts.dependency.untrusted', 'Untrusted content - no sanitisation promise');
row.appendChild(version);
row.appendChild(sourceClass);
row.appendChild(sensitivity);
row.appendChild(digest);
row.appendChild(untrusted);
dependenciesHost.appendChild(row);
});
}
function resetPreview() {
previewGeneration += 1;
previewStatus.textContent = '';
clearComposition();
previewButton.setAttribute('aria-busy', 'false');
previewButton.disabled = !activePromptId || definitionDirty;
}
function markDefinitionDirty() {
definitionDirty = true;
resetPreview();
setStatus(previewStatus, 'prompts.preview.requires_save');
refreshStateLabel();
}
function statusLabel(status) {
if (status === 'archived') return t('prompts.archived_state', 'Archived');
if (status === 'published') return t('prompts.published_state', 'Published');
return t('prompts.draft');
}
function refreshStateLabel() {
var label = statusLabel(activeStatus);
document.getElementById('prompt-state-label').textContent =
label + (activeVersion == null ? '' : ' · v' + activeVersion);
var detail = t('prompts.not_published');
if (activeStatus === 'archived') {
detail = t('prompts.archived_detail', 'This Prompt is archived; published versions stay immutable.');
} else if (activePublishedVersion != null) {
detail = t('prompts.published_version', 'Published version') + ' v' + activePublishedVersion +
' · ' + t('prompts.immutable', 'immutable snapshot');
}
document.getElementById('prompt-state-detail').textContent = detail;
if (exportLink) {
exportLink.hidden = activePromptId == null;
exportLink.setAttribute('aria-disabled', activePromptId == null ? 'true' : 'false');
}
publishButton.disabled = activePromptId == null || activeStatus === 'archived' || definitionDirty || busy;
archiveButton.disabled = activePromptId == null || activeStatus === 'archived' || busy;
viewPublishedButton.hidden = activePublishedVersion == null;
bindButton.disabled = activePromptId == null || activePublishedVersion == null ||
!bindAgentSelect.value || busy;
}
function markActive(id) {
Array.prototype.forEach.call(list.querySelectorAll('button[data-prompt-id]'), function (button) {
button.setAttribute('aria-current', button.getAttribute('data-prompt-id') === id ? 'true' : 'false');
});
}
function renderList(items) {
list.textContent = '';
empty.hidden = items.length !== 0;
items.forEach(function (item) {
var button = document.createElement('button');
button.type = 'button';
button.className = 'prompt-list-item';
button.setAttribute('data-prompt-id', item.prompt_id);
button.setAttribute('data-testid', 'prompt-list-item');
button.setAttribute('aria-current', item.prompt_id === activePromptId ? 'true' : 'false');
var name = document.createElement('strong');
name.textContent = item.name;
var detail = document.createElement('span');
detail.textContent = statusLabel(item.status) + ' · v' + item.version;
button.appendChild(name);
button.appendChild(detail);
button.addEventListener('click', function () { loadPrompt(item.prompt_id); });
var row = document.createElement('li');
row.appendChild(button);
list.appendChild(row);
});
}
async function loadList() {
var generation = ++loadGeneration;
if (!workspaceId) {
setStatus(pageStatus, 'prompts.error.load');
return;
}
setStatus(pageStatus, 'prompts.loading');
try {
var result = await request('GET', basePath());
if (generation !== loadGeneration) return;
if (!result.ok) throw new Error('list failed');
var items = result.payload && Array.isArray(result.payload.items) ? result.payload.items : [];
lastItems = items;
renderList(items);
setStatus(pageStatus, '');
if (!activePromptId && items.length) await loadPrompt(items[0].prompt_id);
else if (activePromptId && !items.some(function (item) { return item.prompt_id === activePromptId; })) {
activePromptId = null;
activeUpdatedAt = null;
activeStatus = null;
activePublishedVersion = null;
resetEditor();
}
} catch (_error) {
if (generation === loadGeneration) setStatus(pageStatus, 'prompts.error.load');
}
}
function populate(record) {
activePromptId = record.prompt_id;
activeVersion = record.version;
activeUpdatedAt = record.updated_at;
activeStatus = record.status;
activePublishedVersion = record.latest_published_version == null
? null
: record.latest_published_version;
definitionDirty = false;
hidePublished();
clearPortabilityTransient();
document.getElementById('prompt-name').value = record.definition.name;
document.getElementById('prompt-description').value = record.definition.description;
document.getElementById('prompt-sensitivity').value = record.sensitivity;
document.getElementById('prompt-arguments').value = JSON.stringify(record.definition.arguments, null, 2);
document.getElementById('prompt-messages').value = JSON.stringify(record.definition.messages, null, 2);
dependenciesField().value = JSON.stringify(record.definition.dependencies || [], null, 2);
refreshStateLabel();
reloadButton.hidden = true;
saveButton.disabled = false;
previewButton.disabled = false;
markActive(activePromptId);
resetPreview();
}
function resetEditor() {
activePromptId = null;
activeVersion = null;
activeUpdatedAt = null;
activeStatus = null;
activePublishedVersion = null;
definitionDirty = false;
hidePublished();
clearPortabilityTransient();
form.reset();
document.getElementById('prompt-arguments').value = '[\n {"name":"name","schema":{"type":"string"},"required":true}\n]';
document.getElementById('prompt-messages').value = '[\n {"role":"user","content":"Hello {{name}}"}\n]';
dependenciesField().value = '[]';
document.getElementById('prompt-preview-arguments').value = '{\n "name": "Ada"\n}';
refreshStateLabel();
reloadButton.hidden = true;
saveButton.disabled = false;
previewButton.disabled = true;
markActive('');
resetPreview();
}
async function loadPrompt(id) {
var generation = ++loadGeneration;
resetPreview();
saveButton.disabled = true;
previewButton.disabled = true;
setStatus(pageStatus, 'prompts.loading');
try {
var result = await request('GET', basePath() + '/' + encodeURIComponent(id));
if (generation !== loadGeneration) return;
if (!result.ok) throw new Error('load failed');
populate(result.payload);
setStatus(pageStatus, '');
} catch (_error) {
if (generation === loadGeneration) setStatus(pageStatus, 'prompts.error.load');
} finally {
if (generation === loadGeneration) saveButton.disabled = false;
}
}
function showConfirmation(kind, titleKey, text, acceptKey) {
pendingConfirm = kind;
var title = document.getElementById('prompt-confirm-title');
var node = document.getElementById('prompt-confirm-text');
var accept = document.getElementById('prompt-confirm-save');
var cancel = document.getElementById('prompt-confirm-cancel');
title.textContent = t(titleKey);
node.textContent = text;
accept.textContent = t(acceptKey);
cancel.textContent = t('prompts.confirm.cancel', 'Cancel');
if (confirmDialog.showModal) confirmDialog.showModal();
else confirmDialog.setAttribute('open', '');
}
function closeConfirmation() {
pendingConfirm = null;
if (confirmDialog.open && confirmDialog.close) confirmDialog.close();
else confirmDialog.removeAttribute('open');
}
function hidePublished() {
publishedGeneration += 1;
publishedPanel.hidden = true;
// Блок точной версии существует только для показанного снимка: у черновика
// без публикаций этого элемента нет вовсе (контракт Story 3.15 §5).
publishedPanel.removeAttribute('data-testid');
publishedStatus.textContent = '';
publishedVersionNode.textContent = '';
publishedDefinition.textContent = '';
removeNode(publishedPanel.querySelector('[data-testid="prompt-published-export"]'));
}
/// Ссылка экспорта точной Published Version живёт только внутри показанного
/// снимка: у черновика без публикаций такого действия нет вовсе.
function renderPublishedExport(version) {
removeNode(publishedPanel.querySelector('[data-testid="prompt-published-export"]'));
var link = document.createElement('a');
link.className = 'btn-secondary';
link.id = 'prompt-published-export';
link.setAttribute('data-testid', 'prompt-published-export');
link.setAttribute('role', 'button');
link.href = exportUrl(activePromptId, version);
link.textContent = t('prompts.export.published', 'Export this version');
link.addEventListener('click', function (event) {
event.preventDefault();
startExport(link.getAttribute('href'), activePromptId);
});
publishedPanel.appendChild(link);
}
async function saveDraft() {
if (busy || !workspaceId) return;
var body;
try {
body = definitionFromForm();
} catch (_error) {
setStatus(pageStatus, 'prompts.error.invalid_json');
// Невалидный JSON dependencies блокирует и сохранение, и предпросмотр.
previewButton.disabled = true;
return;
}
if (activePromptId) body.expected_updated_at = activeUpdatedAt;
pendingSaveBody = body;
showConfirmation(
'save',
activePromptId ? 'prompts.confirm.update' : 'prompts.confirm.create',
document.getElementById('prompt-name').value.trim(),
'prompts.save'
);
}
async function confirmSave() {
if (!pendingSaveBody || busy) return;
var body = pendingSaveBody;
pendingSaveBody = null;
closeConfirmation();
var wasUpdate = Boolean(activePromptId);
var targetId = activePromptId;
var generation = loadGeneration;
busy = true;
saveButton.disabled = true;
saveButton.setAttribute('aria-busy', 'true');
setStatus(pageStatus, 'prompts.saving');
try {
var url = basePath() + (wasUpdate ? '/' + encodeURIComponent(targetId) : '');
var result = await request(wasUpdate ? 'PUT' : 'POST', url, body);
if (generation !== loadGeneration || workspaceId == null) return;
if (!result.ok) {
if (result.status === 409 || result.status === 428) {
setStatus(pageStatus, 'prompts.stale');
reloadButton.hidden = false;
} else {
setStatus(pageStatus, 'prompts.error.save');
}
return;
}
populate(result.payload);
var savedPromptId = result.payload.prompt_id;
var savedWorkspaceId = workspaceId;
await loadList();
if (workspaceId === savedWorkspaceId && activePromptId === savedPromptId) {
setStatus(pageStatus, 'prompts.saved');
}
} catch (_error) {
if (generation === loadGeneration) setStatus(pageStatus, 'prompts.error.save');
} finally {
busy = false;
saveButton.disabled = false;
saveButton.setAttribute('aria-busy', 'false');
refreshStateLabel();
}
}
function requestLifecycle(action) {
if (busy || !activePromptId || definitionDirty) return;
if (activeStatus === 'archived') return;
showConfirmation(
action,
action === 'publish' ? 'prompts.confirm.publish' : 'prompts.confirm.archive',
document.getElementById('prompt-name').value.trim(),
action === 'publish' ? 'prompts.publish' : 'prompts.archive'
);
}
async function confirmLifecycle(action) {
if (busy || !activePromptId) return;
closeConfirmation();
var selected = activePromptId;
var workspace = workspaceId;
var generation = loadGeneration;
busy = true;
refreshStateLabel();
setStatus(pageStatus, action === 'publish' ? 'prompts.publishing' : 'prompts.archiving');
try {
var result = await request('POST', basePath() + '/' + encodeURIComponent(selected), {
action: action,
expected_updated_at: activeUpdatedAt,
});
if (generation !== loadGeneration || workspace !== workspaceId || selected !== activePromptId) return;
if (!result.ok) {
if (result.status === 409 || result.status === 428) {
setStatus(pageStatus, 'prompts.stale');
reloadButton.hidden = false;
} else {
setStatus(pageStatus, 'prompts.error.action');
}
return;
}
populate(result.payload);
await loadList();
setStatus(pageStatus, action === 'publish' ? 'prompts.published_saved' : 'prompts.archived_saved');
} catch (_error) {
if (generation === loadGeneration) setStatus(pageStatus, 'prompts.error.action');
} finally {
busy = false;
refreshStateLabel();
}
}
async function loadPublishedVersion() {
if (!activePromptId || activePublishedVersion == null) return;
if (!publishedPanel.hidden) {
hidePublished();
return;
}
var generation = ++publishedGeneration;
var selected = activePromptId;
var version = activePublishedVersion;
publishedPanel.hidden = false;
publishedVersionNode.textContent = '';
publishedDefinition.textContent = '';
setStatus(publishedStatus, 'prompts.loading_published');
try {
var result = await request(
'GET',
basePath() + '/' + encodeURIComponent(selected) + '?version=' + encodeURIComponent(version)
);
if (generation !== publishedGeneration || selected !== activePromptId || version !== activePublishedVersion) return;
if (!result.ok || !result.payload) {
setStatus(publishedStatus, 'prompts.error.published');
return;
}
publishedVersionNode.textContent = 'v' + result.payload.version;
publishedDefinition.textContent = JSON.stringify(result.payload.definition, null, 2);
publishedPanel.setAttribute('data-testid', 'prompt-published');
renderPublishedExport(result.payload.version);
setStatus(publishedStatus, 'prompts.published_loaded');
} catch (_error) {
if (generation === publishedGeneration) setStatus(publishedStatus, 'prompts.error.published');
}
}
function agentsPath() {
return '/api/admin/workspaces/' + encodeURIComponent(workspaceId || '') + '/agents';
}
async function loadAgents() {
if (!workspaceId) return;
try {
var result = await request('GET', agentsPath());
if (!result.ok || !result.payload || !Array.isArray(result.payload.items)) {
setStatus(bindStatus, 'prompts.error.agents');
return;
}
var items = result.payload.items;
var previous = bindAgentSelect.value;
bindAgentSelect.textContent = '';
var placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = items.length ? '—' : t('prompts.no_agents', 'No Agents available.');
bindAgentSelect.appendChild(placeholder);
items.forEach(function (agent) {
var option = document.createElement('option');
option.value = agent.id;
option.textContent = agent.display_name || agent.slug;
bindAgentSelect.appendChild(option);
});
if (previous && items.some(function (agent) { return agent.id === previous; })) {
bindAgentSelect.value = previous;
}
if (!items.length) setStatus(bindStatus, 'prompts.no_agents');
refreshStateLabel();
} catch (_error) {
setStatus(bindStatus, 'prompts.error.agents');
}
}
function requestBind() {
if (busy || !activePromptId || activePublishedVersion == null || !bindAgentSelect.value) return;
showConfirmation('bind', 'prompts.confirm.bind', bindAgentSelect.options[bindAgentSelect.selectedIndex].textContent, 'prompts.bind');
}
async function confirmBind() {
if (busy || !activePromptId || activePublishedVersion == null || !bindAgentSelect.value) return;
closeConfirmation();
var generation = ++bindGeneration;
var selected = activePromptId;
var version = activePublishedVersion;
var agentId = bindAgentSelect.value;
var agentUrl = agentsPath() + '/' + encodeURIComponent(agentId);
busy = true;
refreshStateLabel();
setStatus(bindStatus, 'prompts.binding');
try {
var detail = await request('GET', agentUrl);
if (generation !== bindGeneration) return;
if (!detail.ok || !detail.payload) {
setStatus(bindStatus, 'prompts.error.bind');
return;
}
var etag = detail.headers && detail.headers.get ? detail.headers.get('etag') : null;
var draftVersion = detail.payload.current_draft_version;
if (!etag || draftVersion == null) {
setStatus(bindStatus, 'prompts.error.bind');
return;
}
var snapshot = await request('GET', agentUrl + '/versions/' + encodeURIComponent(draftVersion));
if (generation !== bindGeneration) return;
if (!snapshot.ok || !snapshot.payload) {
setStatus(bindStatus, 'prompts.error.bind');
return;
}
var existing = (snapshot.payload.prompt_bindings || []).filter(function (binding) {
return binding.prompt_id !== selected;
});
existing.push({ prompt_id: selected, prompt_version: version });
var saved = await request(
'POST',
agentUrl + '/bindings',
{
bindings: snapshot.payload.bindings || [],
tool_selection_policy: snapshot.payload.snapshot.tool_selection_policy,
resource_bindings: snapshot.payload.resource_bindings || [],
prompt_bindings: existing,
},
{ 'If-Match': etag }
);
if (generation !== bindGeneration) return;
if (!saved.ok || !saved.payload) {
if (saved.status === 409 || saved.status === 428) {
setStatus(bindStatus, 'prompts.bind.stale');
} else if (saved.status === 404) {
setStatus(bindStatus, 'prompts.bind.not_found');
} else {
setStatus(bindStatus, 'prompts.error.bind');
}
return;
}
var bound = (saved.payload.prompt_bindings || []).some(function (binding) {
return binding.prompt_id === selected && binding.prompt_version === version;
});
setStatus(bindStatus, bound ? 'prompts.bound' : 'prompts.error.bind');
} catch (_error) {
if (generation === bindGeneration) setStatus(bindStatus, 'prompts.error.bind');
} finally {
busy = false;
refreshStateLabel();
}
}
function renderMessages(messages) {
messagesHost.textContent = '';
(messages || []).forEach(function (message) {
var item = document.createElement('li');
item.setAttribute('data-role', message.role);
var role = document.createElement('span');
role.className = 'prompt-preview-role';
role.textContent = message.role;
var content = document.createElement('span');
content.className = 'prompt-preview-content';
content.textContent = message.content;
item.appendChild(role);
item.appendChild(content);
messagesHost.appendChild(item);
});
}
async function preview() {
if (!activePromptId || !workspaceId) return;
if (definitionDirty) {
clearComposition();
setStatus(previewStatus, 'prompts.preview.requires_save');
return;
}
var argumentsValue;
try {
argumentsValue = parseJson(document.getElementById('prompt-preview-arguments').value);
if (!argumentsValue || Array.isArray(argumentsValue) || typeof argumentsValue !== 'object') throw new Error('not object');
} catch (_error) {
clearComposition();
setStatus(previewStatus, 'prompts.error.invalid_json');
return;
}
var generation = ++previewGeneration;
var selected = activePromptId;
var workspace = workspaceId;
var hadFocus = document.activeElement === previewButton;
previewButton.disabled = true;
previewButton.setAttribute('aria-busy', 'true');
clearComposition();
setStatus(previewStatus, 'prompts.previewing');
try {
var result = await request('POST', basePath() + '/' + encodeURIComponent(selected) + '/preview', { arguments: argumentsValue });
if (generation !== previewGeneration || selected !== activePromptId || workspace !== workspaceId) return;
if (result.status === 409 || result.status === 428) {
clearComposition();
setStatus(previewStatus, 'prompts.preview.stale');
reloadButton.hidden = false;
return;
}
if (!result.ok || !result.payload || !Array.isArray(result.payload.messages)) {
clearComposition();
// Структурированный отказ композиции (unresolved/unsafe/unsupported): только код и
// source_path, без частичного списка сообщений.
showCompositionError(result.payload);
setStatus(previewStatus, 'prompts.error.preview');
return;
}
if (result.payload.version !== activeVersion) {
clearComposition();
setStatus(previewStatus, 'prompts.preview.stale');
reloadButton.hidden = false;
return;
}
renderMessages(result.payload.messages);
renderDependencies(result.payload.dependencies);
setEffectiveSensitivity(result.payload.effective_sensitivity);
setStatus(previewStatus, 'prompts.preview_done');
} catch (_error) {
if (generation === previewGeneration && selected === activePromptId) {
clearComposition();
setStatus(previewStatus, 'prompts.error.preview');
}
} finally {
if (generation === previewGeneration) {
previewButton.disabled = !activePromptId;
previewButton.setAttribute('aria-busy', 'false');
if (hadFocus && !previewButton.disabled) previewButton.focus();
}
}
}
// ---------------------------------------------------------------------------
// Story 3.15: перенос шаблонов сообщений — экспорт Draft/точной Published
// Version и импорт envelope как **нового** Draft. Определение показывается
// только как текст (`textContent`), поэтому перенесённый HTML инертен.
// ---------------------------------------------------------------------------
function removeNode(node) {
if (node && node.parentNode) node.parentNode.removeChild(node);
}
function clearChildren(node) {
if (node) node.textContent = '';
}
function exportUrl(promptId, version) {
if (version == null) return basePath() + '/' + encodeURIComponent(promptId) + '/export';
return basePath() + '/' + encodeURIComponent(promptId) + '/versions/' +
encodeURIComponent(version) + '/export';
}
function filenameFromDisposition(value) {
var match = /filename="([^"]+)"/.exec(value || '');
return match && match[1] ? match[1] : '';
}
function downloadEnvelopeFile(text, filename) {
var blob = new Blob([text], { type: 'application/json' });
var url = URL.createObjectURL(blob);
var anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
anchor.rel = 'noopener';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
}
function isCurrentSelection(generation, workspace, promptId) {
return generation === loadGeneration && workspace === workspaceId &&
(promptId == null || promptId === activePromptId);
}
/// Скачивание начинается только из принятого ответа текущего выбора: поздний
/// ответ прежнего Prompt не запускает download и не подменяет новый выбор.
async function startExport(url, promptId) {
if (!url || !promptId) return;
clearPortabilityStale();
var generation = loadGeneration;
var workspace = workspaceId;
setStatus(exportStatus, 'prompts.export.pending');
var response;
try {
response = await fetch(url, {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
} catch (_error) {
if (isCurrentSelection(generation, workspace, promptId)) {
setStatus(exportStatus, 'prompts.export.error');
}
return;
}
var text = await response.text();
if (!isCurrentSelection(generation, workspace, promptId)) {
setStatus(exportStatus, '');
showPortabilityStale();
return;
}
if (!response.ok) {
setStatus(exportStatus, 'prompts.export.error');
return;
}
setStatus(exportStatus, '');
downloadEnvelopeFile(
text,
filenameFromDisposition(response.headers.get('content-disposition')) ||
promptId + '.crank-prompt.json'
);
}
function clearPortabilityStale() {
clearChildren(importStaleHost);
}
function showPortabilityStale() {
clearPortabilityStale();
if (!importStaleHost) return;
var node = document.createElement('div');
node.className = 'prompt-stale';
node.setAttribute('role', 'alert');
node.setAttribute('data-testid', 'prompt-portability-stale');
node.textContent = t(
'prompts.portability.stale',
'The previous selection changed: this portability response was not applied.'
);
importStaleHost.appendChild(node);
}
function clearImportError() {
if (!importError) return;
importError.textContent = '';
importError.hidden = true;
}
function showImportError(message) {
if (!importError) return;
importError.textContent = message;
importError.hidden = false;
}
/// Смена выбора/workspace сбрасывает незавершённый предпросмотр: поздний ответ
/// отмечается как stale, а не приписывается другому Prompt.
function clearPortabilityTransient() {
pendingEnvelope = null;
clearChildren(importPreviewHost);
clearChildren(importConfirmHost);
clearPortabilityStale();
setStatus(importStatus, '');
clearImportError();
}
/// Подтверждение переноса одноразовое: после отмены, отправки или успешного импорта
/// оставшийся envelope не должен восстанавливаться сменой языка (Story 3.15, N1).
function clearPendingImport() {
pendingEnvelope = null;
clearChildren(importPreviewHost);
clearChildren(importConfirmHost);
}
function setImportBusy(value) {
importBusy = value;
if (!importSubmit) return;
importSubmit.disabled = value;
importSubmit.setAttribute('aria-busy', value ? 'true' : 'false');
importSubmit.textContent = value
? t('prompts.import.pending', 'Importing…')
: t('prompts.import.submit', 'Preview import');
}
function hasExactKeys(value, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
var actual = Object.keys(value).sort();
var expected = keys.slice().sort();
return actual.length === expected.length && actual.every(function (key, index) {
return key === expected[index];
});
}
function isBoundedInteger(value, min, max) {
return Number.isSafeInteger(value) && value >= min && value <= max;
}
/// Структурная проверка файла до подтверждения: те же поля и allowlist, что
/// принимает сервер. Содержимое definition оценивает сервер принятым парсером.
function parseImportEnvelope(text) {
var value;
try { value = JSON.parse(text); } catch (_error) { return null; }
if (!hasExactKeys(value, ['format', 'version', 'prompt', 'source'])) return null;
if (value.format !== 'crank-prompt-portability' || value.version !== 1) return null;
if (!hasExactKeys(value.prompt, ['name', 'description', 'sensitivity', 'arguments', 'messages'])) {
return null;
}
if (typeof value.prompt.name !== 'string' || typeof value.prompt.description !== 'string') {
return null;
}
if (['public', 'internal', 'secret'].indexOf(value.prompt.sensitivity) === -1) return null;
if (!Array.isArray(value.prompt.arguments) || !Array.isArray(value.prompt.messages)) return null;
if (!hasExactKeys(value.source, ['kind', 'version'])) return null;
if (value.source.kind !== 'draft' && value.source.kind !== 'published') return null;
if (!isBoundedInteger(value.source.version, 1, 4294967295)) return null;
return value;
}
function renderImportPreview(envelope) {
clearChildren(importPreviewHost);
if (!importPreviewHost) return;
var block = envelope.prompt;
var node = document.createElement('div');
node.className = 'prompt-import-preview';
node.setAttribute('data-testid', 'prompt-import-preview');
var title = document.createElement('p');
title.textContent = block.name;
node.appendChild(title);
var meta = document.createElement('p');
meta.textContent = [
t('prompts.import.preview.sensitivity', 'Sensitivity') + ': ' + block.sensitivity,
t('prompts.import.preview.arguments', 'Arguments') + ': ' + block.arguments.length,
t('prompts.import.preview.messages', 'Messages') + ': ' + block.messages.length,
].join(' · ');
node.appendChild(meta);
var consequence = document.createElement('p');
consequence.textContent = t(
'prompts.import.preview.draft',
'A new Draft will be created in this workspace; nothing will be published.'
);
node.appendChild(consequence);
var definition = document.createElement('pre');
definition.textContent = JSON.stringify(
{ arguments: block.arguments, messages: block.messages },
null,
2
);
node.appendChild(definition);
importPreviewHost.appendChild(node);
}
function renderImportConfirm(envelope) {
clearChildren(importConfirmHost);
if (!importConfirmHost) return;
pendingEnvelope = envelope;
var node = document.createElement('div');
node.className = 'prompt-import-confirm';
node.setAttribute('data-testid', 'prompt-import-confirm');
node.setAttribute('role', 'group');
var text = document.createElement('p');
text.textContent = envelope.prompt.name + ' · ' + t(
'prompts.import.preview.draft',
'A new Draft will be created in this workspace; nothing will be published.'
);
node.appendChild(text);
var accept = document.createElement('button');
accept.type = 'button';
accept.className = 'btn-new';
accept.setAttribute('data-testid', 'prompt-import-confirm-accept');
accept.textContent = t('prompts.import.confirm.accept', 'Create the Draft');
accept.addEventListener('click', function () { runImport(envelope); });
node.appendChild(accept);
var cancel = document.createElement('button');
cancel.type = 'button';
cancel.className = 'btn-secondary';
cancel.setAttribute('data-testid', 'prompt-import-cancel');
cancel.textContent = t('prompts.import.cancel', 'Cancel');
cancel.addEventListener('click', function () { clearPendingImport(); });
node.appendChild(cancel);
importConfirmHost.appendChild(node);
}
function errorCode(payload) {
return payload && payload.error && typeof payload.error.code === 'string'
? payload.error.code
: '';
}
/// Безопасные локализованные сообщения: только стабильный код/status API, без
/// содержимого definition, путей и внутренних данных.
function importFailureMessage(result) {
var code = errorCode(result.payload);
if (code === 'prompt_invalid_definition') {
return t(
'prompts.import.error.definition',
'The template definition is invalid; nothing was created.'
);
}
if (result.status === 400) {
return t(
'prompts.import.error.invalid',
'The file is not a valid Crank Prompt portability file.'
);
}
return t('prompts.import.error.generic', 'The Prompt could not be imported.');
}
async function runImport(envelope) {
if (!workspaceId || importBusy) return;
clearPendingImport();
clearImportError();
setStatus(importStatus, '');
var promptId = activePromptId;
var workspace = workspaceId;
var generation = loadGeneration;
setImportBusy(true);
try {
var result = await request('POST', basePath() + '/import', envelope);
// Поздний ответ импорта не приписывается другому Prompt/контексту.
if (!isCurrentSelection(generation, workspace, promptId)) {
showPortabilityStale();
loadList().catch(function () {});
return;
}
// Список отражает серверную правду независимо от смены выбора.
loadList().catch(function () {});
if (result.status === 201 && result.payload) {
setStatus(importStatus, 'prompts.import.done');
if (importFile) importFile.value = '';
return;
}
showImportError(importFailureMessage(result));
} catch (_error) {
if (isCurrentSelection(generation, workspace, promptId)) {
showImportError(t('prompts.import.error.generic', 'The Prompt could not be imported.'));
} else {
showPortabilityStale();
}
} finally {
setImportBusy(false);
}
}
if (exportLink) {
exportLink.addEventListener('click', function (event) {
event.preventDefault();
if (!activePromptId) return;
startExport(exportUrl(activePromptId, null), activePromptId);
});
}
if (importSubmit) {
importSubmit.addEventListener('click', function () {
if (importBusy) return;
clearImportError();
clearPendingImport();
clearPortabilityStale();
setStatus(importStatus, '');
var file = importFile && importFile.files && importFile.files[0];
if (!file) {
showImportError(t('prompts.import.select', 'Choose a portability file first.'));
return;
}
file
.text()
.then(function (text) {
var envelope = parseImportEnvelope(text);
if (!envelope) {
showImportError(
t(
'prompts.import.error.invalid',
'The file is not a valid Crank Prompt portability file.'
)
);
return;
}
renderImportPreview(envelope);
renderImportConfirm(envelope);
})
.catch(function () {
showImportError(
t(
'prompts.import.error.invalid',
'The file is not a valid Crank Prompt portability file.'
)
);
});
});
}
document.getElementById('prompt-new').addEventListener('click', function () {
loadGeneration += 1;
resetEditor();
document.getElementById('prompt-name').focus();
});
form.addEventListener('submit', function (event) { event.preventDefault(); saveDraft(); });
previewButton.addEventListener('click', preview);
publishButton.addEventListener('click', function () { requestLifecycle('publish'); });
archiveButton.addEventListener('click', function () { requestLifecycle('archive'); });
viewPublishedButton.addEventListener('click', loadPublishedVersion);
bindButton.addEventListener('click', requestBind);
bindAgentSelect.addEventListener('change', refreshStateLabel);
document.getElementById('prompt-confirm-save').addEventListener('click', function () {
var kind = pendingConfirm;
if (kind === 'save') return confirmSave();
if (kind === 'publish' || kind === 'archive') return confirmLifecycle(kind);
if (kind === 'bind') return confirmBind();
closeConfirmation();
});
document.getElementById('prompt-confirm-cancel').addEventListener('click', function () {
pendingSaveBody = null;
closeConfirmation();
});
reloadButton.addEventListener('click', function () { if (activePromptId) loadPrompt(activePromptId); });
document.getElementById('prompt-preview-arguments').addEventListener('input', resetPreview);
document.getElementById('prompt-name').addEventListener('input', markDefinitionDirty);
document.getElementById('prompt-description').addEventListener('input', markDefinitionDirty);
document.getElementById('prompt-arguments').addEventListener('input', markDefinitionDirty);
document.getElementById('prompt-messages').addEventListener('input', markDefinitionDirty);
dependenciesField().addEventListener('input', markDefinitionDirty);
window.addEventListener('crank:workspacechange', function (event) {
loadGeneration += 1;
previewGeneration += 1;
activePromptId = null;
activeVersion = null;
activeUpdatedAt = null;
activeStatus = null;
activePublishedVersion = null;
definitionDirty = false;
lastItems = [];
bindGeneration += 1;
workspaceId = event.detail && event.detail.id ? event.detail.id : null;
resetEditor();
loadList();
loadAgents();
});
// A language switch only re-renders the current state; it must never reload or
// replace unsaved new/edit fields (Story 3.12, R2).
window.addEventListener('crank:langchange', function () {
renderList(lastItems);
refreshStateLabel();
if (!publishedPanel.hidden && publishedStatus.textContent) {
setStatus(publishedStatus, publishedVersionNode.textContent ? 'prompts.published_loaded' : 'prompts.loading_published');
}
if (definitionDirty) setStatus(previewStatus, 'prompts.preview.requires_save');
// Story 3.15: уже показанные состояния переноса перерисовываются в новом языке.
if (!importBusy) setImportBusy(false);
if (pendingEnvelope && importPreviewHost && importPreviewHost.firstChild) {
renderImportPreview(pendingEnvelope);
renderImportConfirm(pendingEnvelope);
}
if (importStaleHost && importStaleHost.firstChild) showPortabilityStale();
if (!publishedPanel.hidden && publishedVersionNode.textContent) {
renderPublishedExport(activePublishedVersion);
}
});
(async function init() {
if (window.whenWorkspacesReady) await window.whenWorkspacesReady();
var current = window.getCurrentWorkspace ? window.getCurrentWorkspace() : null;
workspaceId = current ? current.id : null;
resetEditor();
if (workspaceId) loadList();
else setStatus(pageStatus, 'prompts.error.load');
loadAgents();
})();
})();