fix: зависание UI — stderr deadlock + таймер анализа

3 исправления:
1. stderr=DEVNULL вместо PIPE — устраняет deadlock когда
   stderr буфер переполняется и proc.wait() зависает навечно
2. proc.wait() с timeout=5с + kill() при таймауте
3. Таймер на странице — показывает сколько идёт анализ (Xм Yс)

Также: fix cp437→utf-8 для кириллических имён в ZIP (batch.py)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-26 03:22:30 +10:00
co-authored by Claude Opus 4.6
parent 5549b5da97
commit 3c9f4b8f4f
2 changed files with 42 additions and 33 deletions
+25 -32
View File
@@ -266,6 +266,21 @@ The script must handle any file with the same general structure as the samples.
"""
def _read_result_files(job_dir: Path) -> dict:
"""Read batch_script.py and batch_summary.json from job dir."""
script_path = job_dir / "batch_script.py"
summary_path = job_dir / "batch_summary.json"
summary = {}
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
if script_path.exists():
return {"script": script_path.read_text(encoding="utf-8"), "summary": summary}
return {"script": "", "result": "Script not generated", "summary": summary}
async def run_claude_analysis(
job_dir: Path,
task_description: str,
@@ -317,7 +332,7 @@ async def run_claude_analysis(
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL, # don't capture stderr — prevents buffer deadlock
)
except FileNotFoundError:
yield {"type": "done", "script": "", "result": "Docker not found"}
@@ -349,43 +364,21 @@ async def run_claude_analysis(
elif etype == "result":
got_result = True
script_path = job_dir / "batch_script.py"
summary_path = job_dir / "batch_summary.json"
summary = {}
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
if script_path.exists():
script = script_path.read_text(encoding="utf-8")
yield {"type": "done", "script": script, "summary": summary}
else:
result_text = event.get("result", "")
yield {"type": "done", "script": "", "result": result_text, "summary": summary}
result_data = _read_result_files(job_dir)
yield {"type": "done", **result_data}
finally:
if proc.returncode is None:
proc.terminate()
await proc.wait()
try:
await asyncio.wait_for(proc.wait(), timeout=5)
except asyncio.TimeoutError:
proc.kill()
# If Claude exited without emitting a result event — check files directly
# Fallback: Claude exited without result event — check files on disk
if not got_result:
script_path = job_dir / "batch_script.py"
summary_path = job_dir / "batch_summary.json"
summary = {}
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
if script_path.exists():
script = script_path.read_text(encoding="utf-8")
yield {"type": "done", "script": script, "summary": summary}
else:
stderr = await proc.stderr.read()
err_msg = stderr.decode()[:500] if stderr else "Claude exited without generating script"
yield {"type": "done", "script": "", "result": f"Error: {err_msg}", "summary": summary}
result_data = _read_result_files(job_dir)
yield {"type": "done", **result_data}
def run_batch_v2(job_id: str, script: str, source_dir: str, target_file: str):
+17 -1
View File
@@ -60,7 +60,7 @@ pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; o
<div class="card hidden" id="step-analyze">
<label>2. Анализ Claude Code</label>
<div class="info-row" id="csv-info"></div>
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude анализирует файлы...</span></p>
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude анализирует файлы...</span> <span id="analyze-timer" style="color:var(--muted);font-size:.8rem"></span></p>
<div class="log" id="analyze-log"></div>
</div>
@@ -95,10 +95,23 @@ if (!token) window.location.href = '/';
const H = {'Authorization': 'Bearer ' + token};
let jobId = null;
let timerInterval = null;
let timerStart = 0;
function show(id) { document.getElementById(id).classList.remove('hidden'); }
function hide(id) { document.getElementById(id).classList.add('hidden'); }
function startTimer() {
timerStart = Date.now();
timerInterval = setInterval(() => {
const s = Math.floor((Date.now() - timerStart) / 1000);
const m = Math.floor(s / 60);
const sec = s % 60;
document.getElementById('analyze-timer').textContent = m > 0 ? m + 'м ' + sec + 'с' : sec + 'с';
}, 1000);
}
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
async function uploadFiles() {
const zipFile = document.getElementById('zip-file').files[0];
const targetFile = document.getElementById('target-file').files[0];
@@ -134,6 +147,7 @@ async function uploadFiles() {
async function startAnalysis() {
const log = document.getElementById('analyze-log');
log.textContent = '';
startTimer();
try {
const r = await fetch('/api/batch-v2/analyze/' + jobId, {method: 'POST', headers: H});
@@ -163,6 +177,7 @@ async function startAnalysis() {
log.scrollTop = log.scrollHeight;
} else if (eventType === 'done') {
document.getElementById('analyze-spinner').style.display = 'none';
stopTimer();
if (d.script) {
document.getElementById('analyze-status').textContent = 'Анализ завершён';
document.getElementById('script-code').textContent = d.script;
@@ -178,6 +193,7 @@ async function startAnalysis() {
}
} catch(e) {
document.getElementById('analyze-spinner').style.display = 'none';
stopTimer();
document.getElementById('analyze-status').textContent = 'Ошибка: ' + e.message;
document.getElementById('analyze-status').style.color = 'var(--accent)';
}