diff --git a/console/static/personal-feedback.test.js b/console/static/personal-feedback.test.js index 903ffbae..55589df1 100644 --- a/console/static/personal-feedback.test.js +++ b/console/static/personal-feedback.test.js @@ -41,7 +41,7 @@ test('a different project stays independent; edits cannot replace a running requ assert.deepEqual(calls.map(call => call.project_id), ['one', 'two']); }); -async function page({failedHistory = false, readReceipt} = {}) { +async function page({failedHistory = false, readReceipt, history = [], saved = new Map(), proposal = null, readReview} = {}) { const nodes = new Map(), submitted = [], proposals = []; let generated = 0; function node(id) { if (!nodes.has(id)) nodes.set(id, { @@ -67,19 +67,21 @@ async function page({failedHistory = false, readReceipt} = {}) { } if (url.endsWith('/feedback')) { if (submitted.length && failedHistory) throw Error('list unavailable'); - return response({feedback: submitted.map(row => ({...row, id: 'recorded-id'}))}); + return response({feedback: [...history, ...submitted.map(row => ({...row, id: 'recorded-id'}))]}); } if (url.endsWith('/feedback/recorded-id')) { - const receipt = {...submitted[0], id: 'recorded-id'}; + const receipt = {...(history[0] || submitted[0]), id: 'recorded-id'}; return response(readReceipt ? await readReceipt(receipt) : receipt); } if (url.endsWith('/feedback/recorded-id/proposal')) { proposals.push(options.method); - return response({proposal: null}); + return response({proposal}); } + if (readReview && url.endsWith('/evolution/evo-one')) return response(readReview(proposals)); return response({revision:1}); }; - const storage = {getItem: () => null, removeItem() {}}; + const storage = {getItem: key => saved.get(key) ?? null, setItem: (key, value) => saved.set(key, value), + removeItem: key => saved.delete(key)}; vm.runInNewContext(fs.readFileSync(path.join(__dirname, 'personal.js'),'utf8'), { document, fetch, window: {HGPersonalDraft: require('./personal-draft.js'), HGPersonalWindow: require('./personal-window.js'), HGPersonalFeedback:{create}, HGPersonalProposal: require('./personal-proposal.js'), @@ -127,6 +129,52 @@ test('submission and history open the same proposal without creating a second ta assert.equal(ui.submitted.length, 1); }); +test('refresh reopens the selected feedback read-only and leaving the detail clears that selection', async () => { + const saved = new Map(), history = [{id: 'recorded-id', kind: 'explicit_request', text: 'Saved feedback', evidence: []}]; + const first = await page({saved, history}); + await first.node('feedback-history').children[0].children[1].onclick(); + const restored = await page({saved, history}); + assert.equal(restored.node('proposal-page').hidden, false); + assert.match(restored.node('proposal-feedback').textContent, /Saved feedback/); + assert.deepEqual(restored.proposals, ['GET']); + assert.deepEqual(restored.submitted, []); + await restored.node('proposal-records').onclick(); + const records = await page({saved, history}); + assert.deepEqual(records.proposals, []); +}); + +test('an unmeasured proposal shows its reason without opening a review job', async () => { + for (const [reason, label] of [['scenario_unavailable', '场景不可用'], ['invalid_conditions', '验收条件超出复测支持的范围']]) { + const history = [{id: 'recorded-id', kind: 'explicit_request', text: 'Saved feedback', evidence: []}]; + const proposal = {status: 'ready', result: {evolution_job: null, + evolution_review: {status: 'unmeasured', reason_code: reason}}}; + const ui = await page({history, proposal}); + await ui.node('feedback-history').children[0].children[1].onclick(); + assert.equal(ui.node('review-title').textContent, '本次提案未复测'); + assert.equal(ui.node('review-detail').textContent, label); + assert.equal(ui.node('review-refs').hidden, true); + } +}); + +test('a pending local review can be resumed from history without configuring the proposal model', async () => { + const history = [{id: 'recorded-id', kind: 'explicit_request', text: 'Saved feedback', evidence: []}]; + const job = {profile_id: 'default', project_id: 'one', job_id: 'evo-one'}; + const proposal = {status: 'ready', result: {evolution_job: job}}; + const ui = await page({history, proposal, readReview: requests => ({ + job, status: requests.includes('POST') ? 'no_change' : 'collecting' + })}); + await ui.node('feedback-history').children[0].children[1].onclick(); + await new Promise(resolve => setImmediate(resolve)); + const action = ui.node('proposal-refresh'); + assert.deepEqual(ui.proposals, ['GET']); + assert.equal(action.hidden, false); + assert.equal(action.textContent, '继续复测'); + await action.onclick(); + assert.deepEqual(ui.proposals, ['GET', 'POST']); + assert.equal(action.textContent, '重新查看状态'); + assert.equal(ui.node('review-title').textContent, '无需修改'); +}); + for (const failed of [false, true]) { test(`collapsing ignores a late history ${failed ? 'error' : 'receipt'}`, async () => { let finishRead; diff --git a/console/static/personal-proposal.js b/console/static/personal-proposal.js index d2415b91..bcfd2de8 100644 --- a/console/static/personal-proposal.js +++ b/console/static/personal-proposal.js @@ -1,5 +1,6 @@ (function(root) { 'use strict'; + const review = typeof module !== 'undefined' && module.exports ? require('./personal-review') : root.HGPersonalReview; const active = new Set(['collecting', 'planning', 'proposing', 'checking']); const messages = { collecting: '正在读取项目指令', planning: '正在根据反馈制定计划', @@ -34,20 +35,27 @@ return current; } - function create({read, start, reply, cancel, updates, render, + function create({read, start, reply, cancel, updates, render, reviewApi, + reviewWait = () => new Promise(resolve => setTimeout(resolve, 1500)), wait = () => new Promise(resolve => setTimeout(resolve, 350))}) { let version = 0, controller; - function reset() { version++; controller?.abort(); render(null); } - async function open(project, feedback, action, initial = null) { + let pendingReply; + function stop() { version++; controller?.abort(); } + function reset() { stop(); pendingReply = undefined; render(null); } + async function open(project, feedback, action, initial = null, initialReview = null) { const current = ++version; controller?.abort(); const abort = controller = new AbortController(); let proposal = initial, after = 0, readFailures = 0; const display = (extra = {}) => render({project, feedback, proposal, ...extra}); - display({loading: true}); + display({loading: true, review: initialReview}); try { - ({proposal} = await action(project, feedback)); + ({proposal} = await action(project, feedback, abort.signal)); while (current === version) { + if (proposal?.feedback_id && proposal.feedback_id !== feedback) { + proposal = null; + throw Error('提案回执与当前反馈不匹配。'); + } display(); if (!active.has(proposal?.status)) break; if (updates) { @@ -57,20 +65,39 @@ } else await wait(); if (current !== version) break; try { - ({proposal} = await read(project, feedback)); + ({proposal} = await read(project, feedback, abort.signal)); readFailures = 0; } catch (error) { if (++readFailures >= 3) throw error; await wait(); } } + if (current === version && review.linkedJob(proposal?.result) && reviewApi) { + await review.watch({api: reviewApi, project, result: proposal.result, signal: abort.signal, + wait: reviewWait, display: value => { if (current === version) display({review: value}); }}); + } } catch (error) { - if (current === version) display({error: errors[error.code] || error.message}); + if (current === version) display({error: errors[error.code] || error.message, review: initialReview}); } } - return {reset, show: (project, feedback, generate = false) => open(project, feedback, generate ? start : read), + async function answerReview(project, feedback, proposal, question, answer, currentReview) { + const job = review.linkedJob(proposal.result); + const local = Boolean(proposal.result.evolution_job); + const key = JSON.stringify([job, question, answer]); + if (!pendingReply || pendingReply.key !== key) pendingReply = {key, id: 'reply_' + root.crypto.randomUUID()}; + await open(project, feedback, async (_id, _feedback, signal) => { + if (job.project_id !== project || job.profile_id !== 'default') throw Error('任务归属不匹配。'); + const payload = {question_id: question, answer}; + if (!local) payload.idempotency_key = pendingReply.id; + const view = await reviewApi(review.paths(job, local).task + '/reply', payload, {signal}); + if (!review.sameJob(view?.job, job)) throw Error('回复回执的任务归属不匹配。'); + if (!signal.aborted) pendingReply = undefined; + return {proposal}; + }, proposal, currentReview); + } + return {reset, stop, answerReview, show: (project, feedback, generate = false) => open(project, feedback, generate ? start : read), reply: (project, feedback, question, answer, current) => open(project, feedback, - (id, receipt) => reply(id, receipt, question, answer), current), + (id, receipt, signal) => reply(id, receipt, question, answer, signal), current), cancel: (project, feedback, current) => open(project, feedback, cancel, current)}; } @@ -106,6 +133,8 @@ return summary; } - if (typeof module !== 'undefined' && module.exports) module.exports = {create, describe, lastEventId, summarizeDiff}; - else root.HGPersonalProposal = {create, describe, summarizeDiff}; + const exported = {create, describe, lastEventId, summarizeDiff, renderReview: review.render, + linkedJob: review.linkedJob, initialReview: review.initialReview}; + if (typeof module !== 'undefined' && module.exports) module.exports = exported; + else root.HGPersonalProposal = exported; })(typeof window === 'undefined' ? globalThis : window); diff --git a/console/static/personal-review.js b/console/static/personal-review.js new file mode 100644 index 00000000..1c1c54f2 --- /dev/null +++ b/console/static/personal-review.js @@ -0,0 +1,271 @@ +(function(root) { + 'use strict'; + const pending = new Set(['created', 'collecting', 'reproducing', 'baseline_ready', 'proposing', 'validating', 'retesting']); + const labels = { + needs_input: '等待补充信息', not_reproduced: '原版本未复现问题', not_comparable: '两次运行不可比', + retest_passed: '复测通过', retest_failed: '候选复测失败', no_change: '无需修改', + failed: '审核失败', interrupted: '审核已中断', cancelled: '审核已取消' + }; + const reasons = { + missing_evidence: '缺少判定所需的证据', execution_timeout: '运行超时', scenario_mismatch: '两次运行的场景或输入不一致', + stale_snapshot: '文件快照已变化', unstable_result: '多次尝试的结果不一致', budget_exhausted: '任务预算已用完', + runner_unavailable: '运行器不可用', scenario_unavailable: '场景不可用', candidate_failed: '候选未达到场景要求', + baseline_passed: '原版本已满足要求', invalid_conditions: '验收条件超出复测支持的范围' + }; + class ReviewMismatch extends Error {} + function check(valid) { + if (!valid) throw new ReviewMismatch('回执与当前任务或冻结版本不匹配,请重新查看。'); + } + function id(value) { + check(typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value)); + return encodeURIComponent(value); + } + function sameJob(actual, expected) { + return actual?.job_id === expected.job_id && actual?.project_id === expected.project_id && + actual?.profile_id === expected.profile_id; + } + function paths(job, local = false) { + if (local) return {task: 'projects/' + id(job.project_id) + '/evolution/' + id(job.job_id)}; + const scope = 'evolution/v1/profiles/' + id(job.profile_id) + '/projects/' + id(job.project_id); + return {scope, task: scope + '/jobs/' + id(job.job_id)}; + } + function linkedJob(result) { return result?.evolution_job ?? result?.job_ref; } + function reason(code) { return reasons[code] || (typeof code === 'string' ? code : ''); } + function initialReview(proposal) { + if (linkedJob(proposal?.result)) return {title: '正在读取审核任务…'}; + if (proposal?.status !== 'ready') return null; + const saved = proposal.result?.evolution_review; + if (saved?.status === 'unmeasured') return {title: '本次提案未复测', reason: reason(saved.reason_code)}; + return {title: '这份历史提案尚无关联审核任务'}; + } + function supportsRetestPass(run) { + const candidate = run.phase === 'candidate'; + if (run.judge_result !== (candidate ? 'met' : 'not_met')) return false; + if (run.scenario_id !== 'python-related-tests') return true; + return Number.isInteger(run.exit_code) && ((run.exit_code === 0) === candidate); + } + function verdict(view, report, runs) { + if ([view.reason_code, report?.reason_code].includes('execution_timeout') || + runs.some(row => row.status === 'timeout' || row.reason_code === 'execution_timeout')) return '运行超时'; + if (report?.verdict === 'retest_passed' && runs.every(row => row.scenario_id === 'python-related-tests')) + return '复测通过 · 已验证指令文本'; + if (report) return labels[report.verdict] || '报告结论待确认'; + if (pending.has(view.status) || view.status === 'retest_passed') return '等待复测报告'; + return labels[view.status] || '审核状态待确认'; + } + + async function localDetails(api, job, view, result, signal) { + const {task} = paths(job, true); + const review = {job, canResume: pending.has(view.status), title: verdict(view, null, []), reason: reason(view.reason_code), + original: result.original_text, adoption: '尚无采用回执'}; + if (view.status === 'needs_input' && view.question_id) { + const question = await api(task + '/questions/' + id(view.question_id), undefined, {signal}); + check(sameJob(question?.job, job) && question.question_id === view.question_id); + review.question = question; + } + if (!view.comparison_ref) return review; + const report = await api(task + '/comparisons/' + id(view.comparison_ref), undefined, {signal}); + check(sameJob(report?.job, job) && report.comparison_ref === view.comparison_ref && + report.status === view.status && view.candidate_id && report.candidate_id === view.candidate_id && + result.snapshot_sha256 && report.snapshot_sha256 === result.snapshot_sha256 && + result.candidate_sha256 && report.candidate_sha256 === result.candidate_sha256); + const runs = ['baseline', 'candidate'].map(phase => { + const run = report[phase]; + check(run?.phase === phase && run.run_ref && report.scenario_id && run.scenario_id === report.scenario_id); + const executed = Number.isInteger(run.exit_code) && run.timed_out === false && !run.reason_code; + return {...run, status: run.timed_out ? 'timeout' : (executed ? 'executed' : 'failed'), + judge_result: executed ? (run.exit_code === 0 ? 'met' : 'not_met') : 'unknown', + log: {text: [run.stdout, run.stderr].filter(Boolean).join('\n'), truncated: run.output_truncated}}; + }); + const [before, after] = runs; + check(before.run_ref !== after.run_ref); + if (report.status === 'retest_passed') { + check(report.comparable === true && before.judge_result === 'not_met' && after.judge_result === 'met' && + before.source_unchanged === true && after.source_unchanged === true && Array.isArray(before.command) && + before.command.length && JSON.stringify(before.command) === JSON.stringify(after.command)); + } + const summary = {...report, report_ref: report.comparison_ref, verdict: report.status, fixture: result.fixture}; + return {...review, title: verdict(view, summary, runs), reason: reason(report.reason_code || view.reason_code), + runs, report: summary}; + } + + async function details(api, job, view, result, signal) { + const {scope, task} = paths(job); + const get = path => { + signal.throwIfAborted(); + return api(path, undefined, {signal}); + }; + async function artifact(ref, kind) { + const item = await get(scope + '/artifacts/' + id(ref) + '?kind=' + kind); + check(item?.ref === ref && item.kind === kind); + return item; + } + let original, candidate, report, question, adoption = '尚无采用回执'; + const runs = []; + if (view.candidate_id) { + candidate = await get(task + '/candidates/' + id(view.candidate_id)); + check(sameJob(candidate?.job, job) && candidate.candidate_id === view.candidate_id && + typeof result.snapshot_sha256 === 'string' && candidate.snapshot_sha256 === result.snapshot_sha256); + if (result.candidate_sha256) check(result.candidate_sha256 === candidate.candidate_sha256); + else check(candidate.diff_ref); + const snapshot = await artifact(candidate.snapshot_ref, 'virtual_snapshot'); + check(snapshot.sha256 === candidate.snapshot_sha256 && !snapshot.truncated); + original = snapshot.payload?.files?.['instruction.md']; + check(typeof original === 'string'); + if (typeof result.original_text === 'string') check(original === result.original_text); + if (!result.candidate_sha256) { + const diff = await artifact(candidate.diff_ref, 'diff'); + check(!diff.truncated && diff.payload?.text === result.diff); + } + } + if (view.question_id && view.status === 'needs_input') { + question = await get(task + '/questions/' + id(view.question_id)); + check(question?.question_id === view.question_id && (!question.job || sameJob(question.job, job))); + } + if (view.comparison_ref) { + report = await get(task + '/reports/' + id(view.comparison_ref)); + check(sameJob(report?.job, job) && report.report_ref === view.comparison_ref && + (!report.candidate_id || report.candidate_id === view.candidate_id) && + (!report.candidate_sha256 || report.candidate_sha256 === candidate?.candidate_sha256) && + view.status === report.verdict); + const seen = new Set(); + for (const phase of ['baseline', 'candidate']) { + const refs = report[phase + '_run_refs']; + check(Array.isArray(refs) && refs.length <= 3); + for (const ref of refs) { + check(!seen.has(ref)); seen.add(ref); + const run = await get(task + '/runs/' + id(ref)); + check(sameJob(run?.job, job) && run.run_ref === ref && run.phase === phase && + run.snapshot_sha256 === result.snapshot_sha256 && run.fixture === report.fixture); + let log; + if (run.log_ref) { + const item = await artifact(run.log_ref, 'run_log'); + check(typeof item.payload?.text === 'string'); + log = {text: item.payload.text, truncated: item.truncated || run.log_truncated}; + } + runs.push({...run, log}); + } + } + if (report.verdict === 'retest_passed') { + const first = runs[0]; + check(candidate && report.candidate_id === candidate.candidate_id && report.comparable === true && + ![view.reason_code, report.reason_code].includes('execution_timeout') && + report.baseline_run_refs.length && report.candidate_run_refs.length && + runs.every(row => row.status === 'executed' && row.reason_code !== 'execution_timeout' && supportsRetestPass(row) && + row.scenario_id && row.scenario_sha256 && + row.scenario_id === first.scenario_id && row.scenario_sha256 === first.scenario_sha256 && + Array.isArray(row.command) && row.command.length && + JSON.stringify(row.command) === JSON.stringify(first.command) && + (row.phase !== 'candidate' || row.prepared_sha256 && + [candidate.candidate_sha256, result.prepared_sha256].includes(row.prepared_sha256)))); + } + } + const versionRef = result.version_receipt_ref || view.version_receipt_ref; + if (versionRef) { + const receipt = await get(task + '/receipts/' + id(versionRef)); + check(sameJob(receipt?.operation?.job, job) && receipt.receipt_ref === versionRef && + candidate && receipt.candidate_id === candidate.candidate_id && receipt.candidate_sha256 === candidate.candidate_sha256); + const entry = receipt.entries?.length === 1 && receipt.entries[0]; + const states = {applied: '已采用', rolled_back: '已回退', unchanged: '未改动', conflict: '采用时发生冲突', failed: '采用失败'}; + adoption = candidate.target_ids?.includes(entry?.target_id) && states[entry.status] || '采用回执待核对'; + } + return {job, title: verdict(view, report, runs), reason: reason(report?.reason_code || view.reason_code), + original: original ?? result.original_text, report, runs, question, adoption}; + } + + async function watch({api, project, result, signal, display, wait}) { + const job = linkedJob(result); + let after = 0, previous = '', pageFailures = 0, readFailures = 0; + try { + check(job.project_id === project && job.profile_id === 'default'); + const local = Boolean(result.evolution_job); + const {task} = paths(job, local); + while (!signal.aborted) { + let view; + try { + view = await api(task, undefined, {signal}); + readFailures = 0; + } catch (error) { + if (signal.aborted || ++readFailures >= 3) throw error; + await wait(); + continue; + } + check(sameJob(view?.job, job)); + const signature = JSON.stringify(view); + if (signature !== previous) { + const current = await (local ? localDetails : details)(api, job, view, result, signal); + if (signal.aborted) return; + display(current); previous = signature; + } + if (!pending.has(view.status) && !(view.status === 'retest_passed' && !view.comparison_ref)) return; + await wait(); + if (signal.aborted) return; + try { + const page = await api(task + '/events?after=' + after, undefined, {signal}); + let cursor = after; + check(Array.isArray(page.events)); + for (const event of page.events) { + check(sameJob(event?.job, job) && Number.isSafeInteger(event.seq) && event.seq > cursor); + cursor = event.seq; + } + check(page.next_after === cursor); + after = cursor; pageFailures = 0; + } catch (error) { + // A dropped event page leaves its cursor intact. Read the job again on reconnect. + if (error instanceof ReviewMismatch || ++pageFailures >= 3) throw error; + } + } + } catch (error) { + if (!signal.aborted) display({job: job.project_id === project && job.profile_id === 'default' ? job : null, + title: '复测报告暂不可用', error: error.message || '暂时无法读取复测报告。'}); + } + } + + function render(doc, review) { + const el = name => doc.getElementById('review-' + name); + el('section').hidden = !review; + if (!review) return; + el('title').textContent = review.title; + el('detail').textContent = [review.reason, review.error].filter(Boolean).join(' · '); + el('detail').hidden = !el('detail').textContent; + el('refs').hidden = !review.job; + el('refs').textContent = review.job ? [review.job.project_id, review.job.job_id, review.report?.report_ref].filter(Boolean).join(' / ') : ''; + el('adoption').textContent = review.adoption || ''; + el('fixture').hidden = review.report?.fixture !== true; + el('original').hidden = typeof review.original !== 'string'; + el('source').textContent = review.original ?? ''; + const question = review.question; + el('prompt').textContent = question?.prompt || ''; + el('prompt').hidden = !question?.prompt; + const block = (tag, text) => { + const element = doc.createElement(tag); + element.textContent = text; + return element; + }; + el('runs').replaceChildren(); + if (!review.report) return; + const judges = {met: '满足要求', not_met: '未满足要求', unknown: '未判定'}; + for (const phase of ['baseline', 'candidate']) { + const section = doc.createElement('section'); + section.append(block('h4', phase === 'baseline' ? '原版本运行' : '候选运行')); + const rows = review.runs.filter(row => row.phase === phase); + if (!rows.length) section.append(block('p', '没有运行记录')); + for (const row of rows) { + if (rows.length > 1) section.append(block('strong', '第 ' + row.attempt + ' 次尝试')); + section.append(block('p', [row.scenario_id || '场景未记录', + Number.isInteger(row.exit_code) ? '退出码 ' + row.exit_code : '无退出码', + judges[row.judge_result] || '判定未知'].join(' · '))); + const command = Array.isArray(row.command) && row.command.map(arg => + /[\s"']/.test(arg) ? JSON.stringify(arg) : arg).join(' '); + section.append(block('small', '执行命令'), block('pre', command || '无命令记录')); + if (row.reason_code) section.append(block('p', reason(row.reason_code))); + section.append(block('small', '运行证据'), block('pre', row.log?.text || (row.log ? '日志为空' : '无日志记录'))); + if (row.log?.truncated) section.append(block('small', '日志已截断')); + } + el('runs').append(section); + } + } + const exported = {watch, render, paths, sameJob, linkedJob, initialReview}; + if (typeof module !== 'undefined' && module.exports) module.exports = exported; + else root.HGPersonalReview = exported; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/console/static/personal-review.test.js b/console/static/personal-review.test.js new file mode 100644 index 00000000..f390f004 --- /dev/null +++ b/console/static/personal-review.test.js @@ -0,0 +1,201 @@ +'use strict'; +const assert = require('node:assert/strict'); +const test = require('node:test'); +const {create} = require('./personal-proposal'); +const {watch, paths} = require('./personal-review'); + +const job = {profile_id: 'default', project_id: 'project-a', job_id: 'evo-one'}; +const {scope, task} = paths(job); +const result = {job_ref: job, snapshot_sha256: 'a'.repeat(64), candidate_sha256: 'b'.repeat(64), diff: '+new'}; +function fixture() { + const view = {job, status: 'retest_passed', candidate_id: 'cand', comparison_ref: 'report'}; + const report = {report_ref: 'report', job, candidate_id: 'cand', comparable: true, verdict: view.status, + baseline_run_refs: ['r1'], candidate_run_refs: ['r2'], fixture: true}; + const data = new Map([[task, view], [task + '/reports/report', report], + [task + '/candidates/cand', {job, candidate_id: 'cand', snapshot_ref: 'snap', target_ids: ['project-instructions'], + snapshot_sha256: result.snapshot_sha256, candidate_sha256: result.candidate_sha256}], + [scope + '/artifacts/snap?kind=virtual_snapshot', {kind: 'virtual_snapshot', ref: 'snap', + sha256: result.snapshot_sha256, payload: {files: {'instruction.md': 'before'}}}]]); + for (const [index, phase] of ['baseline', 'candidate'].entries()) { + const ref = 'r' + (index + 1), log = 'log' + index; + data.set(task + '/runs/' + ref, {job, run_ref: ref, phase, scenario_id: 'python-related-tests', + scenario_sha256: 'c'.repeat(64), snapshot_sha256: result.snapshot_sha256, fixture: true, + command: ['python', 'check.py'], log_ref: log, prepared_sha256: index ? result.candidate_sha256 : null, + exit_code: index ? 0 : 1, judge_result: index ? 'met' : 'not_met', status: 'executed'}); + data.set(scope + '/artifacts/' + log + '?kind=run_log', {ref: log, kind: 'run_log', payload: {text: phase}}); + } + return {view, report, data, api: async (path, value) => { + assert.equal(value, undefined); assert.ok(data.has(path), path); return data.get(path); + }}; +} +async function read(f, options = {}) { + const output = []; + await watch({project: job.project_id, result, api: f.api, signal: new AbortController().signal, + display: value => output.push(value), wait: async () => {}, ...options}); + return output.at(-1); +} + +test('reads the frozen original, both scoped runs and logs before reporting a text-only pass', async () => { + const value = await read(fixture()); + assert.equal(value.title, '复测通过 · 已验证指令文本'); + assert.equal(value.original, 'before'); + assert.deepEqual(value.runs.map(r => [r.exit_code, r.log.text]), [[1, 'baseline'], [0, 'candidate']]); + assert.equal(value.adoption, '尚无采用回执'); +}); + +test('a v1 text pass requires every baseline to fail and every candidate to pass', async () => { + for (const [ref, exit_code, judge_result] of [ + ['r1', 0, 'met'], ['r1', 0, 'not_met'], ['r1', 1, 'unknown'], + ['r1', null, 'not_met'], ['r2', 1, 'met'], ['r2', null, 'met'], + ]) { + const f = fixture(); + const run = f.data.get(task + '/runs/' + ref); + f.report[run.phase + '_run_refs'].push('retry'); + f.data.set(task + '/runs/retry', {...run, run_ref: 'retry', exit_code, judge_result}); + const value = await read(f); + assert.equal(value.title, '复测报告暂不可用'); + assert.ok(value.error); + assert.equal(value.report, undefined); + } +}); + +test('two successful v1 runs support not_reproduced but cannot support retest_passed', async () => { + const f = fixture(); + Object.assign(f.data.get(task + '/runs/r1'), {exit_code: 0, judge_result: 'met'}); + assert.ok((await read(f)).error); + f.view.status = f.report.verdict = 'not_reproduced'; + f.report.reason_code = 'baseline_passed'; + const value = await read(f); + assert.equal(value.title, '原版本未复现问题'); + assert.equal(value.reason, '原版本已满足要求'); +}); + +test('the local worker report is tied to the B snapshot and reads both embedded runs', async () => { + const ref = 'comparison-one', path = 'projects/project-a/evolution/evo-one'; + const local = {evolution_job: job, snapshot_sha256: result.snapshot_sha256, candidate_sha256: result.candidate_sha256}; + const run = {scenario_id: 'python-related-tests', source_unchanged: true, timed_out: false, command: ['python', 'check.py']}; + const report = {comparison_ref: ref, scenario_id: run.scenario_id, candidate_id: 'c', job, + snapshot_sha256: local.snapshot_sha256, candidate_sha256: local.candidate_sha256, status: 'retest_passed', + comparable: true, baseline: {...run, phase: 'baseline', run_ref: 'r1', exit_code: 1, stderr: 'rule missing'}, + candidate: {...run, phase: 'candidate', run_ref: 'r2', exit_code: 0, stderr: 'OK'}}; + const api = async (url, value) => { + assert.equal(value, undefined); + if (url === path) return {job, candidate_id: 'c', comparison_ref: ref, status: report.status}; + assert.equal(url, path + '/comparisons/' + ref); + return report; + }; + const load = () => read({api}, {result: local}); + const success = await load(); + assert.equal(success.title, '复测通过 · 已验证指令文本'); + assert.deepEqual(success.runs.map(row => row.log.text), ['rule missing', 'OK']); + report.candidate.exit_code = 1; + assert.ok((await load()).error); + report.status = 'retest_failed'; + assert.equal((await load()).title, '候选复测失败'); + report.snapshot_sha256 = 'other'; + assert.ok((await load()).error); +}); + +test('requires matching job, snapshot, candidate, run and artifact identities', async () => { + for (const change of [ + f => { f.view.job = {...job, project_id: 'b'}; }, + f => { f.data.get(task + '/candidates/cand').candidate_sha256 = 'wrong'; }, + f => { f.report.job = {...job, job_id: 'another'}; }, + f => { f.data.get(task + '/runs/r1').phase = 'candidate'; }, + f => { f.data.get(task + '/runs/r1').snapshot_sha256 = 'wrong'; }, + f => { f.data.get(scope + '/artifacts/log0?kind=run_log').ref = 'other'; }, + f => { f.report.candidate_run_refs = []; }, + f => { f.view.status = 'failed'; }, + f => { f.view.reason_code = 'execution_timeout'; }, + f => { f.data.get(task + '/runs/r2').reason_code = 'execution_timeout'; }, + f => { f.data.get(task + '/runs/r2').command = ['another']; }, + ]) { + const f = fixture(); change(f); + const value = await read(f); assert.ok(value.error); assert.equal(value.report, undefined); + } + let calls = 0; + const foreign = await read(fixture(), {project: 'b', api: () => calls++}); + assert.equal(calls, 0); assert.equal(foreign.job, null); +}); + +test('shows verdicts, the actual reason and the scoped version receipt independently', async () => { + for (const [status, code, title] of [ + ['not_reproduced', 'baseline_passed', '原版本未复现问题'], ['retest_failed', 'candidate_failed', '候选复测失败'], + ['not_comparable', 'scenario_mismatch', '两次运行不可比'], ['not_comparable', 'execution_timeout', '运行超时'], + ['not_comparable', 'future_reason', '两次运行不可比'] + ]) { + const f = fixture(); + f.report.verdict = f.view.status = status; f.report.reason_code = code; + const value = await read(f); assert.equal(value.title, title); assert.ok(value.reason); + } + const f = fixture(); + f.view.version_receipt_ref = 'v1'; + const receipt = {receipt_ref: 'v1', operation: {job}, candidate_id: 'cand', candidate_sha256: result.candidate_sha256, + entries: [{target_id: 'project-instructions', status: 'applied'}]}; + f.data.set(task + '/receipts/v1', receipt); + assert.equal((await read(f)).adoption, '已采用'); + receipt.operation.job = {...job, job_id: 'other'}; + assert.ok((await read(f)).error); +}); + +test('resumes C pages independently of proposal SSE and re-reads the completed job', async () => { + const f = fixture(), cursors = [], b = [], seen = []; + let reads = 0; + const controller = create({read: async () => ({proposal: ++reads === 1 ? {status: 'checking'} : {status: 'ready', result}}), + updates: async (_p, _f, after) => { b.push(after); return 'id: 19\n\n'; }, + reviewApi: async (path, value) => { + if (path === task && cursors.length < 3) return {job, status: 'collecting'}; + if (path.includes('/events?')) { + cursors.push(path.split('=').pop()); + if (cursors.length === 2) throw Error('disconnected'); + const seq = cursors.length; return {events: [{seq, job}], next_after: seq}; + } + return f.api(path, value); + }, render: state => seen.push(state), reviewWait: async () => {}}); + await controller.show(job.project_id, 'feedback'); + assert.deepEqual(b, [0]); assert.deepEqual(cursors, ['0', '1', '1']); + assert.ok(seen.some(s => s.review?.title === '等待复测报告')); + assert.equal(seen.at(-1).review.report.report_ref, 'report'); +}); + +test('an open C question sends the scoped reply and retries a lost acknowledgement using the same key', async () => { + const f = fixture(), writes = [], seen = []; + const proposal = {status: 'ready', result}; + let answered = false; + const controller = create({read: async () => ({proposal}), render: state => seen.push(state), + reviewApi: async (path, value) => { + if (path === task && !answered) return {job, status: 'needs_input', question_id: 'q'}; + if (path.endsWith('/questions/q')) return {question_id: 'q', prompt: '哪项测试?', open: true}; + if (path.endsWith('/reply')) { + writes.push(value); + if (writes.length === 1) throw Error('lost reply'); + answered = true; return f.view; + } + return f.api(path, value); + }}); + await controller.show(job.project_id, 'feedback'); + assert.equal(seen.at(-1).review.question.prompt, '哪项测试?'); + for (let i = 0; i < 2; i++) await controller.answerReview(job.project_id, 'feedback', proposal, 'q', 'pytest'); + assert.deepEqual(writes[0], writes[1]); assert.ok(writes[0].idempotency_key); + assert.equal(seen.at(-1).review.job.job_id, job.job_id); +}); + +test('switching projects or closing during a report read suppresses the late response', async () => { + for (const change of ['switch', 'close']) { + let release, began; + const reading = new Promise(resolve => { began = resolve; }); + const seen = [], f = fixture(); + const controller = create({read: async project => ({proposal: project === 'b' ? null : {status: 'ready', result}}), + render: state => seen.push(state), reviewApi: async (path, value, {signal}) => { + if (path.endsWith('/reports/report')) { + began(signal); await new Promise(resolve => { release = resolve; }); + } + return f.api(path, value); + }}); + const showing = controller.show(job.project_id, 'feedback'), signal = await reading; + if (change === 'switch') await controller.show('b', 'feedback-b'); else controller.stop(); + const count = seen.length; + release(); await showing; + assert.equal(signal.aborted, true); assert.equal(seen.length, count); + } +}); diff --git a/console/static/personal.css b/console/static/personal.css index fbf17890..63a79a41 100644 --- a/console/static/personal.css +++ b/console/static/personal.css @@ -239,6 +239,26 @@ body[data-mode="details"][data-view="proposal"] .composer { display: none; } .proposal-approval { margin-top: 14px; text-align: center; } .proposal-approval button { width: 100%; white-space: normal; } .proposal-approval p { margin-bottom: 0; } +.review-report { border-top: 1px solid var(--hg-alias-border-l2); margin: 16px 0; padding-top: 14px; } +.review-report h3, .review-report h4 { margin: 0; } +.review-report h3 { font-size: 15px; } +.review-report .badge { color: var(--hg-alias-brand-text); font-size: 11px; } +.review-report h4 { font-size: 13px; } +.review-outcome { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline; margin: 6px 0; } +.review-outcome strong { color: var(--hg-alias-brand-text); } +.review-outcome span, .review-report details, .review-report p { font-size: 12px; } +.review-report details { margin: 8px 0; } +.review-report summary { cursor: pointer; } +.review-report pre { + white-space: pre-wrap; overflow-wrap: anywhere; max-height: 14rem; overflow: auto; + margin: 6px 0; padding: 7px 9px; background: var(--hg-alias-bg-layer-2); + border-radius: 6px; font: 12px/1.55 ui-monospace, monospace; +} +#review-runs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 205px), 1fr)); gap: 12px; } +#review-runs section { min-width: 0; padding-top: 7px; } +#review-runs small { display: block; margin-top: 6px; color: var(--hg-alias-label-primary); } +#review-runs pre { margin-top: 2px; } +.review-report p { margin: 4px 0; overflow-wrap: anywhere; } @media (max-width: 460px) { body:not(.desktop) { padding: 12px; } } diff --git a/console/static/personal.html b/console/static/personal.html index 8aa85eb6..24741e84 100644 --- a/console/static/personal.html +++ b/console/static/personal.html @@ -1,5 +1,5 @@ -HarnessGrad · 个人持续进化 +HarnessGrad · 个人持续进化
@@ -94,6 +94,15 @@

把这次反馈,变成下次的习惯< 查看修改前后的差异

           
+