app.js 29.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
// U-008: hash-based client-side router (no History API / server catch-all
// needed). U-022 adds the first real page, #/setup (v_project_setup, 02-V
// §2.1); U-023 adds #/goals/new and #/bugs/new; U-025 adds the real #/
// (v_dashboard), #/tasks (v_task_board), #/tasks/:task_id (v_task_detail).

// 02-V's console has no multi-project switcher UI (decision 2), but
// c_task_create/c_bug_report_create both require project_id (03-C §3.1;
// §3.1.1 doesn't list it, but needs it too -- see bug_record.py's
// create_bug_report docstring). Until v_dashboard carries "current project"
// state through some richer UI, the id picked/created in v_project_setup is
// stashed here and read back by the pages that need it.
const CURRENT_PROJECT_KEY = "graphlemon_project_id";
function getCurrentProjectId() {
  return localStorage.getItem(CURRENT_PROJECT_KEY);
}
function setCurrentProjectId(projectId) {
  localStorage.setItem(CURRENT_PROJECT_KEY, projectId);
}

function escapeHtml(text) {
  const div = document.createElement("div");
  div.textContent = text == null ? "" : String(text);
  return div.innerHTML;
}

// c_ws_subscribe (03-C §3.14, U-024): opens a live event feed for a project
// (optionally scoped to one task_id) and auto-reconnects on drop -- 02-V
// §2.2's "实时连接已断开,正在重连" exception state. REQ-12's deeper
// reconnect-catch-up semantics are U-024.5's job (03-C §3.14 itself routes
// that through REST snapshots, not WS replay); this only re-opens the
// socket and reports connection status back to the caller.
function connectEventSocket(projectId, taskId, { onEvent, onStatusChange }) {
  const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
  let url = wsProtocol + "//" + window.location.host + "/api/ws/projects/" + encodeURIComponent(projectId);
  if (taskId) url += "?task_id=" + encodeURIComponent(taskId);

  let closedByCaller = false;
  let socket = null;

  function open() {
    socket = new WebSocket(url);
    socket.onopen = () => onStatusChange("connected");
    socket.onmessage = (event) => onEvent(JSON.parse(event.data));
    socket.onclose = () => {
      if (closedByCaller) return;
      onStatusChange("disconnected");
      setTimeout(open, 2000);
    };
    socket.onerror = () => socket.close();
  }
  open();

  return {
    close: () => {
      closedByCaller = true;
      if (socket) socket.close();
    },
  };
}

const routes = {
  "#/": { render: renderDashboard, mount: mountDashboard },
  "#/tasks": { render: renderTaskBoard, mount: mountTaskBoard },
  "#/settings": { render: () => "<h1>Settings</h1><p>placeholder -- real content is PH3 (U-030)</p>" },
  "#/setup": { render: renderProjectSetup, mount: mountProjectSetup },
  "#/goals/new": { render: renderGoalComposer, mount: mountGoalComposer },
  "#/bugs/new": { render: renderBugFeedback, mount: mountBugFeedback },
};

// #/tasks/:task_id (v_task_detail) is the one dynamic route -- not worth a
// full path-matching router for a single pattern.
const TASK_DETAIL_RE = /^#\/tasks\/([^/]+)$/;

let currentRouteCleanup = null;
function registerRouteCleanup(fn) {
  currentRouteCleanup = fn;
}

function render() {
  if (currentRouteCleanup) {
    currentRouteCleanup();
    currentRouteCleanup = null;
  }

  const hash = window.location.hash || "#/";
  let route = routes[hash];
  let routeArgs = [];
  if (!route) {
    const match = hash.match(TASK_DETAIL_RE);
    if (match) {
      route = { render: renderTaskDetail, mount: mountTaskDetail };
      routeArgs = [match[1]];
    }
  }
  if (!route) route = { render: () => "<h1>Not found</h1><p>" + hash + "</p>" };

  document.getElementById("app").innerHTML = route.render(...routeArgs);
  if (route.mount) route.mount(...routeArgs);

  for (const a of document.querySelectorAll("#nav a")) {
    a.classList.toggle("active", a.getAttribute("href") === hash);
  }
}

window.addEventListener("hashchange", render);
window.addEventListener("DOMContentLoaded", render);

