fix(assessment): center and restructure the creation dialog

This commit is contained in:
Sycun committed 2026-11-03 00:27:29 +08:00
1 parent 1931bf322a
commit 5c6edff1dd
7 files changed
+512 -24

No files matched your search

+15 -1
View File
@@ -103,6 +103,20 @@ try {
await click('[data-assessment-action=fact]'); await waitFor("document.getElementById('assessment-message').textContent.includes('已保存')");
await click('[data-tab=logs]'); assert.equal(await evaluate('window.XSS || 0'), 0, 'untrusted log rendered as HTML');
await click('[data-assessment-action=new]'); await waitFor("document.getElementById('assessment-create')?.open"); assert.equal(await evaluate("document.querySelector('[name=project_id] option:last-child').textContent"), '本地测试项目');
const dialogLayout = await evaluate("(()=>{const d=document.getElementById('assessment-create').getBoundingClientRect(), f=document.querySelector('#assessment-create .assessment-dialog-footer').getBoundingClientRect();return {left:d.left,right:d.right,top:d.top,bottom:d.bottom,footer:f.bottom,width:innerWidth,height:innerHeight}})()");
assert.ok(Math.abs(dialogLayout.left - (dialogLayout.width - dialogLayout.right)) < 3, 'create dialog is not horizontally centered');
assert.ok(dialogLayout.top >= 12 && dialogLayout.bottom <= dialogLayout.height - 12 && dialogLayout.footer <= dialogLayout.bottom, 'create dialog/footer escapes viewport');
await screenshot('desktop-create');
await evaluate("document.documentElement.dataset.theme='dark'"); await delay(300); await screenshot('desktop-dark-create'); await evaluate("document.documentElement.dataset.theme='light'");
await evaluate("document.getElementById('assessment-tools-search').value='no-match-fixture';document.getElementById('assessment-tools-search').dispatchEvent(new Event('input'))");
assert.equal(await evaluate("document.getElementById('assessment-tools-empty').hidden"), false);
await evaluate("document.getElementById('assessment-tools-search').value='inspect';document.getElementById('assessment-tools-search').dispatchEvent(new Event('input'))");
await click('[data-tool-selection=visible]');
assert.ok(await evaluate("document.getElementById('assessment-tools-count').textContent.includes('1 / 100')"));
await cdp('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await screenshot('mobile-create');
assert.ok(await evaluate("(()=>{const d=document.getElementById('assessment-create'),r=d.getBoundingClientRect(),f=d.querySelector('.assessment-dialog-footer').getBoundingClientRect();return r.left>=8&&r.right<=innerWidth-8&&f.bottom<=innerHeight-8&&d.scrollWidth<=d.clientWidth+1})()"), 'mobile create dialog overflows or hides footer');
await cdp('Emulation.setDeviceMetricsOverride', { width: 1440, height: 1000, deviceScaleFactor: 1, mobile: false });
await evaluate(`document.querySelector('[name=name]').value='Created in browser';document.querySelector('[name=goal]').value='Inspect fixture';document.querySelector('[name=scope]').value='Local fixture';document.querySelector('[name=criteria]').value='Record a fixture response';document.querySelector('[name=tools]').checked=true;document.getElementById('assessment-create-form').requestSubmit()`);
await waitFor("document.querySelector('#assessment-detail h2')?.textContent==='Created in browser'");
assert.ok((await evaluate('location.hash')).startsWith('#assessments?task=created-'), 'created task deep link missing');
@@ -119,7 +133,7 @@ try {
assert.equal(unauthorizedRequests,0,'a logged-in workbench request omitted its Bearer token');
for(const route of ['/api/assessments','/api/assessments/options','/api/assessments/fixture-assessment/report','/api/assessments/fixture-assessment/metrics']) assert.ok(authenticatedPaths.has(route),'missing authenticated request: '+route);
await evaluate('cleanupAssessmentsPage()');
console.log(JSON.stringify({ ok: true, screenshots: out, checks: ['real auth.js login and Bearer propagation', 'authenticated create/options/control/downloads', 'task selection', 'poll preserves draft', 'graph', 'candidate publishing controls', 'XSS escaping', 'create', 'start', 'approval', 'completion', 'mobile overflow'] }, null, 2));
console.log(JSON.stringify({ ok: true, screenshots: out, checks: ['real auth.js login and Bearer propagation', 'authenticated create/options/control/downloads', 'task selection', 'poll preserves draft', 'graph', 'candidate publishing controls', 'XSS escaping', 'create', 'start', 'approval', 'completion', 'mobile overflow', 'centered create modal and visible footer', 'tool search and bulk selection', 'desktop/dark/mobile create layout'] }, null, 2));
} finally {
if (socket) socket.close(); chrome.kill(); server.close();
}
+242
View File
@@ -274,3 +274,245 @@ html[data-theme=dark] #assessment-graph {
height:360px;
}
}
/* Explicit centering is required: the global reset removes dialog's UA margin. */
.assessment-dialog {
position: fixed;
inset: 0;
margin: auto;
width: min(680px, calc(100vw - 32px));
max-width: none;
max-height: calc(100vh - 32px);
max-height: calc(100dvh - 32px);
box-shadow: 0 24px 80px rgba(15, 23, 42, .24);
}
.assessment-dialog::backdrop {
background: rgba(15, 23, 42, .42);
-webkit-backdrop-filter: blur(3px);
backdrop-filter: blur(3px);
}
.assessment-create-dialog {
width: min(1020px, calc(100vw - 48px));
padding: 0;
overflow: hidden;
border-radius: 18px;
}
.assessment-create-dialog[open] { display: flex; }
#assessment-create-form {
display: flex;
flex-direction: column;
width: 100%;
min-width: 0;
min-height: 0;
height: min(800px, calc(100vh - 48px));
height: min(800px, calc(100dvh - 48px));
overflow: hidden;
}
.assessment-dialog-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
padding: 24px 28px 20px;
border-bottom: 1px solid var(--border-color);
flex: 0 0 auto;
}
.assessment-dialog-header h2 {
margin: 0;
font-size: 22px;
line-height: 1.35;
font-weight: 650;
letter-spacing: -.3px;
}
.assessment-dialog-header p {
margin: 7px 0 0;
color: var(--text-secondary);
font-size: 13px;
line-height: 1.6;
}
.assessment-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 32px;
width: 32px;
height: 32px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--text-secondary);
cursor: pointer;
}
.assessment-icon-button:hover { background: var(--bg-tertiary); color: var(--text-primary); }
.assessment-create-scroll {
flex: 1 1 auto;
min-height: 0;
padding: 24px 28px;
overflow: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
}
.assessment-create-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) 290px;
align-items: start;
gap: 28px;
}
.assessment-create-main, .assessment-runtime-panel { min-width: 0; }
.assessment-create-section + .assessment-create-section { margin-top: 24px; }
.assessment-create-dialog h3 {
margin: 0 0 14px;
font-size: 14px;
line-height: 1.5;
font-weight: 650;
color: var(--text-primary);
}
.assessment-create-dialog .assessment-field {
margin: 0 0 16px;
gap: 7px;
min-width: 0;
font-size: 13px;
}
.assessment-create-dialog .assessment-field > span { line-height: 1.5; font-weight: 500; }
.assessment-create-dialog .assessment-field small {
margin-left: 7px;
color: var(--text-secondary);
font-size: 11px;
font-weight: 400;
}
.assessment-required { color: var(--accent-color); margin-left: 4px; }
.assessment-create-dialog .assessment-field input,
.assessment-create-dialog .assessment-field textarea,
.assessment-create-dialog .assessment-field select,
.assessment-tool-toolbar input {
min-height: 40px;
padding: 9px 11px;
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--bg-primary);
color: var(--text-primary);
font: inherit;
font-size: 13px;
line-height: 1.5;
outline: none;
transition: border-color .15s, box-shadow .15s;
}
.assessment-create-dialog input::placeholder,
.assessment-create-dialog textarea::placeholder { color: var(--text-secondary); opacity: .65; }
.assessment-create-dialog .assessment-field textarea { resize: vertical; min-height: 76px; max-height: 220px; }
.assessment-create-dialog .assessment-field input:focus,
.assessment-create-dialog .assessment-field textarea:focus,
.assessment-create-dialog .assessment-field select:focus,
.assessment-tool-toolbar input:focus {
border-color: var(--accent-color);
box-shadow: 0 0 0 3px rgba(0, 102, 255, .10);
}
.assessment-create-dialog .assessment-field select:not([multiple]) {
-webkit-appearance: none;
appearance: none;
padding-right: 32px;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%236c757d' stroke-width='1.5'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 9px center;
background-size: 16px;
text-overflow: ellipsis;
}
.assessment-create-dialog .assessment-form-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 0 14px; }
.assessment-runtime-panel {
padding: 18px;
border: 1px solid var(--border-color);
border-radius: 12px;
background: var(--bg-secondary);
}
.assessment-runtime-panel .assessment-form-grid .assessment-field > span { min-height: 36px; display: flex; align-items: flex-end; }
.assessment-inline-hint {
margin: 8px 0 14px;
font-size: 12px;
line-height: 1.6;
color: var(--text-secondary);
}
.assessment-disclosure {
border-top: 1px solid var(--border-color);
padding-top: 13px;
}
.assessment-disclosure > summary {
font-size: 13px;
font-weight: 500;
color: var(--text-secondary);
cursor: pointer;
padding: 3px 0;
}
.assessment-disclosure > summary > span { font-size: 11px; font-weight: 400; margin-left: 8px; }
.assessment-disclosure[open] > summary { color: var(--text-primary); }
.assessment-disclosure-body { margin-top: 14px; }
.assessment-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.assessment-section-heading h3 { margin-bottom: 0; }
.assessment-selection-count { color: var(--accent-color); font-size: 12px; white-space: nowrap; }
.assessment-tool-toolbar { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
.assessment-tool-toolbar input { min-width: 0; width: 0; flex: 1; }
.assessment-text-button { padding: 6px 2px; border: 0; background: transparent; color: var(--text-secondary); font-size: 12px; cursor: pointer; white-space: nowrap; }
.assessment-text-button:hover { color: var(--accent-color); }
.assessment-create-dialog .assessment-tool-picker { max-height: 240px; border: 1px solid var(--border-color); border-radius: 10px; background: var(--bg-primary); }
.assessment-create-dialog .assessment-tool-option { padding: 11px 12px; gap: 10px; cursor: pointer; }
.assessment-tool-option[hidden] { display: none; }
.assessment-tool-option:last-of-type { border-bottom: 0; }
.assessment-tool-option:hover, .assessment-tool-option.selected { background: rgba(0, 102, 255, .045); }
.assessment-create-dialog .assessment-tool-option input { flex: 0 0 16px; width: 16px; height: 16px; margin-top: 3px; accent-color: var(--accent-color); }
.assessment-tool-option > span { min-width: 0; }
.assessment-tool-option strong { display: block; font-size: 12px; font-weight: 600; overflow-wrap: anywhere; }
.assessment-tool-option small { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; margin-top: 3px; }
#assessment-tools-empty { padding: 14px; margin: 0; }
.assessment-dialog-footer {
flex: 0 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
gap: 18px;
padding: 16px 28px;
border-top: 1px solid var(--border-color);
background: var(--bg-primary);
}
.assessment-footer-copy { min-width: 0; font-size: 12px; color: var(--text-secondary); line-height: 1.6; }
#assessment-create-error:empty { display: none; }
.assessment-dialog-footer .assessment-actions { flex-wrap: nowrap; flex-shrink: 0; }
.assessment-dialog-footer button { min-height: 40px; padding: 9px 18px; border-radius: 8px; font-size: 13px; }
.assessment-create-dialog button:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 3px; }
@media (max-width: 760px) {
.assessment-create-dialog { width: calc(100vw - 24px); max-height: calc(100vh - 24px); max-height: calc(100dvh - 24px); border-radius: 14px; }
#assessment-create-form { height: calc(100vh - 24px); height: calc(100dvh - 24px); }
.assessment-dialog-header { padding: 18px 18px 15px; gap: 12px; }
.assessment-dialog-header h2 { font-size: 20px; }
.assessment-create-scroll { padding: 18px; }
.assessment-create-grid { grid-template-columns: minmax(0, 1fr); gap: 20px; }
.assessment-dialog-footer { padding: 13px 18px; gap: 10px; }
.assessment-footer-copy > p:last-child { display: none; }
.assessment-dialog-footer .assessment-actions { margin-left: auto; }
.assessment-tool-toolbar { flex-wrap: wrap; }
.assessment-tool-toolbar input { flex-basis: 100%; width: 100%; }
}
@media (max-width: 420px) {
.assessment-create-main > .assessment-create-section > .assessment-form-grid { grid-template-columns: minmax(0, 1fr); }
}
.assessment-create-dialog .btn-secondary {
border: 1px solid var(--border-color);
background: var(--bg-primary);
color: var(--text-primary);
}
.assessment-create-dialog .btn-secondary:hover { background: var(--bg-tertiary); }
.assessment-create-dialog .btn-secondary:disabled { opacity: .45; cursor: not-allowed; }
html[data-theme="dark"] .assessment-create-dialog .assessment-field input,
html[data-theme="dark"] .assessment-create-dialog .assessment-field textarea,
html[data-theme="dark"] .assessment-create-dialog .assessment-field select,
html[data-theme="dark"] .assessment-create-dialog .assessment-tool-toolbar input {
border-color: var(--border-color);
background-color: var(--bg-primary);
color: var(--text-primary);
}
html[data-theme="dark"] .assessment-create-dialog input::placeholder,
html[data-theme="dark"] .assessment-create-dialog textarea::placeholder { color: var(--text-secondary); opacity: .78; }
html[data-theme="dark"] .assessment-create-dialog .btn-secondary {
background: var(--bg-primary);
border-color: var(--border-color);
color: var(--text-primary);
}
html[data-theme="dark"] .assessment-create-dialog .btn-secondary:hover { background: var(--bg-tertiary); }
+30 -1
View File
@@ -5271,6 +5271,35 @@
"execution_error": "Execution error",
"budget": "Budget unavailable",
"cancelled": "Cancelled"
}
},
"createIntro": "Define the goal, scope and execution settings. Save a draft, then start when ready.",
"taskBasics": "Goal & scope",
"optional": "Optional",
"noProject": "No linked project",
"namePlaceholder": "e.g. Staging login and access review",
"goalPlaceholder": "What should be verified? Describe the intended result and evidence.",
"scopePlaceholder": "Authorized domains, IPs or environments, plus excluded targets and actions.",
"materialPlaceholder": "Existing clues, test-account notes or material paths.",
"criteriaPlaceholder": "One criterion per line; leave blank to use the assessment goal.",
"materialsAndCriteria": "Materials & acceptance criteria",
"searchTools": "Search tool names or capabilities",
"selectVisible": "Select matches",
"clearSelection": "Clear",
"noMatchingTools": "No matching tools",
"selectionHint": "Choose tools available to this assessment. Search to narrow the list.",
"runSettings": "Run settings",
"approvalPolicyShort": "Use global policy",
"approvalManualShort": "Approve every call",
"approvalPolicyHint": "Runs autonomously when global approval is off. Calls requiring approval wait in the plan.",
"runMinutes": "Duration (minutes)",
"advancedSettings": "Advanced models & skills",
"noSkillsAvailable": "No reference skills available. Default capabilities remain usable.",
"draftHint": "Saving a draft does not execute tools.",
"selectedTools": "Selected",
"toolLimit": "Select at most 100 tools.",
"chooseTools": "Select 1–100 tools.",
"concurrencyShort": "Workers (1–4)",
"runtimeBudgetHint": "Duration includes approval waits. Budgets can be adjusted while paused.",
"loadingOptions": "Loading…"
}
}
+30 -1
View File
@@ -5284,6 +5284,35 @@
"execution_error": "Ошибка выполнения",
"budget": "Недостаточный бюджет",
"cancelled": "Отменено"
}
},
"createIntro": "Задайте цель, границы и параметры. Сохраните черновик и запустите, когда будете готовы.",
"taskBasics": "Цель и границы",
"optional": "Необязательно",
"noProject": "Без проекта",
"namePlaceholder": "Например: проверка входа и прав доступа",
"goalPlaceholder": "Что нужно проверить? Опишите результат и необходимые доказательства.",
"scopePlaceholder": "Разрешённые домены, IP или среды, а также исключённые цели и действия.",
"materialPlaceholder": "Известные сведения, описание тестовых аккаунтов или пути к материалам.",
"criteriaPlaceholder": "По одному критерию в строке; пустое поле означает использование цели оценки.",
"materialsAndCriteria": "Материалы и критерии приёмки",
"searchTools": "Поиск по названию или функции",
"selectVisible": "Выбрать найденные",
"clearSelection": "Очистить",
"noMatchingTools": "Совпадений нет",
"selectionHint": "Выберите доступные для этой оценки инструменты. Используйте поиск.",
"runSettings": "Параметры запуска",
"approvalPolicyShort": "Глобальная политика",
"approvalManualShort": "Одобрять каждый вызов",
"approvalPolicyHint": "При выключенном глобальном одобрении работа автономна. Остальные вызовы ожидают подтверждения в плане.",
"runMinutes": "Время (минуты)",
"advancedSettings": "Модели и навыки",
"noSkillsAvailable": "Справочных навыков нет. Можно использовать стандартные возможности.",
"draftHint": "Сохранение черновика не запускает инструменты.",
"selectedTools": "Выбрано",
"toolLimit": "Выберите не более 100 инструментов.",
"chooseTools": "Выберите от 1 до 100 инструментов.",
"concurrencyShort": "Исполнители (1–4)",
"runtimeBudgetHint": "Время включает ожидание одобрения. Бюджет можно изменить во время паузы.",
"loadingOptions": "Загрузка…"
}
}
+30 -1
View File
@@ -5259,6 +5259,35 @@
"execution_error": "执行错误",
"budget": "预算不足",
"cancelled": "已取消"
}
},
"createIntro": "定义目标、范围和执行方式,保存为草稿后再启动。",
"taskBasics": "目标与范围",
"optional": "可选",
"noProject": "不关联项目",
"namePlaceholder": "例如:测试环境登录与权限测评",
"goalPlaceholder": "希望验证什么?例如:检查登录与权限边界,交付可复现证据。",
"scopePlaceholder": "填写授权域名、IP 或环境,并列出禁止测试的目标与操作。",
"materialPlaceholder": "已有线索、测试账号说明或材料路径。",
"criteriaPlaceholder": "每行一项;留空则按测评目标验收。",
"materialsAndCriteria": "补充材料与验收条件",
"searchTools": "搜索工具名称或功能",
"selectVisible": "选择匹配项",
"clearSelection": "清空",
"noMatchingTools": "没有匹配的工具",
"selectionHint": "请选择本次测评可用的工具,可随时搜索和调整。",
"runSettings": "运行设置",
"approvalPolicyShort": "沿用全局策略",
"approvalManualShort": "每次调用人工批准",
"approvalPolicyHint": "全局审批关闭时自主执行;需要审批的调用将在计划中等待确认。",
"runMinutes": "运行时长(分钟)",
"advancedSettings": "高级模型与技能配置",
"noSkillsAvailable": "暂无可选技能,使用默认能力即可。",
"draftHint": "保存草稿不会立即执行工具。",
"selectedTools": "已选",
"toolLimit": "最多选择 100 个工具。",
"chooseTools": "请选择 1–100 个工具。",
"concurrencyShort": "并发数量(1–4)",
"runtimeBudgetHint": "运行时长包含审批等待,预算可在暂停后调整。",
"loadingOptions": "加载配置…"
}
}
+74
View File
@@ -0,0 +1,74 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
function harness(responseStatus = 200) {
const requests = [];
const context = {
Headers, Response, Blob,
URL: { createObjectURL: () => 'blob:fixture', revokeObjectURL() {} },
console, Element: class Element {},
setTimeout() {}, clearTimeout() {}, setInterval() {}, clearInterval() {},
localStorage: { setItem() {}, removeItem() {}, getItem() { return null; } },
document: {
getElementById() { return null; }, querySelector() { return null; },
querySelectorAll() { return []; }, addEventListener() {},
createElement() { return { click() {}, style: {} }; },
},
async fetch(url, options = {}) {
requests.push({ url, ...options, headers: new Headers(options.headers) });
return new Response(JSON.stringify(responseStatus === 401 ? { error: 'unauthorized' } : { ok: true }), { status: responseStatus });
},
};
context.window = context;
vm.createContext(context);
// Load the actual application authentication implementation, not a mock apiFetch.
vm.runInContext(fs.readFileSync('web/static/js/auth.js', 'utf8'), context);
let source = fs.readFileSync('web/static/js/assessments.js', 'utf8');
const end = source.lastIndexOf('})();');
assert.ok(end > 0);
source = source.slice(0, end) + '\nwindow.assessmentTest = {api, onClick, select(id) {selected=id;task={id};}};\n' + source.slice(end);
vm.runInContext(source, context);
vm.runInContext("saveAuth('fixture-session', new Date(Date.now()+60000), {user:{username:'fixture'},permissions:['assessment:read','assessment:write']})", context);
return { context, requests, workbench: context.assessmentTest };
}
test('assessment listing, options and creation use the real login Bearer transport', async () => {
const { workbench, requests } = harness();
await workbench.api('');
await workbench.api('/options');
await workbench.api('', 'POST', { name: 'fixture' });
assert.equal(requests.length, 3);
for (const r of requests) assert.equal(r.headers.get('Authorization'), 'Bearer fixture-session');
assert.equal(requests[2].method, 'POST');
assert.equal(JSON.parse(requests[2].body).name, 'fixture');
});
test('assessment report and metrics downloads carry the login token', async () => {
const { workbench, requests } = harness();
workbench.select('fixture-task');
for (const action of ['report', 'metrics']) {
const button = { dataset: { assessmentAction: action }, disabled: false };
await workbench.onClick({ target: { closest: () => button } });
}
assert.deepEqual(requests.map(r => r.url), ['/api/assessments/fixture-task/report', '/api/assessments/fixture-task/metrics']);
for (const r of requests) assert.equal(r.headers.get('Authorization'), 'Bearer fixture-session');
});
test('assessment requests wait for login and use the renewed token', async () => {
const { context, workbench, requests } = harness();
vm.runInContext('authTokenExpiry = new Date(0)', context);
const pending = workbench.api('/options');
await Promise.resolve();
assert.equal(requests.length, 0, 'anonymous request sent while waiting for login');
vm.runInContext("saveAuth('renewed-fixture', new Date(Date.now()+60000)); resolveAuthPromises(true)", context);
await pending;
assert.equal(requests[0].headers.get('Authorization'), 'Bearer renewed-fixture');
});
test('assessment unauthorized response invokes normal session invalidation', async () => {
const { context, workbench } = harness(401);
await assert.rejects(workbench.api(''));
assert.equal(vm.runInContext('isTokenValid()', context), false);
});
+91 -20
View File
@@ -113,26 +113,97 @@
} catch (err) { if (version === epoch) message(err.message, true); }
finally { loading = false; }
}
let createDialogLoading = false;
async function createDialog() {
options = await api('/options');
const prior = document.getElementById('assessment-create'); if (prior) prior.remove();
const dialog = document.createElement('dialog'); dialog.id = 'assessment-create'; dialog.className = 'assessment-dialog';
const field = (name, type, value, extra) => '<label class="assessment-field">' + esc(tr(name)) + '<input name="' + name + '" type="' + type + '" value="' + esc(value || '') + '" ' + (extra || '') + '></label>';
dialog.innerHTML = '<form id="assessment-create-form"><h2>' + esc(tr('new')) + '</h2>' + field('name', 'text', '', 'required maxlength="200"') +
['goal', 'scope', 'material', 'criteria'].map(name => '<label class="assessment-field">' + esc(tr(name)) + '<textarea name="' + name + '" rows="3" maxlength="' + (name === 'material' ? '24000' : '12000') + '"' + (!['material','criteria'].includes(name) ? ' required' : '') + '></textarea></label>').join('') +
'<div class="assessment-form-grid">' + '<label class="assessment-field">' + esc(tr('project')) + '<select name="project_id"><option value="">' + esc(tr('none')) + '</option>' + (options.projects || []).map(p => '<option value="' + esc(p.id) + '">' + esc(p.name) + '</option>').join('') + '</select></label>' + '<label class="assessment-field">' + esc(tr('model')) + '<select name="model">' + options.models.map(m => '<option value="' + esc(m.id) + '"' + (m.default ? ' selected' : '') + '>' + esc((m.name || m.id || tr('default')) + ' · ' + m.model) + '</option>').join('') + '</select></label>' +
'<label class="assessment-field">' + esc(tr('approvalMode')) + '<select name="approval_mode"><option value="policy">' + esc(tr('approvalPolicy')) + '</option><option value="manual">' + esc(tr('approvalManual')) + '</option></select></label>' + field('concurrency', 'number', 2, 'min="1" max="4" required') + field('token_budget', 'number', 200000, 'min="4000" max="10000000" required') + field('duration', 'number', 120, 'min="1" max="1440" required') + field('max_rounds', 'number', 12, 'min="1" max="50" required') + '</div>' +
'<details><summary>' + esc(tr('specialists')) + '</summary><label class="assessment-field">'+esc(tr('reviewModel'))+'<select name="reviewer_model"><option value="">'+esc(tr('inheritModel'))+'</option>'+options.models.map(m=>'<option value="'+esc(m.id)+'">'+esc(m.name||m.id)+'</option>').join('')+'</select></label>' + ['general','recon','auth','validation','verification'].map(p=>'<label class="assessment-field">'+esc(tr('profiles.'+p))+'<select name="worker_model_'+p+'"><option value="">'+esc(tr('inheritModel'))+'</option>'+options.models.map(m=>'<option value="'+esc(m.id)+'">'+esc(m.name||m.id)+'</option>').join('')+'</select></label>').join('') + '<label class="assessment-field">'+esc(tr('selectedSkills'))+'<select name="skill_ids" multiple size="4">'+(options.skills||[]).map(id=>'<option value="'+esc(id)+'">'+esc(id)+'</option>').join('')+'</select></label></details>' +
'<fieldset><legend>' + esc(tr('tools')) + '</legend><p>' + esc(tr('toolsHint')) + '</p><div class="assessment-tool-picker">' + options.tools.map(tool => '<label><input type="checkbox" name="tools" value="' + esc(tool.name) + '"><span><strong>' + esc(tool.name) + '</strong><small>' + esc(tool.description) + '</small></span></label>').join('') + '</div></fieldset><p id="assessment-create-error" role="alert"></p><div class="assessment-actions"><button type="button" class="btn-secondary" data-assessment-action="cancel-create">' + esc(tr('cancel')) + '</button><button class="btn-primary" type="submit">' + esc(tr('createDraft')) + '</button></div></form>';
document.body.appendChild(dialog); dialog.addEventListener('click', onClick);
dialog.querySelector('form').addEventListener('submit', async ev => {
ev.preventDefault(); const submit = dialog.querySelector('[type=submit]'); submit.disabled = true;
const data = new FormData(ev.target), body = Object.fromEntries(data.entries());
body.tools = data.getAll('tools'); body.criteria=String(data.get('criteria')||'').split(/\n/).map(s=>s.trim()).filter(Boolean); body.skill_ids=data.getAll('skill_ids'); body.worker_models={}; ['general','recon','auth','validation','verification'].forEach(p=>{const key='worker_model_'+p; if(data.get(key)) body.worker_models[p]=data.get(key); delete body[key];}); ['concurrency', 'token_budget', 'max_rounds'].forEach(key => body[key] = Number(body[key])); body.remaining_seconds = Number(body.duration) * 60; delete body.duration;
try { const created = await api('', 'POST', body); selected = created.assessment.id; history.replaceState(null, '', '#assessments?task=' + encodeURIComponent(selected)); events = []; after = 0; task = created.assessment; dialog.close(); dialog.remove(); tab = 'overview'; await refresh(true); }
catch (err) { dialog.querySelector('#assessment-create-error').textContent = err.message; submit.disabled = false; }
});
dialog.showModal();
if (createDialogLoading || document.getElementById('assessment-create')?.open) return;
createDialogLoading = true;
const version = epoch;
try {
options = await api('/options');
if (version !== epoch || !root()) return;
const prior = document.getElementById('assessment-create');
if (prior) prior.remove();
const dialog = document.createElement('dialog');
dialog.id = 'assessment-create';
dialog.className = 'assessment-dialog assessment-create-dialog';
dialog.setAttribute('aria-labelledby', 'assessment-create-title');
dialog.setAttribute('aria-describedby', 'assessment-create-intro');
const required = '<span class="assessment-required" aria-hidden="true">*</span>';
const field = (name, type, value, extra) => '<label class="assessment-field"><span>' + esc(tr(name === 'concurrency' ? 'concurrencyShort' : name)) + '</span><input name="' + name + '" type="' + type + '" value="' + esc(value ?? '') + '" ' + (extra || '') + '></label>';
const textarea = (name, rows, mandatory, placeholder) => '<label class="assessment-field"><span>' + esc(tr(name)) + (mandatory ? required : '') + '</span><textarea name="' + name + '" rows="' + rows + '" maxlength="' + (name === 'material' ? '24000' : '12000') + '" placeholder="' + esc(tr(placeholder)) + '"' + (mandatory ? ' required' : '') + '></textarea></label>';
const modelOptions = (inherit) => (inherit ? '<option value="">' + esc(tr('inheritModel')) + '</option>' : '') + options.models.map(m => '<option value="' + esc(m.id) + '"' + (!inherit && m.default ? ' selected' : '') + '>' + esc((m.name || m.id || tr('default')) + (m.model ? ' · ' + m.model : '')) + '</option>').join('');
const closeIcon = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>';
dialog.innerHTML = '<form id="assessment-create-form">' +
'<header class="assessment-dialog-header"><div><h2 id="assessment-create-title">' + esc(tr('new')) + '</h2><p id="assessment-create-intro">' + esc(tr('createIntro')) + '</p></div><button type="button" class="assessment-icon-button" data-assessment-action="cancel-create" aria-label="' + esc(tr('cancel')) + '">' + closeIcon + '</button></header>' +
'<div class="assessment-create-scroll"><div class="assessment-create-grid"><div class="assessment-create-main">' +
'<section class="assessment-create-section"><h3>' + esc(tr('taskBasics')) + '</h3><div class="assessment-form-grid">' +
'<label class="assessment-field"><span>' + esc(tr('name')) + required + '</span><input name="name" type="text" required maxlength="200" placeholder="' + esc(tr('namePlaceholder')) + '" autofocus></label>' +
'<label class="assessment-field"><span>' + esc(tr('project')) + '<small>' + esc(tr('optional')) + '</small></span><select name="project_id"><option value="">' + esc(tr('noProject')) + '</option>' + (options.projects || []).map(p => '<option value="' + esc(p.id) + '">' + esc(p.name) + '</option>').join('') + '</select></label></div>' +
textarea('goal', 3, true, 'goalPlaceholder') + textarea('scope', 3, true, 'scopePlaceholder') +
'<details class="assessment-disclosure"><summary>' + esc(tr('materialsAndCriteria')) + '<span>' + esc(tr('optional')) + '</span></summary><div class="assessment-disclosure-body">' + textarea('material', 2, false, 'materialPlaceholder') + textarea('criteria', 2, false, 'criteriaPlaceholder') + '</div></details></section>' +
'<section class="assessment-create-section"><div class="assessment-section-heading"><h3>' + esc(tr('tools')) + required + '</h3><span id="assessment-tools-count" class="assessment-selection-count" role="status"></span></div>' +
'<div class="assessment-tool-toolbar"><input type="search" id="assessment-tools-search" placeholder="' + esc(tr('searchTools')) + '" aria-label="' + esc(tr('searchTools')) + '"><button type="button" class="btn-secondary btn-small" data-tool-selection="visible">' + esc(tr('selectVisible')) + '</button><button type="button" class="assessment-text-button" data-tool-selection="clear">' + esc(tr('clearSelection')) + '</button></div>' +
'<div class="assessment-tool-picker">' + options.tools.map(tool => '<label class="assessment-tool-option" data-tool-search="' + esc((tool.name + ' ' + tool.description).toLowerCase()) + '"><input type="checkbox" name="tools" value="' + esc(tool.name) + '"><span><strong>' + esc(tool.name) + '</strong><small title="' + esc(tool.description) + '">' + esc(tool.description) + '</small></span></label>').join('') + '<p id="assessment-tools-empty" class="assessment-inline-hint" hidden>' + esc(tr('noMatchingTools')) + '</p></div><p class="assessment-inline-hint">' + esc(tr('selectionHint')) + '</p></section></div>' +
'<aside class="assessment-runtime-panel"><h3>' + esc(tr('runSettings')) + '</h3><label class="assessment-field"><span>' + esc(tr('model')) + '</span><select name="model">' + modelOptions(false) + '</select></label>' +
'<label class="assessment-field"><span>' + esc(tr('approvalMode')) + '</span><select name="approval_mode"><option value="policy">' + esc(tr('approvalPolicyShort')) + '</option><option value="manual">' + esc(tr('approvalManualShort')) + '</option></select></label>' +
'<p class="assessment-inline-hint">' + esc(tr('approvalPolicyHint')) + '</p><div class="assessment-form-grid">' + field('concurrency', 'number', 2, 'min="1" max="4" required') + field('runMinutes', 'number', 120, 'min="1" max="1440" required') + field('token_budget', 'number', 200000, 'min="4000" max="10000000" required') + field('max_rounds', 'number', 12, 'min="1" max="50" required') + '</div><p class="assessment-inline-hint">' + esc(tr('runtimeBudgetHint')) + '</p>' +
'<details class="assessment-disclosure"><summary>' + esc(tr('advancedSettings')) + '</summary><div class="assessment-disclosure-body"><label class="assessment-field"><span>' + esc(tr('reviewModel')) + '</span><select name="reviewer_model">' + modelOptions(true) + '</select></label>' +
['general', 'recon', 'auth', 'validation', 'verification'].map(p => '<label class="assessment-field"><span>' + esc(tr('profiles.' + p)) + '</span><select name="worker_model_' + p + '">' + modelOptions(true) + '</select></label>').join('') +
'<label class="assessment-field"><span>' + esc(tr('selectedSkills')) + '</span><select name="skill_ids" multiple size="4">' + (options.skills || []).map(id => '<option value="' + esc(id) + '">' + esc(id) + '</option>').join('') + '</select></label>' + (!(options.skills || []).length ? '<p class="assessment-inline-hint">' + esc(tr('noSkillsAvailable')) + '</p>' : '') + '</div></details></aside></div></div>' +
'<footer class="assessment-dialog-footer"><div class="assessment-footer-copy"><p id="assessment-create-error" role="alert"></p><p>' + esc(tr('draftHint')) + '</p></div><div class="assessment-actions"><button type="button" class="btn-secondary" data-assessment-action="cancel-create">' + esc(tr('cancel')) + '</button><button class="btn-primary" type="submit">' + esc(tr('createDraft')) + '</button></div></footer></form>';
document.body.appendChild(dialog);
dialog.addEventListener('close', () => dialog.remove());
dialog.addEventListener('click', onClick);
const checkboxes = () => [...dialog.querySelectorAll('input[name=tools]')];
const updateSelection = () => {
const boxes = checkboxes(), count = boxes.filter(b => b.checked).length;
dialog.querySelector('#assessment-tools-count').textContent = tr('selectedTools') + ' ' + count + ' / 100';
boxes.forEach(b => b.closest('label').classList.toggle('selected', b.checked));
const visible = boxes.filter(b => !b.closest('label').hidden);
dialog.querySelector('[data-tool-selection=visible]').disabled = !visible.length || count + visible.filter(b => !b.checked).length > 100;
dialog.querySelector('#assessment-tools-empty').hidden = visible.length > 0;
};
dialog.querySelector('#assessment-tools-search').addEventListener('input', ev => {
const query = ev.target.value.trim().toLowerCase();
dialog.querySelectorAll('.assessment-tool-option').forEach(row => { row.hidden = !row.dataset.toolSearch.includes(query); });
updateSelection();
});
dialog.addEventListener('change', ev => {
if (ev.target.name !== 'tools') return;
if (checkboxes().filter(b => b.checked).length > 100) { ev.target.checked = false; dialog.querySelector('#assessment-create-error').textContent = tr('toolLimit'); }
updateSelection();
});
dialog.querySelectorAll('[data-tool-selection]').forEach(btn => btn.addEventListener('click', () => {
checkboxes().forEach(b => { if (btn.dataset.toolSelection === 'clear') b.checked = false; else if (!b.closest('label').hidden) b.checked = true; });
updateSelection();
}));
dialog.querySelector('form').addEventListener('submit', async ev => {
ev.preventDefault();
const submit = dialog.querySelector('[type=submit]'), error = dialog.querySelector('#assessment-create-error');
error.textContent = '';
const data = new FormData(ev.target), body = Object.fromEntries(data.entries());
body.tools = data.getAll('tools');
if (!body.tools.length || body.tools.length > 100) { error.textContent = tr('chooseTools'); dialog.querySelector('#assessment-tools-search').focus(); return; }
body.criteria = String(data.get('criteria') || '').split(/\n/).map(s => s.trim()).filter(Boolean);
body.skill_ids = data.getAll('skill_ids');
body.worker_models = {};
['general', 'recon', 'auth', 'validation', 'verification'].forEach(p => { const key = 'worker_model_' + p; if (data.get(key)) body.worker_models[p] = data.get(key); delete body[key]; });
['concurrency', 'token_budget', 'max_rounds'].forEach(key => body[key] = Number(body[key]));
body.remaining_seconds = Number(body.runMinutes) * 60;
delete body.runMinutes;
submit.disabled = true;
try {
const created = await api('', 'POST', body);
selected = created.assessment.id;
history.replaceState(null, '', '#assessments?task=' + encodeURIComponent(selected));
events = []; after = 0; task = created.assessment; tab = 'overview';
dialog.close();
await refresh(true);
} catch (err) { error.textContent = err.message; submit.disabled = false; }
});
updateSelection();
dialog.showModal();
} finally { createDialogLoading = false; }
}
function budgetDialog() {
if (!task || !can('assessment:write')) return;
@@ -147,7 +218,7 @@
if (action === 'select') { epoch++; selected = target.dataset.id; history.replaceState(null, '', '#assessments?task=' + encodeURIComponent(selected)); task = null; events = []; after = 0; delete root().dataset.updated; detail(); await refresh(true); return; }
if (action === 'tab') { tab = target.dataset.tab; detail(); return; }
if (action === 'refresh') { await refresh(true); return; }
if (action === 'new') { await createDialog(); return; }
if (action === 'new') { const label=target.textContent; target.disabled=true;target.textContent=tr('loadingOptions');try{await createDialog();}finally{target.textContent=label;target.disabled=false;}return; }
if (action === 'cancel-budget') { document.getElementById('assessment-budget').remove(); return; }
if (action === 'budget') { budgetDialog(); return; }
if (action === 'cancel-create') { document.getElementById('assessment-create').close(); return; }