From 55647e121394b444aa460d3cae43994fe9501ee1 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:24:47 +0800 Subject: [PATCH] fix(tasks): guard controls against stale responses and duplicate submissions --- .github/workflows/task-ui.yml | 24 ++++ scripts/helpers/task-ui-fixture.cjs | 103 +++++++++++++++ scripts/long-tasks-browser.test.cjs | 2 +- scripts/task-controls-browser.test.cjs | 169 +++++++++++++++++++++++++ web/static/i18n/en-US.json | 9 +- web/static/i18n/ru-RU.json | 9 +- web/static/i18n/zh-CN.json | 9 +- web/static/js/form-validation.test.cjs | 4 +- web/static/js/long-tasks.js | 111 +++++++++++----- web/static/js/tasks.js | 107 +++++++++++----- web/templates/index.html | 10 +- 11 files changed, 478 insertions(+), 79 deletions(-) create mode 100644 .github/workflows/task-ui.yml create mode 100644 scripts/helpers/task-ui-fixture.cjs create mode 100644 scripts/task-controls-browser.test.cjs diff --git a/.github/workflows/task-ui.yml b/.github/workflows/task-ui.yml new file mode 100644 index 00000000..9f2501a5 --- /dev/null +++ b/.github/workflows/task-ui.yml @@ -0,0 +1,24 @@ +name: Task management UI +on: + push: + paths: ['web/templates/index.html', 'web/static/js/tasks.js', 'web/static/js/long-tasks.js', 'web/static/js/router.js', 'web/static/js/auth.js', 'web/static/js/modal.js', 'web/static/js/rbac-guards.js', 'web/static/css/**', 'web/static/i18n/**', 'scripts/long-tasks-browser.test.cjs', 'scripts/task-controls-browser.test.cjs', 'scripts/helpers/task-ui-fixture.cjs', '.github/workflows/task-ui.yml'] + pull_request: + paths: ['web/templates/index.html', 'web/static/js/tasks.js', 'web/static/js/long-tasks.js', 'web/static/js/router.js', 'web/static/js/auth.js', 'web/static/js/modal.js', 'web/static/js/rbac-guards.js', 'web/static/css/**', 'web/static/i18n/**', 'scripts/long-tasks-browser.test.cjs', 'scripts/task-controls-browser.test.cjs', 'scripts/helpers/task-ui-fixture.cjs', '.github/workflows/task-ui.yml'] +permissions: + contents: read +jobs: + browser: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Install isolated browser test dependencies + run: | + npm install --prefix "$RUNNER_TEMP/task-ui-deps" --no-save --ignore-scripts --package-lock=false playwright@1.65.0 + "$RUNNER_TEMP/task-ui-deps/node_modules/.bin/playwright" install --with-deps chromium + - name: Test real task page entrypoints and controls + run: | + NODE_PATH="$RUNNER_TEMP/task-ui-deps/node_modules" node --test scripts/long-tasks-browser.test.cjs scripts/task-controls-browser.test.cjs diff --git a/scripts/helpers/task-ui-fixture.cjs b/scripts/helpers/task-ui-fixture.cjs new file mode 100644 index 00000000..ff2c9ebd --- /dev/null +++ b/scripts/helpers/task-ui-fixture.cjs @@ -0,0 +1,103 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const http = require('node:http'); +const { chromium } = require('playwright'); +const root = path.join(__dirname, '../..'); +const read = file => fs.readFileSync(path.join(root, file), 'utf8'); +const template = read('web/templates/index.html'); +function div(id) { + const start = template.indexOf(`
]*>/g; tags.lastIndex = start; + let depth = 0, match; + while ((match = tags.exec(template))) { depth += match[0].startsWith(']*\bsrc=["']([^"']+)["'][^>]*><\/script>/g)].filter(m => /^\/static\/js\/(router|auth|modal|tasks|long-tasks|rbac-guards)\.js(?:\?|$)/.test(m[1])).map(m => m[0]).join(''); + const styles = [...template.matchAll(/]*\bhref=["']([^"']+)["'][^>]*>/g)].filter(m => /^\/static\/css\/(style|mobile|long-tasks)\.css(?:\?|$)/.test(m[1])).map(m => m[0]).join(''); + const locale = JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<', '\\u003c'); + const html = `${styles}
${div('page-tasks')}
${div('batch-import-modal')}${div('batch-queue-detail-modal')}${div('add-batch-task-modal')}${scripts}`; + const server = http.createServer(async (req, res) => { + const url = new URL(req.url, 'http://fixture'); + const send = (status, value) => { res.statusCode = status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(value)); }; + try { + if (url.pathname.startsWith('/static/')) { const file = path.join(root, 'web', url.pathname); res.setHeader('Content-Type', file.endsWith('.css') ? 'text/css; charset=utf-8' : 'text/javascript; charset=utf-8'); return res.end(fs.readFileSync(file)); } + if (url.pathname === '/') { res.setHeader('Content-Type', 'text/html; charset=utf-8'); return res.end(html); } + if (url.pathname === '/favicon.ico') { res.statusCode = 204; return res.end(); } + let raw = ''; for await (const c of req) raw += c; + const body = raw ? JSON.parse(raw) : null; + const request = { method: req.method, path: url.pathname, query: Object.fromEntries(url.searchParams), body, authorization: req.headers.authorization }; state.requests.push(request); + if (req.headers.authorization !== 'Bearer fixture-token') return send(401, { error: 'fixture requires authentication' }); + if (state.hook) { const intercepted = await state.hook(request); if (intercepted) return send(intercepted.status || 200, intercepted.body); } + if (url.pathname === '/api/projects') return send(200, { projects: [] }); + if (url.pathname === '/api/long-tasks/options') return send(200, { projects: [], roles: [], models: [] }); + if (url.pathname === '/api/long-tasks') { + if (req.method === 'POST') { const task = { ...goal('new-' + state.tasks.size), ...body }; state.tasks.set(task.id, task); return send(201, { task }); } + const tasks = [...state.tasks.values()].filter(task => (!url.searchParams.get('status') || task.status === url.searchParams.get('status')) && (!url.searchParams.get('q') || task.name.includes(url.searchParams.get('q')))); + const offset = Number(url.searchParams.get('offset') || 0), limit = Number(url.searchParams.get('limit') || 30); + return send(200, { tasks: tasks.slice(offset, offset + limit), has_more: tasks.length > offset + limit }); + } + const match = url.pathname.match(/^\/api\/long-tasks\/([^/]+)(?:\/(.*))?$/); + if (match) { + const task = state.tasks.get(decodeURIComponent(match[1])); if (!task) return send(404, { error: 'task missing' }); + const suffix = match[2] || ''; + if (suffix === 'report') { res.setHeader('Content-Type', 'text/markdown'); return res.end('# ' + task.id); } + if (suffix === 'events') return send(200, { events: [] }); + if (req.method === 'DELETE') { state.tasks.delete(task.id); return send(200, { deleted: true }); } + if (suffix.startsWith('control/')) { + if (body.revision !== task.revision) return send(409, { error: 'revision conflict' }); + const action = suffix.slice(8); + if (['completed', 'cancelled'].includes(task.status)) return send(409, { error: 'terminal task' }); + if (action === 'start') task.status = 'running'; + else if (action === 'pause') task.status = 'paused'; + else if (action === 'cancel') task.status = 'cancelled'; + else if (action === 'retry') { const step = task.steps.find(s => s.id === body.step_id); if (!step) return send(400, { error: 'missing step' }); step.status = 'pending'; task.status = 'paused'; } + else if (action === 'budget') { task.max_rounds = body.max_rounds; task.remaining_seconds = body.remaining_seconds; task.status = 'paused'; } + else if (action === 'guidance' || action === 'answer') { task.guidance.push(body.message); if (action === 'answer') { task.question = ''; task.status = state.failResume ? 'paused' : 'running'; } } + else return send(400, { error: 'unknown action' }); + task.revision++; return send(200, { task, ...(action === 'answer' && state.failResume ? { start_error: state.failResume } : {}) }); + } + return send(200, { task }); + } + if (url.pathname === '/api/batch-tasks') { + if (req.method === 'POST') { const q = { ...queue('new-queue'), ...body, tasks: body.tasks.map((message, i) => ({ id: 'new-' + i, message, status: 'pending' })) }; state.queues.set(q.id, q); return send(200, { queueId: q.id }); } + const queues = [...state.queues.values()]; return send(200, { queues, total: queues.length, total_pages: 2 }); + } + const batch = url.pathname.match(/^\/api\/batch-tasks\/([^/]+)(?:\/(.*))?$/); + if (batch) { + const q = state.queues.get(batch[1]); if (!q) return send(404, { error: 'queue missing' }); const suffix = batch[2] || ''; + if (suffix === 'start' || suffix === 'rerun') q.status = 'running'; + else if (suffix === 'pause') q.status = 'paused'; + else if (suffix === 'metadata' || suffix === 'schedule' || suffix === 'schedule-enabled') Object.assign(q, body); + else if (suffix === 'tasks' && req.method === 'POST') q.tasks.push({ id: 'added', message: body.message, status: 'pending' }); + else if (suffix.startsWith('tasks/')) { const parts = suffix.split('/'), item = q.tasks.find(t => t.id === parts[1]); if (!item) return send(404, { error: 'step missing' }); if (parts[2] === 'run') { item.status = 'completed'; q.status = 'paused'; } else if (req.method === 'DELETE') q.tasks = q.tasks.filter(t => t !== item); else Object.assign(item, body); } + else if (req.method === 'DELETE') state.queues.delete(q.id); + return send(200, { queue: q }); + } + return send(404, { error: 'unhandled fixture route' }); + } catch (error) { send(500, { error: error.message }); } + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const executablePath = process.env.CHROME_PATH || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : undefined); + const browser = await chromium.launch(executablePath ? { executablePath } : {}); + t.after(async () => { await browser.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }); + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true }); page.setDefaultTimeout(5000); + page.on('pageerror', error => state.pageErrors.push(error.message)); + page.on('dialog', dialog => (dialog.type() === 'confirm' && !state.confirm) ? dialog.dismiss() : dialog.accept()); + await page.goto(`http://127.0.0.1:${server.address().port}/#tasks`); + await page.locator('[data-lt-action=select][data-id=a]').waitFor(); + await page.locator('#tasks-auto-refresh').uncheck(); + const select = async id => { await page.locator(`[data-lt-action=select][data-id="${id}"]`).click(); await page.waitForFunction(id => document.getElementById('lt-name').textContent === '目标 ' + id, id); }; + const refresh = () => page.evaluate(() => refreshTaskWorkspace()); + return { page, state, select, refresh }; +} +module.exports = { fixture, goal }; diff --git a/scripts/long-tasks-browser.test.cjs b/scripts/long-tasks-browser.test.cjs index a4d148bb..38c3ef16 100644 --- a/scripts/long-tasks-browser.test.cjs +++ b/scripts/long-tasks-browser.test.cjs @@ -28,7 +28,7 @@ test('goal task page: authenticated controls, stable polling, XSS, report and re if (req.url.startsWith('/static/')) { const file = path.join(root, 'web', new URL(req.url, 'http://fixture').pathname); res.setHeader('Content-Type', file.endsWith('.css') ? 'text/css; charset=utf-8' : 'text/javascript; charset=utf-8'); return res.end(fs.readFileSync(file)); } if (req.url === '/') { res.setHeader('Content-Type', 'text/html; charset=utf-8'); - const html = `${styleTags}
${pageHTML}
${scriptTags}`; return res.end(html); + const html = `${styleTags}
${pageHTML}
${scriptTags}`; return res.end(html); } if (req.url === '/api/auth/validate') { res.setHeader('Content-Type','application/json'); return res.end('{}'); } if (req.url === '/favicon.ico') { res.statusCode=204; return res.end(); } diff --git a/scripts/task-controls-browser.test.cjs b/scripts/task-controls-browser.test.cjs new file mode 100644 index 00000000..b82164d3 --- /dev/null +++ b/scripts/task-controls-browser.test.cjs @@ -0,0 +1,169 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { fixture, goal } = require('./helpers/task-ui-fixture.cjs'); + +// Each test uses a disposable HTTP fixture, real template/script references and +// the real router/auth/modal code. It never calls a running CSAI deployment. +test('goal task actions: retry, budget, resume, pause, answer, report, cancel and delete', async t => { + const { page, state, select, refresh } = await fixture(t); + await select('a'); + await page.locator('[data-lt-action=retry]').click(); + await page.locator('.lt-step .lt-status-pending').waitFor(); + assert.equal(state.tasks.get('a').steps[0].status, 'pending'); + await page.locator('[data-lt-action=budget]').click(); + await page.locator('#lt-modal [name=max_rounds]').fill('60'); await page.locator('#lt-modal [name=minutes]').fill('90'); + await page.locator('#lt-modal [type=submit]').click(); await page.waitForFunction(() => !document.getElementById('lt-modal')); + assert.equal(state.tasks.get('a').remaining_seconds, 5400); + await page.locator('[data-lt-action=start]').click(); await page.locator('#lt-state .lt-status-running').waitFor(); + await page.locator('[data-lt-action=pause]').click(); await page.locator('#lt-state .lt-status-paused').waitFor(); + state.tasks.get('a').status = 'waiting_input'; state.tasks.get('a').question = 'Which fixture?'; await refresh(); + await page.locator('#lt-guidance-input').fill('Use local fixture A'); await page.locator('#lt-guidance-send').click(); await page.locator('#lt-state .lt-status-running').waitFor(); + assert.deepEqual(state.tasks.get('a').guidance, ['Use local fixture A']); + const downloaded = page.waitForEvent('download'); await page.locator('[data-lt-action=report]').click(); assert.equal((await downloaded).suggestedFilename(), 'task-a.md'); + state.confirm = false; await page.locator('[data-lt-action=cancel]').click(); assert.equal(state.tasks.get('a').status, 'running'); + state.confirm = true; await page.locator('[data-lt-action=cancel]').click(); await page.locator('#lt-state .lt-status-cancelled').waitFor(); + await page.locator('[data-lt-action=delete]').click(); await page.locator('#lt-empty-detail').waitFor(); assert.equal(state.tasks.has('a'), false); + assert.deepEqual(state.pageErrors, []); +}); + +test('search responds while typing and expanded step instructions survive refresh', async t => { + const { page, state, select, refresh } = await fixture(t); + await select('a'); await page.locator('.lt-step details summary').click(); await refresh(); + assert.equal(await page.locator('.lt-step details').evaluate(e => e.open), true); + await page.locator('#lt-search').fill('目标 b'); + await page.waitForFunction(() => document.querySelectorAll('.lt-card').length === 1 && document.querySelector('.lt-card').dataset.id === 'b'); + assert.ok(state.requests.some(r => r.query.q === '目标 b')); +}); + +test('cancelled tasks never offer a retry that the API rejects', async t => { + const { page, state, select, refresh } = await fixture(t); + await select('a'); state.tasks.get('a').status = 'cancelled'; await refresh(); + assert.equal(await page.locator('[data-lt-action=retry]').count(), 0); +}); + +test('a late creation-options response does not open a modal after leaving the page', async t => { + const { page, state } = await fixture(t); let release; + const gate = new Promise(resolve => { release = resolve; }); + state.hook = async req => { if (req.path.endsWith('/options')) await gate; }; + await page.locator('#task-new-goal').click(); await page.waitForTimeout(50); + await page.evaluate(() => switchPage('dashboard')); release(); await page.waitForTimeout(150); + assert.equal(await page.locator('#lt-modal').count(), 0); +}); + +test('deleting A while selecting B preserves B and report filenames stay attached to their task', async t => { + const { page, state, select } = await fixture(t); let release; + await select('a'); const gate = new Promise(resolve => { release = resolve; }); + state.hook = async req => { if (req.path === '/api/long-tasks/a' && req.method === 'DELETE') await gate; }; + await page.locator('[data-lt-action=delete]').click(); await select('b'); release(); await page.waitForTimeout(150); + assert.equal(await page.locator('#lt-detail').isVisible(), true); + assert.equal(await page.locator('#lt-name').textContent(), '目标 b'); + state.tasks.set('a', goal('a')); await page.evaluate(() => refreshTaskWorkspace()); await select('a'); + const reportGate = new Promise(resolve => { release = resolve; }); state.hook = async req => { if (req.path.endsWith('/a/report')) await reportGate; }; + const downloaded = page.waitForEvent('download'); await page.locator('[data-lt-action=report]').click(); await select('b'); release(); + assert.equal((await downloaded).suggestedFilename(), 'task-a.md'); +}); + +test('goal paging, filters, refresh toggle, modal close and execution links work', async t => { + const { page, state, select, refresh } = await fixture(t); + for (let i = 0; i < 34; i++) state.tasks.set('extra-' + i, goal('extra-' + i)); + await refresh(); await page.locator('#lt-next').click(); await page.waitForFunction(() => document.getElementById('lt-page').textContent === '2'); + await page.locator('#lt-prev').click(); await page.waitForFunction(() => document.getElementById('lt-page').textContent === '1'); + await page.locator('#lt-filter').selectOption('paused'); await page.waitForFunction(() => document.querySelectorAll('.lt-card').length === 1); + await page.locator('#lt-filter').selectOption(''); await page.waitForFunction(() => document.querySelectorAll('.lt-card').length === 30); + await page.locator('#task-new-goal').click(); await page.locator('#lt-modal').waitFor(); await page.locator('#lt-modal [data-close]').last().click(); await page.waitForFunction(() => !document.getElementById('lt-modal')); + await page.locator('#task-new-goal').click(); await page.locator('#lt-modal').waitFor(); await page.keyboard.press('Escape'); await page.waitForFunction(() => !document.getElementById('lt-modal')); + assert.equal(state.requests.filter(r => r.method === 'POST').length, 0); + await page.locator('#tasks-auto-refresh').check(); const count = state.requests.filter(r => r.path === '/api/long-tasks').length; + await page.waitForTimeout(4200); assert.ok(state.requests.filter(r => r.path === '/api/long-tasks').length > count); + await page.locator('#tasks-auto-refresh').uncheck(); await refresh(); const stopped = state.requests.length; + await page.waitForTimeout(4200); assert.equal(state.requests.length, stopped); + await select('a'); await page.locator('.lt-step a').click(); await page.waitForFunction(() => window.visitedConversation === 'conversation-a'); + assert.deepEqual(state.pageErrors, []); +}); + +test('slow submissions are single-flight and saved answers are not resubmitted on resume failure', async t => { + const { page, state, select, refresh } = await fixture(t); await select('a'); + state.hook = async req => { if (req.path.endsWith('/control/start')) await new Promise(resolve => setTimeout(resolve, 300)); }; + await page.locator('[data-lt-action=start]').dblclick(); await page.locator('#lt-state .lt-status-running').waitFor(); + assert.equal(state.requests.filter(r => r.path.endsWith('/control/start')).length, 1); + state.hook = null; state.tasks.get('a').status = 'waiting_input'; state.tasks.get('a').question = 'Choose a fixture'; state.failResume = 'All execution slots are busy'; await refresh(); + await page.locator('#lt-guidance-input').fill('Fixture A'); await page.locator('#lt-guidance-send').click(); + await page.waitForFunction(() => document.getElementById('lt-error').textContent.includes('All execution slots')); + assert.equal(await page.locator('#lt-guidance-input').inputValue(), ''); + await refresh(); assert.match(await page.locator('#lt-error').textContent(), /答复已保存/); + assert.deepEqual(state.tasks.get('a').guidance, ['Fixture A']); +}); + +test('creation failures keep form input, and budget/execution permissions match available actions', async t => { + const { page, state, select, refresh } = await fixture(t); + state.hook = req => req.path === '/api/long-tasks' && req.method === 'POST' ? { status: 503, body: { error: 'fixture unavailable' } } : null; + await page.locator('#task-new-goal').click(); await page.locator('#lt-modal [name=name]').fill('Keep this draft'); + await page.locator('#lt-modal [name=objective]').fill('Local report'); await page.locator('#lt-modal [name=scope]').fill('Local only'); await page.locator('#lt-modal [name=criteria]').fill('Evidence'); + await page.locator('#lt-modal [type=submit]').click(); await page.waitForFunction(() => document.querySelector('.lt-form-error').textContent.includes('fixture unavailable')); + assert.equal(await page.locator('#lt-modal [name=name]').inputValue(), 'Keep this draft'); + assert.equal(await page.locator('#lt-modal [type=submit]').isEnabled(), true); + await page.locator('#lt-modal [data-close]').last().click(); state.hook = null; await select('a'); + state.tasks.get('a').status = 'budget_exhausted'; state.tasks.get('a').remaining_seconds = 0; await refresh(); + assert.equal(await page.locator('[data-lt-action=start]').isDisabled(), true); assert.equal(await page.locator('[data-lt-action=budget]').isEnabled(), true); + state.tasks.get('a').rounds = 200; state.tasks.get('a').max_rounds = 200; await refresh(); assert.equal(await page.locator('[data-lt-action=budget]').isDisabled(), true); + await page.evaluate(() => { saveAuth('fixture-token',new Date(Date.now()+3600000),{permissions:['tasks:read','tasks:write'],scope:'own'}); applyRBACToUI(); }); await refresh(); + assert.equal(await page.locator('[data-lt-action=start]').count(), 0); +}); + +test('batch queue controls: create, close, metadata, add/edit/delete steps, single run, start/pause/resume/rerun/delete', async t => { + const { page, state } = await fixture(t); + await page.locator('[data-task-tab=batch]').click(); await page.locator('#task-new-batch').click(); + await page.locator('#batch-import-modal').waitFor({ state: 'visible' }); + await page.locator('#batch-queue-title').fill('New batch'); await page.locator('#batch-tasks-input').fill('Read local A\nRead local B'); + await page.locator('[onclick="createBatchQueue()"]').click(); + await page.locator('[data-bq-detail-for="new-queue"]').waitFor(); + assert.equal(state.queues.get('new-queue').executeNow, false); + await page.locator('#batch-queue-detail-modal .modal-close').click(); + await page.locator('.batch-queue-item[data-queue-id=q1]').click(); await page.locator('[data-bq-detail-for=q1]').waitFor(); + await page.locator('#bq-title-val .bq-inline-editable').click(); await page.locator('#bq-edit-title').fill('Renamed queue'); await page.locator('#bq-edit-title').press('Enter'); + await page.waitForFunction(() => document.getElementById('bq-title-val').textContent === 'Renamed queue'); assert.equal(state.queues.get('q1').title, 'Renamed queue'); + await page.locator('#bq-concurrency-val .bq-inline-editable').click(); await page.locator('#bq-edit-concurrency').fill('2'); await page.locator('#bq-edit-concurrency').press('Enter'); + await page.waitForFunction(() => !document.getElementById('bq-edit-concurrency')); assert.equal(state.queues.get('q1').concurrency, 2); + await page.locator('#batch-queue-add-task-btn').click(); await page.locator('#add-task-message').fill('Added fixture step'); await page.locator('[onclick="saveAddBatchTask()"]').click(); + await page.locator('.batch-task-item[data-task-id=added]').waitFor(); + await page.locator('.batch-task-item[data-task-id=added] .batch-task-edit-btn').click(); await page.locator('#bq-task-edit-added').fill('Edited fixture step'); await page.locator('#bq-task-edit-added').press('Tab'); + await page.waitForFunction(() => document.querySelector('[data-task-id=added] .batch-task-message').textContent === 'Edited fixture step'); + await page.locator('.batch-task-item[data-task-id=added] .batch-task-delete-btn').click(); await page.locator('.batch-task-item[data-task-id=added]').waitFor({ state: 'detached' }); + await page.locator('.batch-task-item[data-task-id=b1] .batch-task-run-btn').click(); await page.waitForFunction(() => document.querySelector('[data-task-id=b1] .batch-task-status').textContent === '已完成'); + await page.locator('#batch-queue-start-btn').click(); await page.locator('#batch-queue-pause-btn').waitFor({ state: 'visible' }); assert.equal(state.queues.get('q1').status, 'running'); + await page.locator('#batch-queue-pause-btn').click(); await page.locator('#batch-queue-start-btn').waitFor({ state: 'visible' }); assert.equal(state.queues.get('q1').status, 'paused'); + await page.locator('#batch-queue-start-btn').click(); await page.locator('#batch-queue-pause-btn').waitFor({ state: 'visible' }); + state.queues.get('q1').status = 'completed'; await page.evaluate(() => showBatchQueueDetail('q1')); await page.locator('#batch-queue-rerun-btn').click(); await page.locator('#batch-queue-pause-btn').waitFor({ state: 'visible' }); + await page.locator('#batch-queue-pause-btn').click(); await page.locator('#batch-queue-delete-btn').waitFor({ state: 'visible' }); await page.locator('#batch-queue-delete-btn').click(); + await page.locator('#batch-queue-detail-modal').waitFor({ state: 'hidden' }); assert.equal(state.queues.has('q1'), false); + await page.locator('.batch-queue-item[data-queue-id=new-queue] .batch-queue-icon-btn--danger').click(); await page.locator('.batch-queue-item[data-queue-id=new-queue]').waitFor({ state: 'detached' }); + assert.deepEqual(state.pageErrors, []); +}); + +test('batch create and add-step clicks cannot submit twice on a slow connection', async t => { + const { page, state } = await fixture(t); + state.hook = async req => { if (req.method === 'POST' && (req.path === '/api/batch-tasks' || req.path.endsWith('/tasks'))) await new Promise(resolve => setTimeout(resolve, 300)); }; + await page.locator('[data-task-tab=batch]').click(); await page.locator('#task-new-batch').click(); + await page.locator('#batch-tasks-input').fill('One local task'); await page.locator('[onclick="createBatchQueue()"]').dblclick(); + await page.locator('[data-bq-detail-for="new-queue"]').waitFor(); + assert.equal(state.requests.filter(r => r.method === 'POST' && r.path === '/api/batch-tasks').length, 1); + await page.locator('#batch-queue-add-task-btn').click(); await page.locator('#add-task-message').fill('One new step'); + await page.locator('[onclick="saveAddBatchTask()"]').dblclick(); await page.locator('[data-task-id=added]').waitFor(); + assert.equal(state.requests.filter(r => r.method === 'POST' && r.path.endsWith('/new-queue/tasks')).length, 1); +}); + +test('late batch detail and creation lookups do not take over a newer selection or page', async t => { + const { page, state } = await fixture(t); + state.queues.set('q2', { ...state.queues.get('q1'), id: 'q2', title: 'Other queue' }); + await page.locator('[data-task-tab=batch]').click(); await page.evaluate(() => refreshBatchQueues()); + let release; const gate = new Promise(resolve => { release = resolve; }); + state.hook = async req => { if (req.path === '/api/batch-tasks/q1' && req.method === 'GET') await gate; }; + await page.locator('.batch-queue-item[data-queue-id=q1]').click(); await page.locator('#batch-queue-detail-modal .modal-close').click(); + await page.locator('.batch-queue-item[data-queue-id=q2]').click(); await page.locator('[data-bq-detail-for=q2]').waitFor(); + release(); await page.waitForTimeout(150); assert.equal(await page.locator('[data-bq-detail-for=q2]').count(), 1); + await page.locator('#batch-queue-detail-modal .modal-close').click(); + const createGate = new Promise(resolve => { release = resolve; }); + state.hook = async req => { if (req.path === '/api/projects') await createGate; }; + await page.locator('#task-new-batch').click(); await page.evaluate(() => switchPage('dashboard')); release(); await page.waitForTimeout(150); + assert.equal(await page.locator('#batch-import-modal').isVisible(), false); +}); diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index a9960ee0..66b1b155 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -5286,7 +5286,7 @@ "instruction": "Step instructions", "noResult": "No result yet", "trace": "View execution", - "retry": "Retry step", + "retry": "Prepare retry", "attempts": "{{count}} attempt(s)", "noPlan": "Start the task to generate its plan.", "noEvents": "No activity yet", @@ -5295,7 +5295,7 @@ "progress": "{{done}} / {{total}} planned steps done · Planning {{rounds}} / {{max}} rounds · About {{minutes}} budget minutes left", "deleteConfirm": "Delete this task and its activity? Execution conversations will be retained.", "cancelConfirm": "Cancel the whole goal task? Saved results will be retained.", - "retryConfirm": "Retry creates a new execution attempt. Check whether the previous attempt already took effect before repeating it.", + "retryConfirm": "Queue this step for retry, then click Resume. First check previous effects and confirm its execution has stopped.", "close": "Close", "save": "Save", "name": "Task name", @@ -5326,6 +5326,9 @@ "waiting_input": "Awaiting input", "budget_exhausted": "Budget exhausted", "cleanup_unconfirmed": "Cleanup unconfirmed" - } + }, + "answerSaved": "Answer saved; the task has not started:", + "extendFirst": "Adjust the execution budget before resuming.", + "roundLimit": "The 200-round limit has been reached. Export the results and create a new goal task." } } diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 753cf80c..79262a6b 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -5299,7 +5299,7 @@ "instruction": "Инструкции шага", "noResult": "Результатов пока нет", "trace": "Открыть выполнение", - "retry": "Повторить шаг", + "retry": "Подготовить повтор", "attempts": "Попыток: {{count}}", "noPlan": "Запустите задачу, чтобы составить план.", "noEvents": "Событий пока нет", @@ -5308,7 +5308,7 @@ "progress": "Выполнено {{done}} / {{total}} шагов · Планирование {{rounds}} / {{max}} · Осталось около {{minutes}} мин.", "deleteConfirm": "Удалить задачу и события? Диалоги выполнения сохранятся.", "cancelConfirm": "Отменить всю задачу? Сохранённые результаты останутся.", - "retryConfirm": "Повтор создаст новую попытку. Сначала проверьте, не выполнилась ли предыдущая операция.", + "retryConfirm": "Поставить шаг в очередь повтора, затем нажмите «Продолжить». Сначала проверьте результаты прошлой попытки и остановку выполнения.", "close": "Закрыть", "save": "Сохранить", "name": "Название задачи", @@ -5339,6 +5339,9 @@ "waiting_input": "Ожидает ответа", "budget_exhausted": "Бюджет исчерпан", "cleanup_unconfirmed": "Остановка не подтверждена" - } + }, + "answerSaved": "Ответ сохранён; задача не запущена:", + "extendFirst": "Измените бюджет перед продолжением.", + "roundLimit": "Достигнут предел в 200 раундов. Экспортируйте результаты и создайте новую задачу." } } diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 3df07a73..eff7e738 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -5274,7 +5274,7 @@ "instruction": "查看步骤要求", "noResult": "尚无结果", "trace": "查看执行会话", - "retry": "重试此步骤", + "retry": "准备重试", "attempts": "已执行 {{count}} 次", "noPlan": "启动后根据目标生成计划。", "noEvents": "暂无动态", @@ -5283,7 +5283,7 @@ "progress": "已完成 {{done}} / 当前计划 {{total}} 步 · 规划 {{rounds}} / {{max}} 轮 · 剩余预算约 {{minutes}} 分钟", "deleteConfirm": "删除此任务及动态?关联执行会话仍保留。", "cancelConfirm": "取消整个目标任务?已保存的结果会保留。", - "retryConfirm": "重试会开启新的执行尝试。请先检查上次执行是否已产生效果,避免重复操作。", + "retryConfirm": "将此步骤重新置为待执行,随后点击“继续任务”执行。请先检查上次是否已产生效果、执行资源是否已停止。", "close": "关闭", "save": "保存", "name": "任务名称", @@ -5314,6 +5314,9 @@ "waiting_input": "待答复", "budget_exhausted": "预算耗尽", "cleanup_unconfirmed": "停止状态待确认" - } + }, + "answerSaved": "答复已保存,任务暂未启动:", + "extendFirst": "请先调整执行预算,再继续任务。", + "roundLimit": "已达到 200 轮上限,可导出结果后创建新的目标任务。" } } diff --git a/web/static/js/form-validation.test.cjs b/web/static/js/form-validation.test.cjs index 01a1be9a..f0aa967a 100644 --- a/web/static/js/form-validation.test.cjs +++ b/web/static/js/form-validation.test.cjs @@ -9,8 +9,10 @@ function concurrencyHarness(value) { const ctx = {_bqInlineSaving:false, batchQueuesState:{currentQueueId:'q'}, document:{getElementById:() => input}, _t:x => x, alert:x => {message=x;}, apiFetch:async () => {calls++;return {ok:true,json:async () => ({queue:{title:'title'}})};}, - showBatchQueueDetail() {},refreshBatchQueues() {},console}; + showBatchQueueDetail() {},isAppModalOpen:() => true,refreshBatchQueues() {},console}; vm.createContext(ctx); + const refreshStart = taskSource.indexOf('function refreshBatchQueueDetailIfCurrent('); + vm.runInContext(taskSource.slice(refreshStart,taskSource.indexOf('// 开始批量任务队列',refreshStart)),ctx); const start = taskSource.indexOf('async function saveInlineConcurrency('); vm.runInContext(taskSource.slice(start,taskSource.indexOf('// --- 单条执行 ---',start)),ctx); return {ctx,calls:() => calls,message:() => message,focused:() => focused}; diff --git a/web/static/js/long-tasks.js b/web/static/js/long-tasks.js index cf19c1b3..416769fc 100644 --- a/web/static/js/long-tasks.js +++ b/web/static/js/long-tasks.js @@ -1,21 +1,25 @@ /* Durable objectives in the existing task-management page. */ (function () { 'use strict'; - const state = { active: false, tab: 'goals', tasks: [], selected: null, task: null, events: [], cursor: 0, offset: 0, more: false, epoch: 0, loading: false, timer: null, options: null, controller: null }; + const state = { active: false, tab: 'goals', tasks: [], selected: null, task: null, events: [], cursor: 0, offset: 0, more: false, epoch: 0, loading: false, timer: null, options: null, controller: null, optionsRequest: null, viewVersion: 0, searchTimer: null, mutating: new Set(), errorKind: null }; const el = id => document.getElementById(id); const tr = (key, args) => typeof window.t === 'function' ? window.t('longTasks.' + key, args) : key; const esc = value => String(value == null ? '' : value).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const active = task => task && ['running', 'pausing', 'cancelling'].includes(task.status); const badge = status => `${esc(tr('status.' + status))}`; - const button = (action, label, extra = '', disabled = false) => ``; + const mutationActions = new Set(['start', 'pause', 'cancel', 'retry', 'budget', 'delete']); + const button = (action, label, extra = '', disabled = false) => ``; function writable(permission = 'tasks:write') { return typeof window.hasPermission !== 'function' || window.hasPermission(permission); } + function canExecute() { return writable() && ['agent:execute', 'chat:read', 'chat:write'].every(permission => writable(permission)); } + function current(task) { return state.active && state.selected === task.id; } async function api(path, options = {}) { const response = await window.apiFetch('/api/long-tasks' + path, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); if (!response.ok) { const body = await response.json().catch(() => ({})); throw new Error(body.error || String(response.status)); } return response.json(); } - function error(message) { const box = el('lt-error'); if (box) { box.textContent = message || ''; box.hidden = !message; } } + function error(message, kind = 'action') { state.errorKind = message ? kind : null; const box = el('lt-error'); if (box) { box.textContent = message || ''; box.hidden = !message; } } function switchTab(tab) { + state.viewVersion++; cancelOptions(); state.tab = tab; el('long-task-workspace').hidden = tab !== 'goals'; el('task-batch-workspace').hidden = tab !== 'batch'; @@ -33,7 +37,7 @@ function renderTask() { const t = state.task; el('lt-empty-detail').hidden = !!t; el('lt-detail').hidden = !t; - if (!t) return; + if (!t) { el('lt-steps').replaceChildren(); el('lt-steps').dataset.taskId = ''; return; } el('lt-name').textContent = t.name; el('lt-state').innerHTML = badge(t.status); const done = t.steps.filter(s => s.status === 'completed').length; @@ -47,18 +51,25 @@ const terminal = ['completed', 'cancelled'].includes(t.status); const actions = []; if (writable()) { - if (!active(t) && !terminal && !t.question) actions.push(button('start', t.status === 'draft' ? 'start' : 'resume')); + if (canExecute() && !active(t) && !terminal && !t.question) { + const needsBudget = t.rounds >= t.max_rounds || t.remaining_seconds <= 0; + actions.push(button('start', t.status === 'draft' ? 'start' : 'resume', needsBudget ? `title="${esc(tr('extendFirst'))}"` : '', needsBudget)); + } if (t.status === 'running') actions.push(button('pause', 'pause')); if (!terminal) actions.push(button('cancel', 'cancel', '', ['pausing', 'cancelling'].includes(t.status))); - if (!active(t) && !terminal) actions.push(button('budget', 'budget')); + if (!active(t) && !terminal) actions.push(button('budget', 'budget', t.rounds >= 200 ? `title="${esc(tr('roundLimit'))}"` : '', t.rounds >= 200)); } actions.push(button('report', 'report')); if (writable('tasks:delete') && !active(t)) actions.push(button('delete', 'delete')); el('lt-actions').innerHTML = actions.join(''); el('lt-guidance-form').hidden = terminal || !writable(); el('lt-guidance-send').textContent = tr(t.question ? 'answerResume' : 'sendGuidance'); - el('lt-guidance-send').disabled = ['pausing', 'cancelling'].includes(t.status); - el('lt-steps').innerHTML = t.steps.length ? t.steps.map(s => `
${esc(s.id)} · ${esc(s.title)}${badge(s.status)}

${esc(tr('depends'))}: ${(s.depends_on || []).length ? s.depends_on.map(esc).join(' → ') : esc(tr('independent'))}

${esc(tr('instruction'))}

${esc(s.instruction)}

${esc(s.summary || tr('noResult'))}

${s.conversation_id ? `${esc(tr('trace'))}` : ''}${writable() && !active(t) && ['failed', 'blocked', 'interrupted', 'cleanup_unconfirmed'].includes(s.status) ? button('retry', 'retry', `data-step="${esc(s.id)}"`) : ''}${esc(tr('attempts', { count: s.attempts || 0 }))}
`).join('') : `
${esc(tr('noPlan'))}
`; + el('lt-guidance-send').disabled = state.mutating.has(t.id) || ['pausing', 'cancelling'].includes(t.status) || (!!t.question && (active(t) || !canExecute())); + const stepsRoot = el('lt-steps'); + const expanded = new Set(stepsRoot.dataset.taskId === t.id ? [...stepsRoot.querySelectorAll('[data-step-id] details[open]')].map(detail => detail.closest('[data-step-id]').dataset.stepId) : []); + stepsRoot.dataset.taskId = t.id; + el('lt-steps').innerHTML = t.steps.length ? t.steps.map(s => `
${esc(s.id)} · ${esc(s.title)}${badge(s.status)}

${esc(tr('depends'))}: ${(s.depends_on || []).length ? s.depends_on.map(esc).join(' → ') : esc(tr('independent'))}

${esc(tr('instruction'))}

${esc(s.instruction)}

${esc(s.summary || tr('noResult'))}

${s.conversation_id ? `${esc(tr('trace'))}` : ''}${writable() && !terminal && !active(t) && ['failed', 'blocked', 'interrupted', 'cleanup_unconfirmed'].includes(s.status) ? button('retry', 'retry', `data-step="${esc(s.id)}"`) : ''}${esc(tr('attempts', { count: s.attempts || 0 }))}
`).join('') : `
${esc(tr('noPlan'))}
`; + stepsRoot.querySelectorAll('[data-step-id] details').forEach(detail => { detail.open = expanded.has(detail.closest('[data-step-id]').dataset.stepId); }); el('lt-guidance-history').textContent = (t.guidance || []).join('\n\n'); } function renderEvents() { @@ -82,32 +93,44 @@ if (log.events.length) state.cursor = log.events[log.events.length - 1].id; renderTask(); renderEvents(); } - error(''); - } catch (e) { if (e.name !== 'AbortError' && epoch === state.epoch) error(e.message); } + if (state.errorKind === 'load') error(''); + } catch (e) { if (e.name !== 'AbortError' && epoch === state.epoch) error(e.message, 'load'); } finally { if (state.controller === controller) { state.controller = null; state.loading = false; } } } function invalidate() { state.epoch++; if (state.controller) state.controller.abort(); state.controller = null; state.loading = false; } function select(id) { - invalidate(); state.selected = id; state.task = null; state.events = []; state.cursor = 0; + error(''); invalidate(); state.selected = id; state.task = null; state.events = []; state.cursor = 0; el('lt-guidance-input').value = ''; renderTask(); renderEvents(); renderList(); refresh(); } - async function control(action, extra = {}) { - const task = state.task; if (!task) return; - const data = await api('/' + encodeURIComponent(task.id) + '/control/' + action, { method: 'POST', body: JSON.stringify({ revision: task.revision, ...extra }) }); - if (state.selected === task.id) { state.task = data.task; renderTask(); } - if (data.start_error) throw new Error(data.start_error); - invalidate(); await refresh(); + async function control(action, extra = {}, task = state.task) { + if (!task || state.mutating.has(task.id)) return null; + state.mutating.add(task.id); if (current(task)) { error(''); renderTask(); } + try { + const data = await api('/' + encodeURIComponent(task.id) + '/control/' + action, { method: 'POST', body: JSON.stringify({ revision: task.revision, ...extra }) }); + if (current(task)) { state.task = data.task; renderTask(); invalidate(); await refresh(); } + return data; + } catch (e) { + if (current(task)) { invalidate(); await refresh(); } + throw e; + } finally { state.mutating.delete(task.id); if (current(task)) renderTask(); } } async function act(action, target) { + const task = state.task; try { if (action === 'select') return select(target.dataset.id); if (action === 'refresh') { invalidate(); return refresh(); } if (action === 'new') return openCreate(); if (action === 'previous' || action === 'next') { state.offset = Math.max(0, state.offset + (action === 'next' ? 30 : -30)); invalidate(); return refresh(); } - if (!state.task) return; + if (!task || (mutationActions.has(action) && state.mutating.has(task.id))) return; if (action === 'delete') { if (!window.confirm(tr('deleteConfirm'))) return; - await api('/' + encodeURIComponent(state.task.id), { method: 'DELETE' }); state.selected = null; state.task = null; renderTask(); invalidate(); return refresh(); + error(''); state.mutating.add(task.id); renderTask(); + try { + await api('/' + encodeURIComponent(task.id), { method: 'DELETE' }); + if (current(task)) { state.selected = null; state.task = null; state.events = []; state.cursor = 0; renderTask(); renderEvents(); } + if (state.active) { invalidate(); await refresh(); } + } finally { state.mutating.delete(task.id); if (current(task)) renderTask(); } + return; } if (action === 'cancel' && !window.confirm(tr('cancelConfirm'))) return; if (action === 'retry') { @@ -116,12 +139,12 @@ } if (action === 'budget') return openBudget(); if (action === 'report') { - const response = await window.apiFetch('/api/long-tasks/' + encodeURIComponent(state.task.id) + '/report'); + const response = await window.apiFetch('/api/long-tasks/' + encodeURIComponent(task.id) + '/report'); if (!response.ok) throw new Error(String(response.status)); - const url = URL.createObjectURL(await response.blob()); const a = document.createElement('a'); a.href = url; a.download = 'task-' + state.task.id + '.md'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); return; + const url = URL.createObjectURL(await response.blob()); const a = document.createElement('a'); a.href = url; a.download = 'task-' + task.id + '.md'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); return; } await control(action); - } catch (e) { error(e.message); if (state.active) { invalidate(); await refresh(); error(e.message); } } + } catch (e) { if (!task || current(task)) error(e.message); } } function modal(title, body, submit) { el('lt-modal')?.remove(); @@ -133,19 +156,35 @@ dialog.showModal(); } const field = (label, html) => ``; + function syncOptionsButton() { + const button = el('task-new-goal'); if (!button) return; + button.dataset.stateDisabled = String(!!state.optionsRequest); + button.disabled = !!state.optionsRequest || !writable(); + button.setAttribute('aria-busy', String(!!state.optionsRequest)); + } + function cancelOptions() { + if (state.optionsRequest) state.optionsRequest.abort(); + state.optionsRequest = null; syncOptionsButton(); + } async function openCreate() { + if (!state.active || state.tab !== 'goals' || state.optionsRequest || !writable()) return; + const viewVersion = state.viewVersion; + const request = new AbortController(); state.optionsRequest = request; syncOptionsButton(); error(''); try { - const options = await api('/options'); state.options = options; + const options = await api('/options', { signal: request.signal }); + if (!state.active || state.tab !== 'goals' || state.optionsRequest !== request || state.viewVersion !== viewVersion) return; + state.options = options; const selectOptions = (items, key = 'id', label = 'name') => `` + items.map(item => ``).join(''); modal(tr('new'), `

${esc(tr('createHint'))}

${field('name', '')}${field('objective', '')}${field('scope', '')}${field('criteria', '')}
${field('project', ``)}${field('role', ``)}${field('model', ``)}${field('hitl', ``)}${field('concurrency', '')}${field('rounds', '')}${field('minutes', '')}
`, async form => { const body = Object.fromEntries(form); body.concurrency = Number(body.concurrency); body.max_rounds = Number(body.max_rounds); body.remaining_seconds = Number(body.minutes) * 60; delete body.minutes; - const created = await api('', { method: 'POST', body: JSON.stringify(body) }); select(created.task.id); + const created = await api('', { method: 'POST', body: JSON.stringify(body) }); if (state.active && state.tab === 'goals' && viewVersion === state.viewVersion) select(created.task.id); }); - } catch (e) { error(e.message); } + } catch (e) { if (e.name !== 'AbortError' && state.active && viewVersion === state.viewVersion) error(e.message); } + finally { if (state.optionsRequest === request) { state.optionsRequest = null; syncOptionsButton(); } } } function openBudget() { const task = state.task; - modal(tr('budget'), `
${field('rounds', ``)}${field('minutes', ``)}
`, form => control('budget', { max_rounds: Number(form.get('max_rounds')), remaining_seconds: Number(form.get('minutes')) * 60 })); + modal(tr('budget'), `
${field('rounds', ``)}${field('minutes', ``)}
`, form => control('budget', { max_rounds: Number(form.get('max_rounds')), remaining_seconds: Number(form.get('minutes')) * 60 }, task)); } function init() { state.active = true; @@ -155,20 +194,26 @@ document.querySelectorAll('[data-task-tab]').forEach(b => b.addEventListener('click', () => switchTab(b.dataset.taskTab))); el('task-new-goal').addEventListener('click', openCreate); root.addEventListener('click', event => { const target = event.target.closest('[data-lt-action]'); if (target) act(target.dataset.ltAction, target); }); - const filter = () => { state.offset = 0; invalidate(); refresh(); }; + const filter = () => { clearTimeout(state.searchTimer); state.offset = 0; invalidate(); refresh(); }; el('lt-filter').addEventListener('change', filter); el('lt-search').addEventListener('change', filter); + el('lt-search').addEventListener('search', filter); + el('lt-search').addEventListener('input', () => { clearTimeout(state.searchTimer); state.searchTimer = setTimeout(filter, 250); }); el('lt-guidance-form').addEventListener('submit', async event => { - event.preventDefault(); const input = el('lt-guidance-input'), value = input.value, selected = state.selected; - el('lt-guidance-send').disabled = true; - try { await control(state.task.question ? 'answer' : 'guidance', { message: value }); if (selected === state.selected && input.value === value) input.value = ''; } - catch (e) { error(e.message); } - finally { renderTask(); } + event.preventDefault(); const input = el('lt-guidance-input'), value = input.value, task = state.task; + if (!task || state.mutating.has(task.id) || el('lt-guidance-send').disabled) return; + try { + const data = await control(task.question ? 'answer' : 'guidance', { message: value }, task); + if (data && current(task)) { + if (input.value === value) input.value = ''; + if (data.start_error) error(tr('answerSaved') + ' ' + data.start_error); + } + } catch (e) { if (current(task)) error(e.message); } }); } switchTab(state.tab); if (!state.timer) state.timer = setInterval(() => { if (el('tasks-auto-refresh')?.checked) refresh(); }, 4000); } - function cleanup() { state.active = false; invalidate(); clearInterval(state.timer); state.timer = null; el('lt-modal')?.close(); } + function cleanup() { state.active = false; state.viewVersion++; cancelOptions(); clearTimeout(state.searchTimer); invalidate(); clearInterval(state.timer); state.timer = null; el('lt-modal')?.close(); } window.initLongTasks = init; window.cleanupLongTasks = cleanup; window.refreshTaskWorkspace = () => state.tab === 'goals' ? (invalidate(), refresh()) : window.refreshBatchQueues(); })(); diff --git a/web/static/js/tasks.js b/web/static/js/tasks.js index 41df19da..181cdcdb 100644 --- a/web/static/js/tasks.js +++ b/web/static/js/tasks.js @@ -813,6 +813,9 @@ function initTasksPage() { // 清理定时器(页面切换时调用) function cleanupTasksPage() { if (typeof cleanupLongTasks === 'function') cleanupLongTasks(); + closeBatchImportModal(); + closeAddBatchTaskModal(); + closeBatchQueueDetailModal(); if (tasksState.refreshInterval) { clearInterval(tasksState.refreshInterval); tasksState.refreshInterval = null; @@ -844,6 +847,21 @@ window.clearTasksHistory = clearTasksHistory; // ==================== 批量任务功能 ==================== +const batchFormPending = new Set(); +let batchImportVersion = 0; +let batchAddVersion = 0; +let batchDetailVersion = 0; + +function setBatchFormPending(kind, buttonId, pending) { + if (pending) batchFormPending.add(kind); else batchFormPending.delete(kind); + const button = document.getElementById(buttonId); + if (!button) return; + button.dataset.stateDisabled = String(pending); + button.disabled = pending || (typeof hasPermission === 'function' && !hasPermission('tasks:write')); + button.setAttribute('aria-busy', String(pending)); +} + + // 批量任务状态 const batchQueuesState = { queues: [], @@ -858,7 +876,7 @@ const batchQueuesState = { totalPages: 1 }; -async function refreshBatchProjectSelectOptions() { +async function refreshBatchProjectSelectOptions(version) { const projectSelect = document.getElementById('batch-queue-project-id'); if (!projectSelect) return; @@ -879,6 +897,7 @@ async function refreshBatchProjectSelectOptions() { ? parseProjectsListResponse(data).items : (Array.isArray(data) ? data : (data.projects || [])); } + if (version !== undefined && version !== batchImportVersion) return; const activeProjectId = typeof getActiveProjectId === 'function' ? getActiveProjectId() || '' : ''; list.forEach((project) => { @@ -898,6 +917,7 @@ async function refreshBatchProjectSelectOptions() { // 显示新建任务模态框 async function showBatchImportModal() { + const version = ++batchImportVersion; const modal = document.getElementById('batch-import-modal'); const input = document.getElementById('batch-tasks-input'); const titleInput = document.getElementById('batch-queue-title'); @@ -940,6 +960,7 @@ async function showBatchImportModal() { if (roleSelect && typeof loadRoles === 'function') { try { const loadedRoles = await loadRoles(); + if (version !== batchImportVersion) return; // 清空现有选项(除了默认选项) roleSelect.innerHTML = ''; @@ -962,7 +983,8 @@ async function showBatchImportModal() { console.error('加载角色列表失败:', error); } } - await refreshBatchProjectSelectOptions(); + await refreshBatchProjectSelectOptions(version); + if (version !== batchImportVersion) return; refreshBatchFormSelects(); openAppModal('batch-import-modal', { focusEl: input }); @@ -971,6 +993,7 @@ async function showBatchImportModal() { // 关闭新建任务模态框 function closeBatchImportModal() { + batchImportVersion++; closeAppModal('batch-import-modal'); } @@ -1020,6 +1043,7 @@ document.addEventListener('DOMContentLoaded', function() { // 创建批量任务队列 async function createBatchQueue() { + if (batchFormPending.has('create')) return; if (typeof requirePermission === 'function' && !requirePermission('tasks:write')) return; const input = document.getElementById('batch-tasks-input'); const titleInput = document.getElementById('batch-queue-title'); @@ -1068,6 +1092,8 @@ async function createBatchQueue() { return; } + const version = batchImportVersion; + setBatchFormPending('create', 'batch-queue-create-btn', true); try { const response = await apiFetch('/api/batch-tasks', { method: 'POST', @@ -1094,17 +1120,17 @@ async function createBatchQueue() { } const result = await response.json(); - closeBatchImportModal(); - - // 显示队列详情 - showBatchQueueDetail(result.queueId); + if (version === batchImportVersion && isAppModalOpen('batch-import-modal')) { + closeBatchImportModal(); + showBatchQueueDetail(result.queueId); + } // 刷新批量队列列表 refreshBatchQueues(); } catch (error) { console.error('创建批量任务队列失败:', error); - alert(_t('tasks.createBatchQueueFailed') + ': ' + error.message); - } + if (version === batchImportVersion) alert(_t('tasks.createBatchQueueFailed') + ': ' + error.message); + } finally { setBatchFormPending('create', 'batch-queue-create-btn', false); } } // 获取角色图标(辅助函数) @@ -1761,6 +1787,7 @@ function changeBatchQueuesPageSize() { // 显示批量任务队列详情 async function showBatchQueueDetail(queueId) { + const version = ++batchDetailVersion; const modal = document.getElementById('batch-queue-detail-modal'); const title = document.getElementById('batch-queue-detail-title'); const content = document.getElementById('batch-queue-detail-content'); @@ -1771,6 +1798,11 @@ async function showBatchQueueDetail(queueId) { if (!modal || !content) return; + if (batchQueuesState.currentQueueId !== queueId) { + stopBatchQueueRefresh(); batchQueuesState.currentQueueId = null; + content.innerHTML = '

…

'; + modal.querySelectorAll('.modal-header-actions button').forEach(button => { button.style.display = 'none'; }); + } const alreadyOpen = isAppModalOpen('batch-queue-detail-modal'); if (!alreadyOpen) { if (content) content.innerHTML = '

…

'; @@ -1794,6 +1826,7 @@ async function showBatchQueueDetail(queueId) { } const result = await response.json(); + if (version !== batchDetailVersion || !isAppModalOpen('batch-queue-detail-modal')) return; const queue = result.queue; batchQueuesState.currentQueueId = queueId; const pres = getBatchQueueStatusPresentation(queue); @@ -1886,6 +1919,7 @@ async function showBatchQueueDetail(queueId) { const savedTechDetailsOpen = sameQueueAsBefore && !!(prevTechDetails && prevTechDetails.open); deferModalContent(function () { + if (version !== batchDetailVersion || !isAppModalOpen('batch-queue-detail-modal')) return; content.innerHTML = `
@@ -1969,12 +2003,19 @@ async function showBatchQueueDetail(queueId) { stopBatchQueueRefresh(); } } catch (error) { + if (version !== batchDetailVersion || !isAppModalOpen('batch-queue-detail-modal')) return; console.error('获取队列详情失败:', error); closeBatchQueueDetailModal(); alert(_t('tasks.getQueueDetailFailed') + ': ' + error.message); } } +function refreshBatchQueueDetailIfCurrent(queueId) { + if (batchQueuesState.currentQueueId === queueId && isAppModalOpen('batch-queue-detail-modal')) { + return showBatchQueueDetail(queueId); + } +} + // 开始批量任务队列 async function startBatchQueue() { const queueId = batchQueuesState.currentQueueId; @@ -2005,7 +2046,7 @@ async function startBatchQueue() { } // 刷新详情 - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (error) { console.error('启动批量任务失败:', error); @@ -2036,7 +2077,7 @@ async function pauseBatchQueue() { } // 刷新详情 - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (error) { console.error('暂停批量任务失败:', error); @@ -2066,7 +2107,7 @@ async function rerunBatchQueue() { throw new Error(result.error || _t('tasks.rerunQueueFailed')); } - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (error) { console.error('重跑批量任务失败:', error); @@ -2139,6 +2180,7 @@ async function deleteBatchQueueFromList(queueId) { // 关闭批量任务队列详情模态框 function closeBatchQueueDetailModal() { + batchDetailVersion++; closeAppModal('batch-queue-detail-modal'); batchQueuesState.currentQueueId = null; stopBatchQueueRefresh(); @@ -2171,7 +2213,7 @@ function startBatchQueueRefresh(queueId) { batchQueuesState._bqDetailRefreshing = true; (async () => { try { - await showBatchQueueDetail(queueId); + await refreshBatchQueueDetailIfCurrent(queueId); await refreshBatchQueues(); } catch (e) { console.warn('批量队列定时刷新失败:', e); @@ -2259,7 +2301,7 @@ function editBatchTaskFromElement(button) { function cancelInlineTask() { // 刷新整个详情来还原 const queueId = batchQueuesState.currentQueueId; - if (queueId) showBatchQueueDetail(queueId); + if (queueId) refreshBatchQueueDetailIfCurrent(queueId); } async function saveInlineTask(queueId, taskId) { @@ -2290,7 +2332,7 @@ async function saveInlineTask(queueId, taskId) { _bqInlineSaving = false; // 刷新队列详情 if (batchQueuesState.currentQueueId === queueId) { - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); } // 刷新队列列表 @@ -2304,6 +2346,7 @@ async function saveInlineTask(queueId, taskId) { // 显示添加批量任务模态框 function showAddBatchTaskModal() { + batchAddVersion++; if (typeof requirePermission === 'function' && !requirePermission('tasks:write')) return; const queueId = batchQueuesState.currentQueueId; if (!queueId) { @@ -2350,6 +2393,7 @@ function showAddBatchTaskModal() { // 关闭添加批量任务模态框 function closeAddBatchTaskModal() { + batchAddVersion++; // 清理事件监听器 if (showAddBatchTaskModal._escHandler) { document.removeEventListener('keydown', showAddBatchTaskModal._escHandler); @@ -2372,6 +2416,7 @@ function closeAddBatchTaskModal() { // 保存添加的批量任务 async function saveAddBatchTask() { + if (batchFormPending.has('add')) return; const queueId = batchQueuesState.currentQueueId; const messageInput = document.getElementById('add-task-message'); @@ -2391,6 +2436,8 @@ async function saveAddBatchTask() { return; } + const version = batchAddVersion; + setBatchFormPending('add', 'batch-task-add-btn', true); try { const response = await apiFetch(`/api/batch-tasks/${queueId}/tasks`, { method: 'POST', @@ -2406,19 +2453,19 @@ async function saveAddBatchTask() { } // 关闭添加任务模态框 - closeAddBatchTaskModal(); + if (version === batchAddVersion && batchQueuesState.currentQueueId === queueId && isAppModalOpen('add-batch-task-modal')) closeAddBatchTaskModal(); // 刷新队列详情 if (batchQueuesState.currentQueueId === queueId) { - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); } // 刷新队列列表 refreshBatchQueues(); } catch (error) { console.error('添加任务失败:', error); - alert(_t('tasks.addTaskFailed') + ': ' + error.message); - } + if (version === batchAddVersion) alert(_t('tasks.addTaskFailed') + ': ' + error.message); + } finally { setBatchFormPending('add', 'batch-task-add-btn', false); } } // 从元素获取任务信息并删除任务 @@ -2475,7 +2522,7 @@ async function deleteBatchTask(queueId, taskId) { // 刷新队列详情 if (batchQueuesState.currentQueueId === queueId) { - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); } // 刷新队列列表 @@ -2499,12 +2546,12 @@ async function updateBatchQueueScheduleEnabled(enabled) { const result = await response.json().catch(() => ({})); throw new Error(result.error || _t('batchQueueDetailModal.scheduleToggleFailed')); } - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { console.error(e); alert(_t('batchQueueDetailModal.scheduleToggleFailed') + ': ' + e.message); - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); } } @@ -2512,7 +2559,7 @@ async function updateBatchQueueScheduleEnabled(enabled) { function cancelAllInlineEdits() { _bqInlineSaving = true; // 防止 blur 触发保存 const queueId = batchQueuesState.currentQueueId; - if (queueId) showBatchQueueDetail(queueId); + if (queueId) refreshBatchQueueDetailIfCurrent(queueId); _bqInlineSaving = false; } @@ -2566,7 +2613,7 @@ async function saveInlineTitle() { throw new Error(result.error || _t('tasks.updateTaskFailed')); } _bqInlineSaving = false; - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { _bqInlineSaving = false; @@ -2633,7 +2680,7 @@ async function saveInlineRole() { throw new Error(result.error || _t('tasks.updateTaskFailed')); } _bqInlineSaving = false; - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { _bqInlineSaving = false; @@ -2700,7 +2747,7 @@ async function saveInlineAgentMode() { throw new Error(result.error || _t('tasks.updateTaskFailed')); } _bqInlineSaving = false; - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { _bqInlineSaving = false; @@ -2775,7 +2822,7 @@ async function saveInlineConcurrency() { throw new Error(result.error || _t('tasks.updateTaskFailed')); } _bqInlineSaving = false; - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { _bqInlineSaving = false; @@ -2799,7 +2846,7 @@ async function runSingleBatchTask(queueId, taskId) { if (result.autoStarted === false && result.message) { alert(result.message); } - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { console.error('单条执行失败:', e); @@ -2890,7 +2937,7 @@ async function saveInlineSchedule() { throw new Error(result.error || _t('batchQueueDetailModal.editScheduleError')); } _bqInlineSaving = false; - showBatchQueueDetail(queueId); + refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (e) { _bqInlineSaving = false; @@ -2992,7 +3039,7 @@ async function startInlineEditHITLPolicy() { const select = document.getElementById('bq-edit-hitl'); select.focus(); select.addEventListener('keydown', e => { - if (e.key === 'Escape') showBatchQueueDetail(queueId); + if (e.key === 'Escape') refreshBatchQueueDetailIfCurrent(queueId); }); select.addEventListener('change', async () => { select.disabled = true; @@ -3008,7 +3055,7 @@ async function startInlineEditHITLPolicy() { const error = await result.json().catch(() => ({})); throw new Error(error.error || _t('tasks.updateTaskFailed')); } - if (batchQueuesState.currentQueueId === queueId) showBatchQueueDetail(queueId); + if (batchQueuesState.currentQueueId === queueId) refreshBatchQueueDetailIfCurrent(queueId); refreshBatchQueues(); } catch (error) { select.disabled = false; diff --git a/web/templates/index.html b/web/templates/index.html index dd6059e6..13e32ca2 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -50,7 +50,7 @@ - +
@@ -6494,7 +6494,7 @@
- +
@@ -7174,8 +7174,8 @@ - - + +