mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-11-23 04:41:41 +01:00
fix(assessment): add select-all tools with bounded bulk selection
This commit is contained in:
1 parent
6be4477e08
commit
cb77d0578c
6 files changed
+47
-7
No files matched your search
@@ -14,6 +14,7 @@ const now = () => new Date().toISOString();
|
||||
let sequence = 0;
|
||||
const authenticatedPaths = new Set();
|
||||
let unauthorizedRequests = 0;
|
||||
const fixtureTools = [{ name: 'inspect', description: 'Inspect local fixture' }, ...Array.from({ length: 104 }, (_, i) => ({ name: 'fixture_tool_' + String(i + 1).padStart(3, '0'), description: 'Local tool fixture' }))];
|
||||
const fixtureSession = { token: 'assessment-fixture-session', expires_at: new Date(Date.now()+3600000).toISOString(), user: {id:'fixture-user',username:'fixture'}, roles:['admin'], scope:'all', permissions:['assessment:read','assessment:write','assessment:delete','agent:execute','hitl:write','project:read','project:write','asset:write','vulnerability:write','skills:read'] };
|
||||
const task = { id: 'fixture-assessment', name: '本地测评 · 浏览器验证', goal: '核验本地隔离测试数据', scope: '仅使用浏览器测试夹具,无外部目标', material: '已提供两个测试端点', strategy: '先核验响应,再检查访问控制边界', model: 'fixture', tools: ['inspect'], approval_mode: 'manual', concurrency: 2, token_budget: 200000, tokens: 1250, reserved_tokens: 0, remaining_seconds: 7200, deadline: 0, rounds: 2, max_rounds: 12, status: 'paused', reason: 'user_paused', summary: '已记录响应证据,下一步检查访问控制。', project_id: 'fixture-project', created_at: now(), updated_at: now(), steps: [
|
||||
{ id: 's1', key: 'inspect', title: '检查响应和服务信息', instruction: '读取测试夹具并记录响应。', depends_on: [], status: 'completed', result: '响应证据已记录。', checkpoint: '服务响应已保存,后续可复用。', evidence: [{ kind: 'fact', title: '已记录测试响应', detail: '本地测试数据返回固定响应。', execution_ids: ['fixture-execution-1'] }] },
|
||||
@@ -51,7 +52,7 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (url.pathname === '/api/auth/validate') {send(fixtureSession);return;}
|
||||
if (url.pathname.endsWith('/report')) {res.setHeader('Content-Type','text/markdown');res.end('# Fixture assessment report');return;}
|
||||
if (url.pathname === '/api/assessments/options') { send({ models: [{ id: 'fixture', name: 'Fixture', model: 'local-test' }], tools: [{ name: 'inspect', description: 'Inspect local fixture' }], projects: [{id:'fixture-project',name:'本地测试项目'}] }); return; }
|
||||
if (url.pathname === '/api/assessments/options') { send({ models: [{ id: 'fixture', name: 'Fixture', model: 'local-test' }], tools: fixtureTools, projects: [{id:'fixture-project',name:'本地测试项目'}] }); return; }
|
||||
if (url.pathname === '/api/assessments' && req.method === 'POST') {
|
||||
const created = { ...task, ...input, id: 'created-' + (++sequence), status: 'draft', steps: [], tokens: 0, rounds: 0, created_at: now(), updated_at: now() }; tasks.unshift(created); send({ assessment: created }); return;
|
||||
}
|
||||
@@ -156,6 +157,9 @@ 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"), '本地测试项目');
|
||||
assert.equal(await evaluate("document.querySelector('[data-tool-selection=all]').textContent"),'全选');
|
||||
assert.equal(await evaluate("document.querySelector('[data-tool-selection=all]').disabled"),false,'more than 100 tools disabled bulk selection');
|
||||
assert.equal(await evaluate("getComputedStyle(document.querySelector('[data-tool-selection=visible]')).display"),'none','search-specific action shown without search');
|
||||
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');
|
||||
@@ -166,6 +170,20 @@ try {
|
||||
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 evaluate("document.getElementById('assessment-tools-search').value='fixture_tool_104';document.getElementById('assessment-tools-search').dispatchEvent(new Event('input'))");
|
||||
await click('[data-tool-selection=visible]');
|
||||
assert.equal(await evaluate("document.querySelectorAll('input[name=tools]:checked').length"),2,'filtered selection discarded an existing selection');
|
||||
await click('[data-tool-selection=all]');
|
||||
assert.equal(await evaluate("document.querySelectorAll('input[name=tools]:checked').length"),100,'select all must fill the limit even while filtering');
|
||||
assert.equal(await evaluate("document.querySelector('[name=tools][value=fixture_tool_104]').checked"),true,'select all discarded a prior selection');
|
||||
assert.ok(await evaluate("document.getElementById('assessment-tools-selection-note').textContent.includes('仍有部分工具未选中')"),'partial bulk selection was not disclosed');
|
||||
await evaluate("document.getElementById('assessment-tools-search').value='';document.getElementById('assessment-tools-search').dispatchEvent(new Event('input'));document.querySelector('.assessment-tool-toolbar').scrollIntoView()");
|
||||
await screenshot('desktop-tools-select-all');
|
||||
await click('[data-tool-selection=clear]');
|
||||
assert.equal(await evaluate("document.querySelectorAll('input[name=tools]:checked').length"),0,'clear did not clear hidden selections');
|
||||
assert.equal(await evaluate("document.getElementById('assessment-tools-selection-note').textContent"),'','clear left a stale limit notice');
|
||||
await evaluate("document.getElementById('assessment-tools-search').value='inspect';document.getElementById('assessment-tools-search').dispatchEvent(new Event('input'))");
|
||||
await click('[data-tool-selection=visible]');
|
||||
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');
|
||||
@@ -187,7 +205,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', 'DAG parallel branches and joins', 'DAG click/keyboard selection and zoom', 'DAG polling preserves viewport, selection and dragged nodes', 'DAG replanning, empty state and library fallback', 'desktop/dark/mobile DAG layout', '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));
|
||||
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', 'DAG parallel branches and joins', 'DAG click/keyboard selection and zoom', 'DAG polling preserves viewport, selection and dragged nodes', 'DAG replanning, empty state and library fallback', 'desktop/dark/mobile DAG layout', 'candidate publishing controls', 'XSS escaping', 'create', 'start', 'approval', 'completion', 'mobile overflow', 'centered create modal and visible footer', 'tool search and bulk selection with 105 tools, selection preservation and 100-tool cap', 'desktop/dark/mobile create layout'] }, null, 2));
|
||||
} finally {
|
||||
if (socket) socket.close(); chrome.kill(); server.close();
|
||||
}
|
||||
@@ -516,6 +516,7 @@ html[data-theme=dark] #assessment-graph {
|
||||
.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-tool-toolbar button[hidden],#assessment-tools-selection-note:empty { display: none; }
|
||||
.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); }
|
||||
|
||||
@@ -5147,6 +5147,9 @@
|
||||
"busy": "Preparing download…"
|
||||
},
|
||||
"assessments": {
|
||||
"selectAllTools": "Select all",
|
||||
"bulkToolsHint": "Select up to 100 tools per task. Select all keeps existing selections and adds tools in list order up to the limit.",
|
||||
"bulkToolsLimited": "100 tools selected; some tools remain unselected. Deselect tools to make room for others.",
|
||||
"dag": "Execution DAG",
|
||||
"dagHint": "Arrows show dependencies. Steps in one column may run in parallel, subject to concurrency limits and prerequisite states.",
|
||||
"dagDetails": "Node details",
|
||||
|
||||
@@ -5160,6 +5160,9 @@
|
||||
"busy": "Подготовка файла…"
|
||||
},
|
||||
"assessments": {
|
||||
"selectAllTools": "Выбрать все",
|
||||
"bulkToolsHint": "Не более 100 инструментов на задачу. «Выбрать все» сохраняет выбранное и добавляет инструменты по порядку до лимита.",
|
||||
"bulkToolsLimited": "Выбрано 100 инструментов; часть осталась невыбранной. Снимите выбор с некоторых, чтобы добавить другие.",
|
||||
"dag": "DAG выполнения",
|
||||
"dagHint": "Стрелки показывают зависимости. Шаги в одном столбце могут выполняться параллельно с учётом лимита и состояния предшественников.",
|
||||
"dagDetails": "Сведения об узле",
|
||||
|
||||
@@ -5135,6 +5135,9 @@
|
||||
"busy": "正在准备下载…"
|
||||
},
|
||||
"assessments": {
|
||||
"selectAllTools": "全选",
|
||||
"bulkToolsHint": "单次最多选择 100 个工具;全选会保留已选项,并按列表顺序补选至上限。",
|
||||
"bulkToolsLimited": "已选满 100 个工具,仍有部分工具未选中。可取消部分选择后再调整。",
|
||||
"dag": "执行 DAG",
|
||||
"dagHint": "箭头表示步骤依赖;同列步骤可能并行,实际执行受并发数量和前置状态约束。",
|
||||
"dagDetails": "节点详情",
|
||||
|
||||
@@ -306,8 +306,8 @@
|
||||
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>' +
|
||||
'<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="all">' + esc(tr('selectAllTools')) + '</button><button type="button" class="btn-secondary btn-small" data-tool-selection="visible" hidden>' + 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(options.tools.length > 100 ? 'bulkToolsHint' : 'selectionHint')) + '</p><p id="assessment-tools-selection-note" class="assessment-inline-hint" role="status"></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>' +
|
||||
@@ -324,7 +324,11 @@
|
||||
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('[data-tool-selection=all]').disabled = count >= 100 || boxes.every(b => b.checked);
|
||||
const selectVisible = dialog.querySelector('[data-tool-selection=visible]');
|
||||
selectVisible.hidden = !dialog.querySelector('#assessment-tools-search').value.trim();
|
||||
selectVisible.disabled = count >= 100 || visible.every(b => b.checked);
|
||||
dialog.querySelector('[data-tool-selection=clear]').disabled = !count;
|
||||
dialog.querySelector('#assessment-tools-empty').hidden = visible.length > 0;
|
||||
};
|
||||
dialog.querySelector('#assessment-tools-search').addEventListener('input', ev => {
|
||||
@@ -334,11 +338,19 @@
|
||||
});
|
||||
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'); }
|
||||
const note = dialog.querySelector('#assessment-tools-selection-note'); note.textContent = '';
|
||||
if (checkboxes().filter(b => b.checked).length > 100) { ev.target.checked = false; note.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; });
|
||||
const boxes = checkboxes(), note = dialog.querySelector('#assessment-tools-selection-note'); note.textContent = '';
|
||||
if (btn.dataset.toolSelection === 'clear') boxes.forEach(b => { b.checked = false; });
|
||||
else {
|
||||
let remaining = Math.max(0, 100 - boxes.filter(b => b.checked).length);
|
||||
const candidates = boxes.filter(b => !b.checked && (btn.dataset.toolSelection === 'all' || !b.closest('label').hidden));
|
||||
candidates.forEach(b => { if (remaining > 0) { b.checked = true; remaining--; } });
|
||||
if (candidates.some(b => !b.checked)) note.textContent = tr('bulkToolsLimited');
|
||||
}
|
||||
updateSelection();
|
||||
}));
|
||||
dialog.querySelector('form').addEventListener('submit', async ev => {
|
||||
|
||||
Reference in new issue
Block a user