// ---- v_project_setup (02-V §2.1): create/switch project ----

function renderProjectSetup() {
  return `
    <div class="top-back"><a href="#/">← 返回仪表盘</a></div>
    <div class="page">
      <h1>创建 / 切换项目</h1>
      <div class="page-sub">选择一个本地文件夹作为目标项目的代码空间</div>
      <div class="panel">
        <div id="setup_error" class="error-banner" style="display:none;"></div>
        <div class="field">
          <label>目标文件夹(folder_path)</label>
          <input type="text" id="folder_path" readonly value="">
          <div class="hint" id="folder_path_hint">点击"选择文件夹"会由后端代为弹出系统原生对话框,不支持手动输入路径(除非返回 DIALOG_UNAVAILABLE)</div>
        </div>
        <button class="btn" id="btn_pick_folder" type="button">📁 选择文件夹</button>
        <div class="field" style="margin-top:20px;">
          <label>项目名称(project_name,非必填)</label>
          <input type="text" id="project_name" placeholder="留空则取文件夹名">
        </div>
        <div class="btn-row">
          <button class="btn btn-primary" id="btn_create" type="button">创建项目</button>
        </div>
        <div class="confirm-banner" id="confirm_banner" style="display:none;">
          该文件夹还不是 Git 仓库,是否代为初始化(<code>git init</code>)?确认前不写入任何文件。
          <div class="btn-row" style="margin-top:10px;">
            <button class="btn" id="btn_cancel_init" type="button">取消</button>
            <button class="btn btn-primary" id="btn_confirm_init" type="button">确认初始化并创建项目</button>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountProjectSetup() {
  const folderInput = document.getElementById("folder_path");
  const folderHint = document.getElementById("folder_path_hint");
  const nameInput = document.getElementById("project_name");
  const errorBox = document.getElementById("setup_error");
  const confirmBanner = document.getElementById("confirm_banner");

  function showError(message) {
    errorBox.textContent = message;
    errorBox.style.display = "block";
  }
  function clearError() {
    errorBox.style.display = "none";
  }

  document.getElementById("btn_pick_folder").addEventListener("click", async () => {
    clearError();
    const resp = await fetch("/api/system/pick-folder", { method: "POST", body: "{}" });
    const body = await resp.json();
    if (resp.status === 422 && body.error === "DIALOG_UNAVAILABLE") {
      folderInput.removeAttribute("readonly");
      folderHint.textContent = "当前环境不支持弹窗选择,请手动输入路径";
      return;
    }
    if (body.selected_path) {
      folderInput.value = body.selected_path;
    }
    // user canceled the native dialog -> folder_path stays as it was (02-V §2.1)
  });

  async function createProject(initGitIfMissing) {
    clearError();
    confirmBanner.style.display = "none";
    const folderPath = folderInput.value.trim();
    if (!folderPath) {
      showError("请先选择目标文件夹");
      return;
    }
    const resp = await fetch("/api/projects", {
      method: "POST",
      body: JSON.stringify({
        target_folder_path: folderPath,
        name: nameInput.value.trim() || undefined,
        init_git_if_missing: initGitIfMissing,
      }),
    });
    const body = await resp.json();
    if (resp.status === 200) {
      setCurrentProjectId(body.project_id);
      window.location.hash = "#/";
      return;
    }
    if (body.error === "GIT_INIT_DECLINED") {
      confirmBanner.style.display = "block";
      return;
    }
    showError(body.error + (body.detail ? ":" + body.detail : ""));
  }

  document.getElementById("btn_create").addEventListener("click", () => createProject(false));
  document.getElementById("btn_confirm_init").addEventListener("click", () => createProject(true));
  document.getElementById("btn_cancel_init").addEventListener("click", () => {
    confirmBanner.style.display = "none";
  });
}

// ---- shared: pages that need a "current project" to already exist ----

function renderNoProjectSelected() {
  return `
    <div class="page">
      <div class="error-banner" style="display:block;">
        还没有选择项目。请先<a href="#/setup">创建或切换项目</a>。
      </div>
    </div>
  `;
}

// ---- v_goal_composer (02-V §2.3): propose a new goal ----

const GOAL_TEXT_MAX_LEN = 4000;

function renderGoalComposer() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="top-back"><a href="#/">← 返回仪表盘</a></div>
    <div class="page">
      <h1>提出新目标</h1>
      <div class="page-sub">用自然语言描述你想让 graphlemon 完成的目标</div>
      <div class="panel">
        <div id="goal_error" class="error-banner" style="display:none;"></div>
        <div class="field" id="goal_form">
          <label>目标描述(goal_text,必填,最长 ${GOAL_TEXT_MAX_LEN} 字)</label>
          <textarea id="goal_text" rows="6" maxlength="${GOAL_TEXT_MAX_LEN}"></textarea>
          <div class="btn-row">
            <button class="btn btn-primary" id="btn_submit_goal" type="button">创建任务</button>
          </div>
        </div>
        <div class="confirm-banner" id="goal_confirm_banner" style="display:none;">
          <div id="goal_confirm_summary"></div>
          <div class="btn-row" style="margin-top:10px;">
            <button class="btn" id="btn_edit_goal" type="button">返回编辑</button>
            <button class="btn btn-primary" id="btn_confirm_goal" type="button">确认创建</button>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountGoalComposer() {
  if (!getCurrentProjectId()) return;
  const textArea = document.getElementById("goal_text");
  const errorBox = document.getElementById("goal_error");
  const form = document.getElementById("goal_form");
  const confirmBanner = document.getElementById("goal_confirm_banner");
  const confirmSummary = document.getElementById("goal_confirm_summary");

  document.getElementById("btn_submit_goal").addEventListener("click", () => {
    errorBox.style.display = "none";
    const goalText = textArea.value.trim();
    if (!goalText) {
      errorBox.textContent = "目标描述不能为空";
      errorBox.style.display = "block";
      return;
    }
    confirmSummary.textContent = "即将创建任务:" + goalText;
    form.style.display = "none";
    confirmBanner.style.display = "block";
  });

  document.getElementById("btn_edit_goal").addEventListener("click", () => {
    confirmBanner.style.display = "none";
    form.style.display = "block";
  });

  document.getElementById("btn_confirm_goal").addEventListener("click", async () => {
    const resp = await fetch("/api/tasks", {
      method: "POST",
      body: JSON.stringify({
        project_id: getCurrentProjectId(),
        goal_text: textArea.value.trim(),
        task_type: "goal",
        created_via: "human_console",
      }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      confirmBanner.style.display = "none";
      form.style.display = "block";
      errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorBox.style.display = "block";
      return;
    }
    // 02-V §2.3: 成功跳转 v_task_detail
    window.location.hash = "#/tasks/" + body.task_id;
  });
}

// ---- v_bug_feedback (02-V §2.4): report a bug ----

function renderBugFeedback() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="top-back"><a href="#/">← 返回仪表盘</a></div>
    <div class="page">
      <h1>反馈 Bug</h1>
      <div class="page-sub">人工反馈,与 Validator 自动生成的 bug_record 复用同一张表(source=human)</div>
      <div class="panel">
        <div id="bug_error" class="error-banner" style="display:none;"></div>
        <div id="bug_success" class="success-banner" style="display:none;"></div>
        <div id="bug_form">
          <div class="field">
            <label>问题描述(description,必填)</label>
            <textarea id="bug_description" rows="4"></textarea>
          </div>
          <div class="field">
            <label>复现步骤(repro_steps,非必填)</label>
            <textarea id="bug_repro_steps" rows="3"></textarea>
          </div>
          <div class="field">
            <label>关联任务(related_task_id,非必填)</label>
            <select id="bug_related_task_id">
              <option value="">— 不关联,视为新发现的独立问题 —</option>
            </select>
          </div>
          <div class="btn-row">
            <button class="btn btn-primary" id="btn_submit_bug" type="button">提交反馈</button>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountBugFeedback() {
  if (!getCurrentProjectId()) return;
  const descriptionArea = document.getElementById("bug_description");
  const reproStepsArea = document.getElementById("bug_repro_steps");
  const relatedTaskIdSelect = document.getElementById("bug_related_task_id");
  const errorBox = document.getElementById("bug_error");
  const successBox = document.getElementById("bug_success");
  const form = document.getElementById("bug_form");

  fetch("/api/tasks?project_id=" + encodeURIComponent(getCurrentProjectId()))
    .then((resp) => resp.json())
    .then((tasks) => {
      for (const task of tasks) {
        const option = document.createElement("option");
        option.value = task.task_id;
        option.textContent = task.goal_text.slice(0, 40) + " (" + task.task_id.slice(0, 8) + ")";
        relatedTaskIdSelect.appendChild(option);
      }
    });

  document.getElementById("btn_submit_bug").addEventListener("click", async () => {
    errorBox.style.display = "none";
    const description = descriptionArea.value.trim();
    if (!description) {
      errorBox.textContent = "问题描述不能为空";
      errorBox.style.display = "block";
      return;
    }
    const relatedTaskId = relatedTaskIdSelect.value || undefined;
    const resp = await fetch("/api/bug-reports", {
      method: "POST",
      body: JSON.stringify({
        project_id: getCurrentProjectId(),
        description: description,
        repro_steps: reproStepsArea.value.trim() || undefined,
        related_task_id: relatedTaskId,
      }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorBox.style.display = "block";
      return;
    }
    // 02-V §2.4: 跳转到该 bug 的详情视图,MVP 复用 v_task_detail 的 bug 展示区
    // -- only possible when the report was tied to a task; otherwise there's
    // no task detail page to land on, so show the confirmation inline.
    if (relatedTaskId) {
      window.location.hash = "#/tasks/" + relatedTaskId;
      return;
    }
    form.style.display = "none";
    successBox.innerHTML = "已提交,Validator 将进行归因确认(bug <code>" + body.bug_id + "</code>)。"
      + '<a href="#/">返回仪表盘</a>';
    successBox.style.display = "block";
  });
}

// ---- v_dashboard (02-V §2.2): real-time landing page ----

const ORG_NODE_ORDER = ["planner", "coder", "validator"];

function renderDashboard() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <h1>仪表盘</h1>
      <div id="quota_info_banner" class="info-banner" style="display:none;"></div>
      <div id="ws_disconnected_banner" class="error-banner" style="display:none;">实时连接已断开,正在重连…</div>
      <div class="grid">
        <div>
          <div class="panel">
            <h2>Org Graph 三节点状态</h2>
            <div class="org-strip" id="org_strip"></div>
          </div>
          <div class="panel">
            <h2>当前任务概要</h2>
            <div class="task-summary" id="task_summary"></div>
          </div>
          <div class="actions">
            <a class="btn btn-primary" href="#/goals/new">+ 提出新目标</a>
            <a class="btn" href="#/bugs/new">反馈 Bug</a>
          </div>
        </div>
        <div>
          <div class="panel">
            <h2>预算用量</h2>
            <div id="budget_summary"></div>
          </div>
          <div class="panel">
            <h2>最近事件</h2>
            <div id="event_timeline"></div>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountDashboard() {
  const projectId = getCurrentProjectId();
  if (!projectId) return;

  const orgStrip = document.getElementById("org_strip");
  const taskSummary = document.getElementById("task_summary");
  const budgetSummary = document.getElementById("budget_summary");
  const eventTimeline = document.getElementById("event_timeline");
  const quotaBanner = document.getElementById("quota_info_banner");
  const wsBanner = document.getElementById("ws_disconnected_banner");
  const recentEvents = [];

  function renderOrgStrip(activeOrgNode, runStatusByOrgNode) {
    orgStrip.innerHTML = ORG_NODE_ORDER.map((node, i) => {
      const isActive = activeOrgNode === node;
      const runStatus = runStatusByOrgNode[node];
      const hint = isActive ? "当前节点" : runStatus === "done" ? "已完成" : runStatus || "未开始";
      const arrow = i < ORG_NODE_ORDER.length - 1 ? '<div class="org-arrow">→</div>' : "";
      return '<div class="org-node' + (isActive ? " active" : "") + '"><div class="role">'
        + node + '</div><div class="hint">' + escapeHtml(hint) + "</div></div>" + arrow;
    }).join("");
  }

  async function refreshTasksAndOrgGraph() {
    const resp = await fetch("/api/tasks?project_id=" + encodeURIComponent(projectId));
    const tasks = await resp.json();
    const active = tasks.find((t) => t.status !== "done") || tasks[0];
    if (!active) {
      orgStrip.innerHTML = '<div class="hint">暂无运行中任务</div>';
      taskSummary.innerHTML = '<div class="hint">暂无运行中任务 · <a href="#/goals/new">提出第一个目标 →</a></div>';
      quotaBanner.style.display = "none";
      return;
    }
    taskSummary.innerHTML = (
      '<div class="row"><span>Goal</span><span>' + escapeHtml(active.goal_text) + "</span></div>"
      + '<div class="row"><span>Loop Round</span><span>' + active.loop_round + "</span></div>"
      + '<div class="row"><span>Status</span><span><a href="#/tasks/' + active.task_id + '">'
      + escapeHtml(active.status) + "</a></span></div>"
    );

    const detailResp = await fetch("/api/tasks/" + active.task_id);
    const detail = await detailResp.json();
    const runStatusByOrgNode = {};
    let waitingNode = null;
    for (const run of detail.work_graph_runs) {
      runStatusByOrgNode[run.org_node] = run.status;
      if (!waitingNode) waitingNode = run.nodes.find((n) => n.status === "waiting_for_quota");
    }
    renderOrgStrip(active.assigned_org_node, runStatusByOrgNode);

    if (waitingNode) {
      quotaBanner.innerHTML = "🕐 有任务正在等待 Claude Code 额度恢复 · "
        + '<a href="#/tasks/' + active.task_id + '">查看详情</a>';
      quotaBanner.style.display = "flex";
    } else {
      quotaBanner.style.display = "none";
    }
  }

  async function refreshBudget() {
    const resp = await fetch("/api/settings/budget");
    const configs = await resp.json();
    if (configs.length === 0) {
      budgetSummary.innerHTML = '<div class="hint">预算护栏未配置</div>';
      return;
    }
    const c = configs[0];
    const pct = c.limit_value > 0 ? Math.min(100, Math.round((c.current_usage / c.limit_value) * 100)) : 0;
    budgetSummary.innerHTML = (
      '<div style="font-size:13px;">' + c.current_usage.toLocaleString() + " / "
      + c.limit_value.toLocaleString() + " " + escapeHtml(c.limit_type) + "</div>"
      + '<div class="progress"><div class="fill" style="width:' + pct + '%"></div></div>'
    );
  }

  function prependEvent(event) {
    recentEvents.unshift(event);
    recentEvents.length = Math.min(recentEvents.length, 20);
    eventTimeline.innerHTML = recentEvents.map((e) =>
      '<div class="event-item"><div>' + escapeHtml(e.event_type) + '</div><div class="t">'
      + escapeHtml(e.created_at || "") + "</div></div>"
    ).join("") || '<div class="hint">暂无事件</div>';
  }

  refreshTasksAndOrgGraph();
  refreshBudget();
  eventTimeline.innerHTML = '<div class="hint">暂无事件</div>';

  const socket = connectEventSocket(projectId, null, {
    onEvent: (event) => {
      prependEvent(event);
      refreshTasksAndOrgGraph();
      if (event.event_type === "budget_updated") refreshBudget();
    },
    onStatusChange: (status) => {
      wsBanner.style.display = status === "disconnected" ? "block" : "none";
    },
  });
  registerRouteCleanup(() => socket.close());
}

// ---- v_task_board (02-V §2.5): task list with filters ----

const TASK_STATUSES = [
  "queued", "planning_brd_prd_sdd", "planning_failed", "coding", "coding_failed",
  "validating", "routed_fast_lane", "routed_full_replan", "blocked_pending_human", "done",
];

function renderTaskBoard() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <h1>任务看板</h1>
      <div class="filters">
        <input type="text" id="tb_keyword" placeholder="搜索 goal_text" maxlength="128">
        <select id="tb_status">
          <option value="">全部状态</option>
          ${TASK_STATUSES.map((s) => '<option value="' + s + '">' + s + "</option>").join("")}
        </select>
        <select id="tb_org_node">
          <option value="">全部 Org 节点</option>
          <option value="planner">planner</option>
          <option value="coder">coder</option>
          <option value="validator">validator</option>
        </select>
      </div>
      <table class="data-table">
        <thead>
          <tr><th>task_id</th><th>goal_text</th><th>status</th><th>assigned_org_node</th><th>loop_round</th><th>updated_at</th></tr>
        </thead>
        <tbody id="tb_rows"></tbody>
      </table>
    </div>
  `;
}

