diff --git a/scripts/assessment-browser-smoke.mjs b/scripts/assessment-browser-smoke.mjs index 7c0d5d24..2f9b0ccc 100644 --- a/scripts/assessment-browser-smoke.mjs +++ b/scripts/assessment-browser-smoke.mjs @@ -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(); } diff --git a/web/static/css/assessments.css b/web/static/css/assessments.css index efeb75e1..833b8606 100644 --- a/web/static/css/assessments.css +++ b/web/static/css/assessments.css @@ -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); } diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index b61c8344..42af52f2 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -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…" } } diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 087a66a0..9c09c3ec 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -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": "Загрузка…" } } diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index e0490fab..85792d8a 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -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": "加载配置…" } } diff --git a/web/static/js/assessments-auth.test.cjs b/web/static/js/assessments-auth.test.cjs new file mode 100644 index 00000000..f7494d49 --- /dev/null +++ b/web/static/js/assessments-auth.test.cjs @@ -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); +}); diff --git a/web/static/js/assessments.js b/web/static/js/assessments.js index 92c4ddce..b4b56a23 100644 --- a/web/static/js/assessments.js +++ b/web/static/js/assessments.js @@ -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) => ''; - dialog.innerHTML = '
'; - 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 = ''; + const field = (name, type, value, extra) => ''; + const textarea = (name, rows, mandatory, placeholder) => ''; + const modelOptions = (inherit) => (inherit ? '' : '') + options.models.map(m => '').join(''); + const closeIcon = ''; + dialog.innerHTML = ''; + 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; }