function mountTaskBoard() {
  const projectId = getCurrentProjectId();
  if (!projectId) return;
  const rowsEl = document.getElementById("tb_rows");
  const keywordEl = document.getElementById("tb_keyword");
  const statusEl = document.getElementById("tb_status");
  const orgNodeEl = document.getElementById("tb_org_node");

  async function refresh() {
    const params = new URLSearchParams({ project_id: projectId });
    if (keywordEl.value.trim()) params.set("keyword", keywordEl.value.trim());
    if (statusEl.value) params.set("status", statusEl.value);
    if (orgNodeEl.value) params.set("org_node", orgNodeEl.value);
    const resp = await fetch("/api/tasks?" + params.toString());
    const tasks = await resp.json();
    if (tasks.length === 0) {
      rowsEl.innerHTML = '<tr><td colspan="6">暂无任务</td></tr>';
      return;
    }
    rowsEl.innerHTML = tasks.map((t) => (
      '<tr data-task-id="' + t.task_id + '">'
      + "<td>" + t.task_id + "</td>"
      + "<td>" + escapeHtml(t.goal_text) + "</td>"
      + '<td><span class="badge ' + t.status + '">' + t.status + "</span></td>"
      + "<td>" + t.assigned_org_node + "</td>"
      + "<td>" + t.loop_round + "</td>"
      + "<td>" + escapeHtml(t.updated_at) + "</td>"
      + "</tr>"
    )).join("");
    for (const row of rowsEl.querySelectorAll("tr[data-task-id]")) {
      row.addEventListener("click", () => {
        window.location.hash = "#/tasks/" + row.dataset.taskId;
      });
    }
  }

  keywordEl.addEventListener("input", refresh);
  statusEl.addEventListener("change", refresh);
  orgNodeEl.addEventListener("change", refresh);
  refresh();

  const socket = connectEventSocket(projectId, null, {
    onEvent: (event) => {
      if (event.event_type === "task_status_changed") refresh();
    },
    onStatusChange: () => {},
  });
  registerRouteCleanup(() => socket.close());
}

// ---- v_task_detail (02-V §2.6): task detail / process inspection ----
// Embeds a to-do tree built from graph_manifest (01-M 1.3's "补充说明") --
// the DAG-layout v_graph_visualizer and the raw-log v_log_viewer are each
// separate Units (U-026/U-027) and show as clearly-labeled placeholders
// here until they land, rather than faking their content.

function renderTaskDetail(taskId) {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <div class="breadcrumb"><a href="#/tasks">任务</a> / ${taskId}</div>
      <div id="td_content"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountTaskDetail(taskId) {
  const projectId = getCurrentProjectId();
  if (!projectId) return;
  const content = document.getElementById("td_content");

  function renderTodoTree(run) {
    if (!run.graph_manifest) return "";
    const nodesById = {};
    for (const n of run.nodes) nodesById[n.node_id] = n;
    const items = run.graph_manifest.nodes.map((gn) => {
      const wn = nodesById[gn.node_id];
      const status = wn ? wn.status : "pending";
      const detail = wn ? (
        '<div class="todo-detail" id="todo-detail-' + wn.node_exec_id + '">'
        + "retry_count: " + wn.retry_count
        + (wn.reflection_notes ? "<br>reflection_notes: " + escapeHtml(wn.reflection_notes) : "")
        + '<div class="hint">原始日志查看器(v_log_viewer)随 U-027 补上</div>'
        + "</div>"
      ) : "";
      return (
        '<li class="status-' + status + '">'
        + '<div class="todo-row" data-node-exec-id="' + (wn ? wn.node_exec_id : "") + '">'
        + '<span class="dot"></span>'
        + '<span class="todo-id">to-do: ' + escapeHtml(gn.node_id) + "</span>"
        + '<span class="todo-status">' + status + (wn ? " · node_exec_id=" + wn.node_exec_id : "") + "</span>"
        + "</div>" + detail + "</li>"
      );
    }).join("");
    return (
      '<div class="panel"><h2>' + run.org_node + " Work Graph 的 to-do 树(run_id=" + run.run_id + ")</h2>"
      + '<ul class="todo-tree">' + items + "</ul>"
      + '<div class="see-more">按执行层级排布的 DAG 视图(v_graph_visualizer)随 U-026 补上</div>'
      + "</div>"
    );
  }

  function renderDetail(task) {
    const activeSet = new Set([task.assigned_org_node]);
    for (const run of task.work_graph_runs) {
      if (run.status !== "done" && run.status !== "failed") activeSet.add(run.org_node);
    }
    const orgStripHtml = ORG_NODE_ORDER.map((node, i) => {
      const arrow = i < ORG_NODE_ORDER.length - 1 ? '<div class="org-arrow">→</div>' : "";
      return '<div class="org-node' + (activeSet.has(node) ? " active" : "") + '">' + node + "</div>" + arrow;
    }).join("");

    const alertHtml = task.status !== "blocked_pending_human" ? "" : (
      '<div class="alert-banner">⚠ 已阻塞(' + escapeHtml(task.blocked_reason || "") + '),需要人工干预'
      + '<button class="btn btn-danger" id="btn_manual_resume" type="button">人工干预(manual_resume)</button></div>'
    );

    const todoTreesHtml = task.work_graph_runs.map(renderTodoTree).join("");

    const artifactsHtml = task.artifacts.length ? (
      '<ul class="simple-list">' + task.artifacts.map((a) =>
        "<li><span>" + escapeHtml(a.file_path) + "</span><span>"
        + escapeHtml(a.artifact_type) + " · " + escapeHtml(a.validation_status) + "</span></li>"
      ).join("") + "</ul>"
    ) : '<div class="hint">暂无 Artifact</div>';

    const bugsHtml = task.bug_records.length ? (
      '<ul class="simple-list">' + task.bug_records.map((b) =>
        "<li><span>" + escapeHtml(b.description) + "</span><span>"
        + escapeHtml(b.root_cause_category || "待归因") + " · " + escapeHtml(b.status) + "</span></li>"
      ).join("") + "</ul>"
    ) : '<div class="hint">暂无 Bug 记录</div>';

    content.innerHTML = (
      "<h1>" + escapeHtml(task.goal_text) + "</h1>"
      + alertHtml
      + '<div class="meta-row">'
      + "<div><b>STATUS</b>" + escapeHtml(task.status) + "</div>"
      + "<div><b>LOOP_ROUND</b>" + task.loop_round + "</div>"
      + "<div><b>ASSIGNED_ORG_NODE</b>" + task.assigned_org_node + "</div>"
      + "<div><b>CREATED_VIA</b>" + escapeHtml(task.created_via) + "</div>"
      + "</div>"
      + '<div class="panel"><h2>Org Graph</h2><div class="org-strip">' + orgStripHtml + "</div></div>"
      + todoTreesHtml
      + '<div class="panel"><h2>关联 Artifact</h2>' + artifactsHtml + "</div>"
      + '<div class="panel"><h2>关联 Bug 记录</h2>' + bugsHtml + "</div>"
      + '<div class="panel"><h2>原始执行日志</h2><div class="hint">v_log_viewer 随 U-027 补上</div></div>'
    );

    for (const row of content.querySelectorAll(".todo-row[data-node-exec-id]")) {
      row.addEventListener("click", () => {
        const nodeExecId = row.dataset.nodeExecId;
        if (!nodeExecId) return;
        const detail = document.getElementById("todo-detail-" + nodeExecId);
        if (detail) detail.classList.toggle("open");
      });
    }

    const resumeBtn = document.getElementById("btn_manual_resume");
    if (resumeBtn) {
      resumeBtn.addEventListener("click", async () => {
        resumeBtn.disabled = true;
        await fetch("/api/tasks/" + taskId + "/route", {
          method: "POST",
          body: JSON.stringify({ decided_route: "manual_resume" }),
        });
        refresh();
      });
    }
  }

  async function refresh() {
    const resp = await fetch("/api/tasks/" + taskId);
    if (resp.status === 404) {
      content.innerHTML = '<div class="error-banner" style="display:block;">任务不存在</div>';
      return;
    }
    renderDetail(await resp.json());
  }

  refresh();

  const socket = connectEventSocket(projectId, taskId, {
    onEvent: () => refresh(),
    onStatusChange: () => {},
  });
  registerRouteCleanup(() => socket.close());
}