import React from "react";
import { displayTimeZone, fmtClock, fmtDate } from "./time";
import { LoadingTitle } from "./loading-indicator";
import { MarkdownBody } from "./markdown";
import { TraceView, codexTracePort } from "./trace";
import { errorMessage, requestJson as requestUniDeskJson } from "./unidesk-error";
import { UniDeskErrorBanner } from "./unidesk-error-banner";
import { useNotification } from "./notification-context";
import { UniDeskDialog } from "./dialog";

type AnyRecord = Record<string, any>;

const h = React.createElement;
const { useEffect, useMemo, useRef } = React;
const useState: any = React.useState;
const codexTranscriptChunkLimit = 120;
const codexInitialTaskLimit = 12;
const codexMoreTaskLimit = 48;
const queueErrorPreviewLength = 1200;

function isDocumentVisible(): boolean {
  return typeof document === "undefined" || document.visibilityState !== "hidden";
}

function errorText(error: unknown, fallback = "操作失败"): string {
  return errorMessage(error, fallback);
}


function fmtDuration(ms: any): string {
  const value = Number(ms);
  if (!Number.isFinite(value) || value < 0) return "--";
  const totalSeconds = Math.floor(value / 1000);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
  if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
  return `${seconds}s`;
}

function timestampMs(value: any): number | null {
  if (value === null || value === undefined || value === "") return null;
  const ms = value instanceof Date ? value.getTime() : new Date(value).getTime();
  return Number.isFinite(ms) ? ms : null;
}

function fmtRelativeAge(value: any, nowMs = Date.now()): string {
  const atMs = timestampMs(value);
  if (atMs === null) return "--";
  const totalSeconds = Math.max(0, Math.floor((nowMs - atMs) / 1000));
  if (totalSeconds < 1) return "刚刚";
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor((totalSeconds % 86400) / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  if (days > 0) return `${days}天${hours > 0 ? `${hours}小时` : ""}前`;
  if (hours > 0) return `${hours}小时${minutes > 0 ? `${minutes}分钟` : ""}前`;
  if (minutes > 0) return `${minutes}分钟${seconds}秒前`;
  return `${seconds}秒前`;
}

function latestTimestampValue(...values: any[]): string {
  let best = "";
  let bestMs = -Infinity;
  for (const value of values) {
    const text = String(value || "");
    if (text.length === 0) continue;
    const ms = timestampMs(value);
    if (ms !== null && ms >= bestMs) {
      best = text;
      bestMs = ms;
    } else if (best.length === 0) {
      best = text;
    }
  }
  return best;
}

function timestampIsAfter(left: any, right: any): boolean {
  const leftMs = timestampMs(left);
  if (leftMs === null) return false;
  const rightMs = timestampMs(right);
  return rightMs === null || leftMs > rightMs + 1;
}

function fmtPreciseMs(ms: any): string {
  const value = Number(ms);
  if (!Number.isFinite(value) || value < 0) return "--";
  if (value < 1000) return `${Math.round(value)}ms`;
  return `${(value / 1000).toFixed(value < 10_000 ? 2 : 1)}s`;
}

function shortText(value: any, max = 180): string {
  const text = String(value || "").replace(/\s+/gu, " ").trim();
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
}

async function requestJson(path: string, options: AnyRecord = {}): Promise<any> {
  return requestUniDeskJson(path, {
    strictJson: true,
    retryInvalidJson: 1,
    invalidJsonPrefix: "Code Queue 返回了无效 JSON",
    invalidJsonPreview: true,
    responsePreviewLength: queueErrorPreviewLength,
    ...options,
  });
}

function StatusBadge({ status, children, title }: AnyRecord) {
  const normalized = String(status || "unknown").toLowerCase();
  return h("span", { className: `status-badge ${normalized}`, title }, children || status || "unknown");
}

function Panel({ title, eyebrow, summary, actions, children, className, loading }: AnyRecord) {
  return h("section", { className: `panel ${className || ""}` },
    h("div", { className: "panel-head" },
      h("div", null,
        eyebrow ? h("p", { className: "panel-eyebrow" }, eyebrow) : null,
        h(LoadingTitle, { title, loading }),
        summary ? h("div", { className: "panel-summary" }, summary) : null,
      ),
      actions ? h("div", { className: "panel-actions" }, actions) : null,
    ),
    h("div", { className: "panel-body" }, children),
  );
}

function RawButton({ title, data, onOpen, testId }: AnyRecord) {
  return h("button", {
    type: "button",
    className: "ghost-btn",
    "data-testid": testId,
    onClick: () => onOpen(title, data),
  }, "查看原始JSON");
}

function EmptyState({ title, text }: AnyRecord) {
  return h("div", { className: "empty-state" }, h("strong", null, title), h("span", null, text));
}

function microserviceRuntime(service: any): AnyRecord {
  return service?.runtime && typeof service.runtime === "object" && !Array.isArray(service.runtime) ? service.runtime : {};
}

function microserviceBackend(service: any): AnyRecord {
  return service?.backend && typeof service.backend === "object" && !Array.isArray(service.backend) ? service.backend : {};
}

function codexApi(apiBaseUrl: string, path: string): string {
  return `${apiBaseUrl}/microservices/code-queue/proxy${path}`;
}

function oaCodeQueueEventsApi(apiBaseUrl: string): string {
  return `${apiBaseUrl}/microservices/oa-event-flow/proxy/api/events/stream?tags=${encodeURIComponent("service:code-queue")}`;
}

function codexNoCacheOptions(): AnyRecord {
  return { headers: { "cache-control": "no-cache", "x-unidesk-no-cache": "1" } };
}

function taskRows(data: any): any[] {
  return Array.isArray(data?.tasks) ? data.tasks : [];
}

function taskPagination(data: any): AnyRecord {
  return data?.pagination && typeof data.pagination === "object" && !Array.isArray(data.pagination) ? data.pagination : {};
}

function taskSortValue(task: any): number {
  const time = Date.parse(String(task?.updatedAt || task?.createdAt || ""));
  return Number.isFinite(time) ? time : 0;
}

function taskQueueOrderValue(task: any): number {
  const time = timestampMs(task?.queueEnteredAt) ?? timestampMs(task?.createdAt) ?? timestampMs(task?.updatedAt);
  return time ?? 0;
}

function compareTaskQueueOrder(left: any, right: any): number {
  const queueDelta = taskQueueOrderValue(left) - taskQueueOrderValue(right);
  if (queueDelta !== 0) return queueDelta;
  const createdDelta = (timestampMs(left?.createdAt) ?? 0) - (timestampMs(right?.createdAt) ?? 0);
  if (createdDelta !== 0) return createdDelta;
  return String(left?.id || "").localeCompare(String(right?.id || ""));
}

function mergeTaskRows(groups: any[][], activeTaskId = ""): any[] {
  const byId = new Map<string, any>();
  for (const group of groups) {
    for (const task of group) {
      const id = String(task?.id || "");
      if (id.length > 0 && !byId.has(id)) byId.set(id, task);
    }
  }
  return Array.from(byId.values()).sort((left, right) => {
    const rankDelta = taskListRank(left) - taskListRank(right);
    if (rankDelta !== 0) return rankDelta;
    const leftActive = String(left?.id || "") === activeTaskId ? 0 : 1;
    const rightActive = String(right?.id || "") === activeTaskId ? 0 : 1;
    if (leftActive !== rightActive) return leftActive - rightActive;
    return taskSortValue(right) - taskSortValue(left);
  });
}

function mergeTaskRowsPreferLatest(groups: any[][], activeTaskId = ""): any[] {
  const byId = new Map<string, any>();
  for (const group of groups) {
    for (const task of group) {
      const id = String(task?.id || "");
      if (id.length === 0) continue;
      byId.set(id, { ...(byId.get(id) || {}), ...task });
    }
  }
  return mergeTaskRows([Array.from(byId.values())], activeTaskId);
}

function activeTaskIds(queue: any): string[] {
  return Array.isArray(queue?.activeTaskIds) ? queue.activeTaskIds.map((id: any) => String(id || "")).filter(Boolean) : [String(queue?.activeTaskId || "")].filter(Boolean);
}

function stringArray(value: any): string[] {
  return Array.isArray(value) ? value.map((item: any) => String(item || "")).filter(Boolean) : [];
}

function compactIdList(value: any, limit = 3): string {
  const ids = stringArray(value);
  if (ids.length === 0) return "--";
  const visible = ids.slice(0, limit).join(" / ");
  return ids.length > limit ? `${visible} +${ids.length - limit}` : visible;
}

function executionDiagnosticsFromQueue(queue: any, health: any): AnyRecord {
  return objectRecord(queue?.executionDiagnostics)
    || objectRecord(health?.body?.queue?.executionDiagnostics)
    || objectRecord(health?.queue?.executionDiagnostics)
    || objectRecord(health?.body?.executionDiagnostics)
    || objectRecord(health?.executionDiagnostics)
    || {};
}

function diagnosticsHeartbeatRiskTaskIds(diagnostics: any): string[] {
  return Array.from(new Set([
    ...stringArray(diagnostics?.heartbeatRiskTaskIds),
    ...stringArray(diagnostics?.heartbeatExpiredTaskIds),
    ...stringArray(diagnostics?.heartbeatMissingTaskIds),
    ...stringArray(diagnostics?.staleRecoveryCandidateTaskIds),
  ])).sort();
}

function splitBrainLiveDiagnostics(diagnostics: any): boolean {
  if (diagnosticsHeartbeatRiskTaskIds(diagnostics).length > 0) return false;
  if (typeof diagnostics?.splitBrainLive === "boolean") return diagnostics.splitBrainLive;
  const state = String(diagnostics?.state || diagnostics?.health || "").toLowerCase();
  const effective = String(diagnostics?.effectiveLiveness || "").toLowerCase();
  return state === "split-brain"
    && (effective === "live" || stringArray(diagnostics?.heartbeatFreshTaskIds).length > 0);
}

function diagnosticsEffectiveLiveness(diagnostics: any): string {
  const explicit = String(diagnostics?.effectiveLiveness || "").toLowerCase();
  if (explicit) return explicit;
  if (diagnosticsHeartbeatRiskTaskIds(diagnostics).length > 0) return "at-risk";
  if (splitBrainLiveDiagnostics(diagnostics)) return "live";
  const state = String(diagnostics?.state || diagnostics?.health || "unknown").toLowerCase();
  return state === "healthy" ? "healthy" : state === "unknown" ? "unknown" : "degraded";
}

function diagnosticsTone(diagnostics: any): string {
  const effective = diagnosticsEffectiveLiveness(diagnostics);
  const heartbeatRiskTaskIds = diagnosticsHeartbeatRiskTaskIds(diagnostics);
  const state = String(diagnostics?.state || diagnostics?.health || "unknown").toLowerCase();
  if (heartbeatRiskTaskIds.length > 0 || effective === "at-risk" || state === "stale-active") return "failed";
  if (splitBrainLiveDiagnostics(diagnostics)) return "degraded-live";
  if (effective === "live" || effective === "degraded") return "warn";
  if (["dead", "failed", "stale", "unhealthy"].includes(effective)) return "failed";
  const value = String(diagnostics?.state || diagnostics?.health || "unknown").toLowerCase();
  if (value === "healthy") return "ok";
  if (value === "split-brain") return "warn";
  if (value === "degraded") return "warn";
  return "unknown";
}

const allQueuesId = "__all__";
const queueMobileMediaQuery = "(max-width: 760px)";
const queueDesktopMediaQuery = "(min-width: 761px)";

function isAllQueues(queueId: string): boolean {
  return !queueId || queueId === allQueuesId;
}

function isMobileQueueViewport(): boolean {
  return typeof window !== "undefined" && window.matchMedia(queueMobileMediaQuery).matches;
}

function queueQuerySuffix(queueId: string): string {
  return isAllQueues(queueId) ? "" : `&queueId=${encodeURIComponent(queueId)}`;
}

function normalizedTaskSearchQuery(value: any): string {
  return String(value || "").trim().replace(/\s+/gu, " ").slice(0, 200);
}

function taskSearchQuerySuffix(query: string): string {
  const normalized = normalizedTaskSearchQuery(query);
  return normalized.length === 0 ? "" : `&search=${encodeURIComponent(normalized)}`;
}

function taskListQuerySuffix(queueId: string, searchQuery = ""): string {
  return `${queueQuerySuffix(queueId)}${taskSearchQuerySuffix(searchQuery)}`;
}

function queueStatusCount(row: any, status: string): number {
  return Number(row?.counts?.[status] || 0);
}

function knownQueueRows(queue: any, currentQueueId = ""): any[] {
  const byId = new Map<string, any>();
  for (const row of Array.isArray(queue?.queues) ? queue.queues : []) {
    const id = String(row?.id || "").trim();
    if (id.length > 0) byId.set(id, { ...row, name: String(row?.name || id).trim() || id });
  }
  for (const id of [String(queue?.defaultQueueId || "default"), currentQueueId].map((value) => value.trim()).filter(Boolean)) {
    if (!byId.has(id)) byId.set(id, { id, name: id, total: 0, counts: {}, activeTaskId: null, runnableTaskId: null, processing: false });
  }
  const rows = Array.from(byId.values());
  return rows.sort((left, right) => {
    const leftDefault = String(left?.id || "") === String(queue?.defaultQueueId || "default") ? 0 : 1;
    const rightDefault = String(right?.id || "") === String(queue?.defaultQueueId || "default") ? 0 : 1;
    if (leftDefault !== rightDefault) return leftDefault - rightDefault;
    return String(left?.id || "").localeCompare(String(right?.id || ""));
  });
}

function queueName(row: any): string {
  const id = String(row?.id || "default");
  const name = String(row?.name || "").trim();
  return name.length > 0 ? name : id;
}

function queueDisplayName(row: any): string {
  const id = String(row?.id || "default");
  const name = queueName(row);
  return name === id ? id : `${name} (${id})`;
}

function queueOptionLabel(row: any): string {
  const running = queueStatusCount(row, "running") + queueStatusCount(row, "judging");
  const waiting = queueStatusCount(row, "queued") + queueStatusCount(row, "retry_wait");
  const total = Number(row?.total || 0);
  const parts = [queueDisplayName(row), `${total} tasks`];
  if (running > 0) parts.push(`${running} running`);
  if (waiting > 0) parts.push(`${waiting} queued`);
  return parts.join(" · ");
}

function selectedQueueRow(queueRows: any[], queueId: string): any | null {
  if (isAllQueues(queueId)) return null;
  return queueRows.find((row) => String(row?.id || "") === queueId) || null;
}

function queueActiveTaskId(queue: any, queueRows: any[], queueId: string, rows: any[]): string {
  if (isAllQueues(queueId)) {
    const ids = activeTaskIds(queue);
    return String(queue?.activeTaskId || ids[0] || rows.find((task: any) => taskIsActive(task))?.id || "");
  }
  const row = selectedQueueRow(queueRows, queueId);
  return String(row?.activeTaskId || rows.find((task: any) => taskIsActive(task))?.id || "");
}

function queueRunnableTaskId(queueRows: any[], queueId: string, rows: any[]): string {
  if (!isAllQueues(queueId)) {
    const row = selectedQueueRow(queueRows, queueId);
    return String(row?.runnableTaskId || rows.find((task: any) => String(task?.status || "") === "queued" || String(task?.status || "") === "retry_wait")?.id || "");
  }
  return String(rows.find((task: any) => String(task?.status || "") === "queued" || String(task?.status || "") === "retry_wait")?.id || "");
}

async function loadTaskList(apiBaseUrl: string, queueId = allQueuesId, searchQuery = ""): Promise<any> {
  return requestJson(codexApi(
    apiBaseUrl,
    `/api/tasks/overview?limit=${codexInitialTaskLimit}&transcriptLimit=1&compact=1&selected=0&includeActive=0&stats=0&skipTrace=1${taskListQuerySuffix(queueId, searchQuery)}`,
  ), codexNoCacheOptions());
}

async function loadTaskOverview(apiBaseUrl: string, preferId: string, afterSeq = 0, queueId = allQueuesId, searchQuery = "", skipTrace = false, options: AnyRecord = {}): Promise<any> {
  const selectedParam = options.selected === false ? "&selected=0" : "";
  const includeActiveParam = options.includeActive === false ? "&includeActive=0" : "";
  const statsParam = options.stats === false ? "&stats=0" : "";
  const limit = Number.isInteger(options.limit) && options.limit > 0 ? Math.min(500, options.limit) : codexInitialTaskLimit;
  return requestJson(codexApi(
    apiBaseUrl,
    `/api/tasks/overview?limit=${encodeURIComponent(String(limit))}&transcriptLimit=3&compact=1&afterSeq=${encodeURIComponent(String(Math.max(0, afterSeq)))}&preferId=${encodeURIComponent(preferId)}${selectedParam}${includeActiveParam}${statsParam}${skipTrace ? "&skipTrace=1" : ""}${taskListQuerySuffix(queueId, searchQuery)}`,
  ), codexNoCacheOptions());
}

async function loadTaskStatistics(apiBaseUrl: string, queueId = allQueuesId): Promise<any> {
  return requestJson(codexApi(
    apiBaseUrl,
    `/api/tasks/stats?days=14${queueQuerySuffix(queueId)}`,
  ), codexNoCacheOptions());
}

async function loadTaskPage(apiBaseUrl: string, queueId: string, beforeId: string, limit = codexMoreTaskLimit, searchQuery = ""): Promise<any> {
  return requestJson(codexApi(
    apiBaseUrl,
    `/api/tasks/overview?limit=${encodeURIComponent(String(limit))}&transcriptLimit=1&compact=1&selected=0&includeActive=0&stats=0&beforeId=${encodeURIComponent(beforeId)}${taskListQuerySuffix(queueId, searchQuery)}`,
  ), codexNoCacheOptions());
}

async function loadTaskTraceSummary(apiBaseUrl: string, taskId: string): Promise<any> {
  return requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/trace-summary`));
}

async function loadTaskPromptPart(apiBaseUrl: string, taskId: string, part: string, attemptIndex: any = null): Promise<any> {
  const attemptParam = attemptIndex === null || attemptIndex === undefined || String(attemptIndex).length === 0
    ? ""
    : `&attempt=${encodeURIComponent(String(attemptIndex))}`;
  return requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/prompt?part=${encodeURIComponent(part)}${attemptParam}`));
}

async function loadTaskTraceSteps(apiBaseUrl: string, taskId: string, afterSeq = 0, limit = 500, attemptIndex: any = null): Promise<any> {
  const attemptParam = attemptIndex === null || attemptIndex === undefined || String(attemptIndex).length === 0
    ? ""
    : `&attempt=${encodeURIComponent(String(attemptIndex))}`;
  return requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/trace-steps?afterSeq=${encodeURIComponent(String(afterSeq))}&limit=${encodeURIComponent(String(limit))}${attemptParam}`));
}

async function loadTaskTraceStep(apiBaseUrl: string, taskId: string, seq: any): Promise<any> {
  return requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/trace-step?seq=${encodeURIComponent(String(seq))}`));
}

async function markTaskReadRequest(apiBaseUrl: string, taskId: string): Promise<any> {
  return requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/read`), { method: "POST", body: {} });
}

async function markAllTerminalReadRequest(apiBaseUrl: string): Promise<any> {
  return requestJson(codexApi(apiBaseUrl, "/api/tasks/read-all"), { method: "POST", body: {} });
}

function taskOutput(task: any): any[] {
  return Array.isArray(task?.output) ? task.output : [];
}

function initialPromptTranscriptItem(task: any): any | null {
  const promptView = taskPromptView(task);
  const prompt = String(promptView.displayPrompt || "").trimEnd();
  if (!task || prompt.length === 0) return null;
  return {
    seq: 0.5,
    at: task?.createdAt || task?.updatedAt,
    kind: "message",
    title: "Submitted prompt",
    status: "enqueue",
    bodyPreview: prompt,
    fullPrompt: promptView.fullPrompt,
    fullPromptLines: promptView.fullLines,
    fullPromptChars: promptView.fullPrompt.length,
    displayPromptLines: promptView.displayLines,
    foldedReferencePrompt: promptView.folded,
    referencePromptLines: promptView.referenceLines,
    referencePromptChars: String(promptView.resolved?.reference || "").length,
    rawSeqs: [],
  };
}

function isInitialPromptTranscriptItem(item: any): boolean {
  const title = String(item?.title || "").toLowerCase();
  return title === "submitted prompt" || title === "initial prompt";
}

function transcriptHasInitialPrompt(transcript: any[]): boolean {
  return transcript.some(isInitialPromptTranscriptItem);
}

function enrichInitialPromptTranscriptItem(task: any, item: any): any {
  const initialPrompt = initialPromptTranscriptItem(task);
  if (initialPrompt === null) return item;
  return {
    ...item,
    bodyPreview: initialPrompt.bodyPreview,
    fullPrompt: initialPrompt.fullPrompt,
    fullPromptLines: initialPrompt.fullPromptLines,
    fullPromptChars: initialPrompt.fullPromptChars,
    displayPromptLines: initialPrompt.displayPromptLines,
    foldedReferencePrompt: initialPrompt.foldedReferencePrompt,
    referencePromptLines: initialPrompt.referencePromptLines,
    referencePromptChars: initialPrompt.referencePromptChars,
  };
}

function withInitialPromptTranscript(task: any, transcript: any[]): any[] {
  if (transcriptHasInitialPrompt(transcript)) {
    return transcript.map((item) => isInitialPromptTranscriptItem(item) ? enrichInitialPromptTranscriptItem(task, item) : item);
  }
  const initialPrompt = initialPromptTranscriptItem(task);
  if (initialPrompt === null) return transcript;
  return [initialPrompt, ...transcript].sort((left, right) => Number(left?.seq ?? 0) - Number(right?.seq ?? 0));
}

function taskPromptHistory(task: any): any[] {
  return Array.isArray(task?.promptHistory) ? task.promptHistory : [];
}

function withPromptHistoryTranscript(task: any, transcript: any[]): any[] {
  const rows = [...transcript];
  for (const item of taskPromptHistory(task)) {
    const seq = Number(item?.seq);
    const text = String(item?.text || "").trimEnd();
    if (!Number.isFinite(seq) || text.length === 0) continue;
    const exists = rows.some((row) => Number(row?.seq) === seq && (String(row?.title || "") === "Steer prompt" || String(row?.status || "") === "turn/steer"));
    if (exists) continue;
    rows.push({
      seq,
      at: item?.at || task?.updatedAt,
      kind: "message",
      title: "Steer prompt",
      status: item?.method || "turn/steer",
      bodyPreview: text,
      rawSeqs: [seq],
    });
  }
  return rows.sort((left, right) => Number(left?.seq ?? 0) - Number(right?.seq ?? 0));
}

function taskTranscript(task: any): any[] {
  if (Array.isArray(task?.transcript)) return withPromptHistoryTranscript(task, withInitialPromptTranscript(task, task.transcript));
  const transcript = taskOutput(task).filter((item: any) => !(item.channel === "user" && item.method === "enqueue")).map((item: any) => ({
    seq: item.seq,
    at: item.at,
    kind: item.channel === "error" ? "error" : item.channel === "command" ? "ran" : "message",
    title: item.method || item.channel || "message",
    bodyPreview: String(item.text || ""),
    rawSeqs: [item.seq],
  }));
  return withPromptHistoryTranscript(task, withInitialPromptTranscript(task, transcript));
}

function taskAttempts(task: any): any[] {
  return Array.isArray(task?.attempts) ? task.attempts : [];
}

function queueCounts(queue: any): AnyRecord {
  return queue?.counts && typeof queue.counts === "object" && !Array.isArray(queue.counts) ? queue.counts : {};
}

function splitPromptTasks(prompt: string): string[] {
  return prompt
    .split(/^\s*---+\s*$/gmu)
    .map((part) => part.trim())
    .filter(Boolean);
}

function repeatCountValue(value: any): number {
  const count = Number(value);
  return Number.isFinite(count) ? Math.max(1, Math.min(50, Math.floor(count))) : 1;
}

function parseReferenceTaskIds(value: string): string[] {
  const ids: string[] = [];
  for (const part of value.split(/[\s,，;；]+/u)) {
    const id = part.trim();
    if (/^codex_\d+_[A-Za-z0-9_-]+$/u.test(id) && !ids.includes(id)) ids.push(id);
  }
  return ids;
}

function withReferenceHint(text: string, taskId: string): string {
  const ids = parseReferenceTaskIds(taskId);
  if (ids.length === 0) return text;
  return [
    `引用 Code Queue 任务 ${ids.join(" ")}。后端会在入队时只注入这些任务的 initial prompt 和 final response 全文；中间执行过程不注入，如需补充核查可运行：${ids.map((id) => `bun scripts/cli.ts codex task ${id}`).join("；")}`,
    "",
    "本次任务：",
    text,
  ].join("\n");
}

function splitResolvedReferencePrompt(prompt: string): { hasInjection: boolean; reference: string; userPrompt: string } {
  const marker = "\n# 本次任务\n";
  const title = "# Code Queue 已解析引用上下文";
  const trimmed = prompt.trimStart();
  if (!trimmed.startsWith(title)) return { hasInjection: false, reference: "", userPrompt: prompt };
  const offset = prompt.length - trimmed.length;
  const index = prompt.lastIndexOf(marker);
  if (index < offset) return { hasInjection: false, reference: "", userPrompt: prompt };
  return {
    hasInjection: true,
    reference: prompt.slice(offset, index).trimEnd(),
    userPrompt: prompt.slice(index + marker.length).trimStart(),
  };
}

function stripAutoReferenceHint(text: string): string {
  const trimmed = text.trimStart();
  if (!/^引用\s+Code Queue\s+任务\s+codex_\d+_[A-Za-z0-9_-]+/u.test(trimmed)) return text;
  const marker = "\n\n本次任务：";
  const index = trimmed.indexOf(marker);
  if (index === -1) return text;
  return trimmed.slice(index + marker.length).trimStart();
}

function promptLineCount(text: string): number {
  return text.length > 0 ? text.split(/\r\n|\r|\n/u).length : 0;
}

function previewTextField(value: any): string {
  if (typeof value === "string") return value;
  if (value && typeof value === "object" && !Array.isArray(value) && typeof value.text === "string") return value.text;
  return "";
}

function taskDisplayPrompt(task: any, options: AnyRecord = {}): string {
  if (options.preview === true) {
    const preview = previewTextField(task?.displayPromptPreview || task?.basePromptPreview || task?.promptPreview);
    if (preview.length > 0) return preview;
  }
  const explicit = String(task?.displayPrompt || "");
  if (explicit.length > 0) return explicit;
  const prompt = String(task?.prompt || "");
  return stripAutoReferenceHint(splitResolvedReferencePrompt(prompt).userPrompt);
}

function taskPromptView(task: any): AnyRecord {
  const fullPrompt = String(task?.prompt || "").trimEnd();
  const displayPrompt = taskDisplayPrompt(task).trimEnd();
  const resolved = splitResolvedReferencePrompt(fullPrompt);
  const folded = fullPrompt.length > 0 && displayPrompt.length > 0 && fullPrompt !== displayPrompt;
  return {
    fullPrompt,
    displayPrompt: displayPrompt || fullPrompt,
    resolved,
    folded,
    displayLines: promptLineCount(displayPrompt || fullPrompt),
    fullLines: promptLineCount(fullPrompt),
    referenceLines: promptLineCount(resolved.reference || ""),
  };
}

function taskTraceSummary(task: any): AnyRecord | null {
  return task?._traceSummary && typeof task._traceSummary === "object" && !Array.isArray(task._traceSummary) ? task._traceSummary : null;
}

function taskPromptDetails(task: any): AnyRecord {
  return task?._promptDetails && typeof task._promptDetails === "object" && !Array.isArray(task._promptDetails) ? task._promptDetails : {};
}

function taskPromptSummary(task: any): AnyRecord {
  const summary = taskTraceSummary(task)?.prompt;
  return summary && typeof summary === "object" && !Array.isArray(summary) ? summary : {};
}

function taskExecutionSummary(task: any): AnyRecord {
  const execution = taskTraceSummary(task)?.execution;
  return execution && typeof execution === "object" && !Array.isArray(execution) ? execution : {};
}

function nonNegativeCount(value: any): number {
  const numeric = Number(value);
  return Number.isFinite(numeric) && numeric >= 0 ? Math.floor(numeric) : 0;
}

function statCount(value: any): number | null {
  const numeric = Number(value);
  return Number.isFinite(numeric) && numeric >= 0 ? Math.floor(numeric) : null;
}

function taskOaTraceStats(task: any): AnyRecord | null {
  const direct = objectRecord(task?.traceStats);
  if (direct && (task?.statsSource === "oa-event-flow" || direct.source === "oa-event-flow")) return direct;
  const summary = taskTraceSummary(task);
  const summaryStats = objectRecord(summary?.traceStats);
  if (summaryStats && (summary?.statsSource === "oa-event-flow" || summaryStats.source === "oa-event-flow")) return summaryStats;
  return null;
}

function attemptOaTraceStats(task: any, attempt: any): AnyRecord | null {
  const direct = objectRecord(attempt?.traceStats) || objectRecord(attempt?.execution?.traceStats);
  const source = String(attempt?.statsSource || attempt?.execution?.statsSource || "");
  if (direct && (source === "oa-event-flow" || direct.source === "oa-event-flow")) return direct;
  return null;
}

function traceStatCount(task: any, key: string): number | null {
  return statCount(taskOaTraceStats(task)?.[key]);
}

function canonicalTaskStepCount(task: any): number | null {
  const direct = traceStatCount(task, "stepCount");
  if (direct !== null) return direct;
  const summary = taskTraceSummary(task);
  if (summary !== null) return traceSummaryStepCount(summary);
  return null;
}

function rawTraceStepCountFallback(...values: any[]): number | null {
  for (const value of values) {
    const count = statCount(value);
    if (count !== null) return count;
  }
  return null;
}

function traceStepCountLabel(state: AnyRecord): string {
  if (state.state === "ready" || state.state === "fallback") return `STEP ${state.count}${state.state === "fallback" ? " raw" : ""}`;
  if (state.state === "syncing") return "STEP sync";
  if (state.state === "failed") return "STEP failed";
  return "STEP N/A";
}

function traceStepCountState(task: any): AnyRecord {
  const oaStats = taskOaTraceStats(task);
  const oaCount = statCount(oaStats?.stepCount ?? oaStats?.llmStepCount);
  if (oaCount !== null) {
    return {
      state: "ready",
      count: oaCount,
      label: `STEP ${oaCount}`,
      title: "STEP 来自 OA Event Flow 统计中心",
      source: "oa-event-flow",
    };
  }
  const summary = taskTraceSummary(task);
  const activeWithoutRawRows = taskIsActive(task)
    && task?._traceSummaryLoaded !== true
    && statCount(task?.outputCount ?? task?.retainedOutputCount) === 0;
  const rawCount = rawTraceStepCountFallback(
    summary?.retainedStepCount,
    summary?.execution?.traceLineCount,
    summary?.execution?.stepCount,
    task?.outputCount,
    task?.retainedOutputCount,
    activeWithoutRawRows ? null : task?.stepCount,
    activeWithoutRawRows ? null : task?.llmStepCount,
  );
  if (rawCount !== null) {
    return {
      state: "fallback",
      count: rawCount,
      label: `STEP ${rawCount} raw`,
      title: "OA STEP 统计不可用，当前显示 raw trace fallback 行数",
      source: "raw-trace",
    };
  }
  if (summary?.traceStatsError || task?.traceStatsError) {
    return {
      state: "failed",
      count: null,
      label: "STEP failed",
      title: "STEP 统计读取失败；请查看 trace summary 原始 JSON",
      source: "stats-error",
    };
  }
  if (taskIsActive(task) || task?._traceSummaryLoaded !== true) {
    return {
      state: "syncing",
      count: null,
      label: "STEP sync",
      title: "STEP 统计同步中；Trace Summary 或 OA 统计尚未返回",
      source: "syncing",
    };
  }
  return {
    state: "unavailable",
    count: null,
    label: "STEP N/A",
    title: "当前任务没有可用 STEP 统计或 raw trace fallback",
    source: "unavailable",
  };
}

function traceSummaryStepCount(summary: AnyRecord | null): number | null {
  const stats = objectRecord(summary?.traceStats);
  if (!stats || (summary?.statsSource !== "oa-event-flow" && stats.source !== "oa-event-flow")) return null;
  return statCount(stats.stepCount);
}

function traceSummaryIsCurrent(task: any): boolean {
  if (!task || task?._traceSummaryLoaded !== true) return false;
  const summary = taskTraceSummary(task);
  const summaryAt = String(task?._traceSummaryUpdatedAt || summary?.updatedAt || "");
  const updatedAt = String(task?.updatedAt || "");
  if (updatedAt.length > 0) {
    const summaryMs = timestampMs(summaryAt);
    const updatedMs = timestampMs(updatedAt);
    if (summaryMs !== null && updatedMs !== null) {
      if (summaryMs + 1 < updatedMs) return false;
    } else if (summaryAt !== updatedAt) {
      return false;
    }
  }
  return true;
}

function taskBasePromptText(task: any): string {
  const summaryPrompt = taskPromptSummary(task);
  const basePrompt = String(summaryPrompt.basePrompt || "");
  if (basePrompt.length > 0) return basePrompt;
  const direct = String(task?.basePrompt || "");
  return direct.length > 0 ? direct : taskDisplayPrompt(task);
}

function taskFinalResponseText(task: any): string {
  const summary = taskTraceSummary(task);
  const finalResponse = String(summary?.finalResponse || task?.finalResponse || "");
  return finalResponse.trimEnd();
}

function taskLastJudge(task: any): AnyRecord | null {
  const summaryJudge = taskTraceSummary(task)?.lastJudge;
  const judge = summaryJudge || task?.lastJudge;
  return judge && typeof judge === "object" && !Array.isArray(judge) ? judge : null;
}

function objectRecord(value: any): AnyRecord | null {
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
}

function judgeFailureDetailsText(judge: any): string {
  const raw = objectRecord(judge?.raw);
  const details = objectRecord(judge?.failureDetails) || objectRecord(raw?.minimaxFailure);
  if (details === null) return "";
  const repairAttempt = details.repairAttempt === undefined ? "" : `${details.repairAttempt}/${details.maxRepairAttempts ?? "?"}`;
  const rows = [
    ["provider", details.provider || "minimax"],
    ["stage", details.stage],
    ["model", details.model],
    ["timedOut", details.timedOut],
    ["durationMs", details.durationMs],
    ["timeoutMs", details.timeoutMs],
    ["promptChars", details.promptChars],
    ["promptLines", details.promptLines],
    ["payloadBytes", details.payloadBytes],
    ["responseStatus", details.responseStatus],
    ["repairAttempt", repairAttempt],
    ["errorName", details.errorName],
    ["error", details.errorMessage],
    ["responseContentPreview", details.responseContentPreview],
    ["responseTextPreview", details.responseTextPreview],
  ].filter(([, value]) => value !== undefined && value !== null && String(value).length > 0);
  return rows.map(([key, value]) => `${key}: ${String(value)}`).join("\n");
}

function JudgeFailureDetails({ judge, testId = "codex-judge-failure-details" }: AnyRecord) {
  const text = judgeFailureDetailsText(judge);
  if (text.length === 0) return null;
  return h("details", { className: "codex-judge-failure-details", "data-testid": testId },
    h("summary", null, "MiniMax failure details"),
    h("pre", null, text),
  );
}

function taskProgressiveAttempts(task: any): any[] {
  const summaryAttempts = taskTraceSummary(task)?.attempts;
  if (Array.isArray(summaryAttempts) && summaryAttempts.length > 0) return currentFirstAttempts(task, withCurrentAttemptSegment(task, summaryAttempts));
  const execution = taskExecutionSummary(task);
  const finalResponse = taskFinalResponseText(task);
  const judge = taskLastJudge(task);
  if (Object.keys(execution).length === 0 && finalResponse.length === 0 && judge === null) return currentFirstAttempts(task, withCurrentAttemptSegment(task, []));
  return currentFirstAttempts(task, withCurrentAttemptSegment(task, [{
    index: Number(task?.currentAttempt || 1),
    mode: task?.currentMode || "initial",
    startedAt: task?.startedAt,
    finishedAt: task?.finishedAt,
    terminalStatus: task?.status,
    execution,
    finalResponse,
    finalResponseChars: finalResponse.length,
    judge,
  }]));
}

function attemptIsCurrent(task: any, attemptIndex: any): boolean {
  const summary = taskTraceSummary(task);
  const currentAttempt = Number(summary?.currentAttempt || task?.currentAttempt || 0);
  const numericAttempt = Number(attemptIndex);
  return Number.isFinite(currentAttempt) && currentAttempt > 0 && Number.isFinite(numericAttempt) && numericAttempt === currentAttempt;
}

function attemptIsActiveCurrent(task: any, attemptIndex: any): boolean {
  return taskIsActive(task) && attemptIsCurrent(task, attemptIndex);
}

function withCurrentAttemptSegment(task: any, attempts: any[]): any[] {
  const rows = Array.isArray(attempts) ? attempts.filter(Boolean) : [];
  const summary = taskTraceSummary(task);
  const currentAttempt = Number(summary?.currentAttempt || task?.currentAttempt || 0);
  if (!taskIsActive(task) || !Number.isFinite(currentAttempt) || currentAttempt <= 0) return rows;
  if (rows.some((attempt) => Number(attempt?.index) === currentAttempt)) return rows;
  const activeAt = latestTimestampValue(task?.startedAt, summary?.startedAt, task?.updatedAt, summary?.updatedAt);
  return [
    ...rows,
    {
      index: currentAttempt,
      mode: task?.currentMode || summary?.currentMode || (currentAttempt <= 1 ? "initial" : "retry"),
      startedAt: activeAt || task?.startedAt || summary?.startedAt,
      finishedAt: null,
      terminalStatus: null,
      execution: {},
      finalResponse: "",
      finalResponsePreview: "",
      finalResponseChars: 0,
      judge: null,
      currentPlaceholder: true,
    },
  ];
}

function currentFirstAttempts(task: any, attempts: any[]): any[] {
  const rows = [...(Array.isArray(attempts) ? attempts : [])];
  if (!taskIsActive(task)) return rows;
  return rows.sort((left, right) => {
    const leftIndex = Number(left?.index);
    const rightIndex = Number(right?.index);
    const leftCurrent = attemptIsCurrent(task, leftIndex) ? 0 : 1;
    const rightCurrent = attemptIsCurrent(task, rightIndex) ? 0 : 1;
    if (leftCurrent !== rightCurrent) return leftCurrent - rightCurrent;
    return leftIndex - rightIndex;
  });
}

function attemptExecutionSummary(task: any, attempt: any): AnyRecord {
  return objectRecord(attempt?.execution) || taskExecutionSummary(task);
}

function attemptExecutionUpdatedAt(task: any, attempt: any, attemptIndex: any, execution: AnyRecord): string {
  const summary = taskTraceSummary(task);
  const currentAttempt = Number(summary?.currentAttempt || task?.currentAttempt || 0);
  const numericAttempt = Number(attemptIndex);
  const isCurrentAttempt = Number.isFinite(numericAttempt) && numericAttempt > 0 && numericAttempt === currentAttempt;
  const activeTaskUpdatedAt = latestTimestampValue(task?.updatedAt, summary?.updatedAt);
  if (isCurrentAttempt && !attempt?.finishedAt && activeTaskUpdatedAt.length > 0) return activeTaskUpdatedAt;
  return String(
    attempt?.updatedAt
      || attempt?.finishedAt
      || execution.effectiveEndAt
      || (isCurrentAttempt ? activeTaskUpdatedAt : "")
      || activeTaskUpdatedAt
      || task?.finishedAt
      || task?.startedAt
      || "",
  );
}

function attemptFinalResponseText(task: any, attempt: any): string {
  const text = String(attempt?.finalResponse || attempt?.finalResponsePreview || "");
  if (attemptIsActiveCurrent(task, attempt?.index)) return "";
  if (Object.prototype.hasOwnProperty.call(attempt || {}, "finalResponse") || Object.prototype.hasOwnProperty.call(attempt || {}, "finalResponsePreview")) return text.trimEnd();
  return text.length > 0 ? text.trimEnd() : taskFinalResponseText(task);
}

function attemptJudge(task: any, attempt: any, attemptIndex: any = attempt?.index): AnyRecord | null {
  if (attemptIsActiveCurrent(task, attemptIndex)) return null;
  if (Object.prototype.hasOwnProperty.call(attempt || {}, "judge")) return objectRecord(attempt?.judge);
  return taskLastJudge(task);
}

function attemptExecutionIsRunning(task: any, attempt: any, attemptIndex: any): boolean {
  if (!taskIsExecuting(task)) return false;
  if (isSyntheticAttemptSegment(attempt, attemptIndex)) return false;
  if (attempt?.finishedAt) return false;
  if (["succeeded", "failed", "canceled"].includes(String(attempt?.terminalStatus || ""))) return false;
  if (attemptIsCurrent(task, attemptIndex)) return true;
  const currentAttempt = Number(taskTraceSummary(task)?.currentAttempt || task?.currentAttempt || 0);
  if (Number.isFinite(currentAttempt) && currentAttempt > 0) return false;
  return true;
}

function feedbackPromptDetailKey(attemptIndex: any): string {
  return `feedback:${String(attemptIndex || "latest")}`;
}

function attemptFeedbackPrompt(task: any, attempt: any, attemptIndex: any): AnyRecord | null {
  const text = String(attempt?.feedbackPrompt || "").trimEnd();
  const preview = String(attempt?.feedbackPromptPreview || text || "").trimEnd();
  const chars = Number(attempt?.feedbackPromptChars || text.length || preview.length || 0);
  const lines = Number(attempt?.feedbackPromptLines || promptLineCount(text || preview));
  if (text.length > 0 || preview.length > 0 || chars > 0) {
    return {
      text,
      preview,
      chars,
      lines,
      source: attempt?.feedbackPromptSource || "judge-feedback",
      forAttempt: attempt?.feedbackPromptForAttempt || Number(attemptIndex || 0) + 1,
      truncated: Boolean(attempt?.feedbackPromptTruncated),
    };
  }
  const judge = attemptJudge(task, attempt, attemptIndex);
  const continuePrompt = String(judge?.continuePrompt || "").trimEnd();
  if (judge?.decision === "retry" && continuePrompt.length > 0) {
    return {
      text: "",
      preview: continuePrompt,
      chars: continuePrompt.length,
      lines: promptLineCount(continuePrompt),
      source: "judge-continue-prompt",
      forAttempt: Number(attemptIndex || 0) + 1,
      truncated: false,
    };
  }
  return null;
}

function taskHasReferencePrompt(task: any): boolean {
  const promptSummary = taskPromptSummary(task);
  return Boolean(promptSummary.hasReferenceInjection || Number(promptSummary.referencePromptChars || 0) > 0 || task?.referenceInjection || task?.referenceInjectionSummary);
}

function taskTraceSteps(task: any, attemptIndex: any = null): any[] {
  if (attemptIndex !== null && attemptIndex !== undefined) {
    const byAttempt = objectRecord(task?._traceStepsByAttempt) || {};
    const rows = byAttempt[String(attemptIndex)];
    return Array.isArray(rows) ? rows : [];
  }
  return Array.isArray(task?._traceSteps) ? task._traceSteps : [];
}

function traceStepSeqValue(step: any): number {
  const candidates = [step?.seq, ...(Array.isArray(step?.rawSeqs) ? step.rawSeqs : [])].map((value) => Number(value));
  const finite = candidates.filter((value) => Number.isFinite(value));
  return finite.length > 0 ? Math.max(...finite) : 0;
}

function traceStepsMaxSeq(steps: any[]): number {
  return (Array.isArray(steps) ? steps : []).reduce((max, step) => Math.max(max, traceStepSeqValue(step)), 0);
}

function mergeTraceStepRows(existing: any[], incoming: any[]): any[] {
  const byKey = new Map<string, any>();
  for (const step of [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(incoming) ? incoming : [])]) {
    const key = String(step?.seq ?? `${step?.title || "step"}:${step?.at || ""}`);
    byKey.set(key, { ...(byKey.get(key) || {}), ...step });
  }
  return Array.from(byKey.values()).sort((left, right) => traceStepSeqValue(left) - traceStepSeqValue(right));
}

function traceStepSummaryLines(step: any): string[] {
  return (Array.isArray(step?.summaryLines) ? step.summaryLines : []).map((line: any) => String(line || ""));
}

function traceStepIsError(step: any): boolean {
  const kind = String(step?.kind || "").trim().toLowerCase();
  const status = String(step?.status || "").trim().toLowerCase();
  return kind === "error" || status === "error";
}

function traceStepErrorCount(steps: any[]): number {
  return (Array.isArray(steps) ? steps : []).reduce((count, step) => count + (traceStepIsError(step) ? 1 : 0), 0);
}

function traceStepFileChangeMethod(step: any): string {
  const status = String(step?.status || "").trim();
  if (status.length > 0) return status;
  const text = traceStepSummaryLines(step).join("\n");
  return /^(item\/[A-Za-z]+(?:\/[A-Za-z]+)?):/u.exec(text)?.[1] || "";
}

function isFileChangeLifecycleSummaryLine(line: string): boolean {
  return /^item\/(?:started|completed): file changes status=/u.test(String(line || "").trim());
}

function fileChangeStatusFromStep(step: any): string {
  const lines = traceStepSummaryLines(step);
  for (let index = lines.length - 1; index >= 0; index -= 1) {
    const status = /file changes status=([A-Za-z0-9_-]+)/u.exec(lines[index] || "")?.[1];
    if (status) return status;
  }
  const method = traceStepFileChangeMethod(step);
  if (method === "item/fileChange/outputDelta") return "updated";
  if (method === "item/started") return "started";
  if (method === "item/completed") return "completed";
  return method.replace(/^item\//u, "") || String(step?.status || "changed");
}

function isFileChangeTraceStep(step: any): boolean {
  if (String(step?.kind || "") !== "edited") return false;
  const title = String(step?.title || "");
  const status = String(step?.status || "");
  const text = traceStepSummaryLines(step).join("\n");
  if (title === "Edited files") return true;
  if (/^item\/fileChange\//u.test(status)) return true;
  if ((status === "item/started" || status === "item/completed") && /file changes status=/u.test(text)) return true;
  if (/^Success\. Updated the following files:/mu.test(text)) return true;
  if (/^diff --git /mu.test(text)) return true;
  return /^([AMDRCU?]{1,2})\s+\S+/mu.test(text);
}

function mergeFileChangeTraceStepGroup(group: any[]): any {
  if (group.length <= 1) return group[0];
  const outputStep = group.find((step) => traceStepFileChangeMethod(step) === "item/fileChange/outputDelta") || group.find((step) => traceStepSummaryLines(step).some((line) => !isFileChangeLifecycleSummaryLine(line))) || group.at(-1) || group[0];
  const rawSeqs = group.flatMap((step) => Array.isArray(step?.rawSeqs) ? step.rawSeqs : [step?.seq]).filter((seq) => seq !== undefined);
  const summaryLines = group
    .flatMap(traceStepSummaryLines)
    .filter((line) => line.trim().length > 0 && !isFileChangeLifecycleSummaryLine(line));
  const finalStep = group[group.length - 1] || outputStep;
  return {
    ...outputStep,
    at: outputStep?.at || finalStep?.at,
    title: String(outputStep?.title || "Edited files"),
    status: fileChangeStatusFromStep(finalStep),
    summaryLines: summaryLines.length > 0 ? summaryLines : traceStepSummaryLines(outputStep),
    rawSeqs,
  };
}

function coalesceFileChangeTraceSteps(steps: any[]): any[] {
  const rows = Array.isArray(steps) ? steps : [];
  const merged: any[] = [];
  let group: any[] = [];
  const flush = () => {
    if (group.length > 0) merged.push(mergeFileChangeTraceStepGroup(group));
    group = [];
  };
  for (const step of rows) {
    if (isFileChangeTraceStep(step)) {
      if (traceStepFileChangeMethod(step) === "item/started" && group.length > 0) flush();
      group.push(step);
      if (traceStepFileChangeMethod(step) === "item/completed") flush();
      continue;
    }
    flush();
    merged.push(step);
  }
  flush();
  return merged;
}

function traceStepMessageMergeKey(step: any): string {
  if (String(step?.kind || "") !== "message") return "";
  const title = String(step?.title || "").trim().toLowerCase();
  if (title !== "assistant message" && title !== "reasoning") return "";
  return `${title}:${String(step?.status || "")}`;
}

function mergeMessageTraceStepGroup(group: any[]): any {
  if (group.length <= 1) return group[0];
  const first = group[0];
  const last = group.at(-1) || first;
  const rawSeqs = group.flatMap((step) => Array.isArray(step?.rawSeqs) ? step.rawSeqs : [step?.seq]).filter((seq) => seq !== undefined);
  const seenRawSeqs: any[] = [];
  for (const seq of rawSeqs) if (!seenRawSeqs.includes(seq)) seenRawSeqs.push(seq);
  const summaryLines = group
    .flatMap(traceStepSummaryLines)
    .filter((line) => line.trim().length > 0);
  return {
    ...first,
    seq: traceStepSeqValue(last) || traceStepSeqValue(first),
    at: last?.at || first?.at,
    summaryLines: summaryLines.length > 0 ? [summaryLines.at(-1) || summaryLines[0]] : [],
    rawSeqs: seenRawSeqs,
  };
}

function coalesceMessageTraceSteps(steps: any[]): any[] {
  const rows = Array.isArray(steps) ? steps : [];
  const merged: any[] = [];
  let group: any[] = [];
  let groupKey = "";
  const flush = () => {
    if (group.length > 0) merged.push(mergeMessageTraceStepGroup(group));
    group = [];
    groupKey = "";
  };
  for (const step of rows) {
    const key = traceStepMessageMergeKey(step);
    if (key.length > 0 && key === groupKey) {
      group.push(step);
      continue;
    }
    flush();
    if (key.length > 0) {
      group = [step];
      groupKey = key;
    } else {
      merged.push(step);
    }
  }
  flush();
  return merged;
}

function coalesceTraceSteps(steps: any[]): any[] {
  return coalesceMessageTraceSteps(coalesceFileChangeTraceSteps(steps));
}

function canonicalExecutionSummary(execution: AnyRecord): AnyRecord {
  return { ...execution };
}

function taskTraceStepsLoaded(task: any, attemptIndex: any = null): boolean {
  if (attemptIndex !== null && attemptIndex !== undefined) {
    const byAttempt = objectRecord(task?._traceStepsLoadedByAttempt) || {};
    return Boolean(byAttempt[String(attemptIndex)]);
  }
  return Boolean(task?._traceStepsLoaded);
}

function traceStepsLoadingKey(taskId: string, attemptIndex: any = null): string {
  const attemptKey = attemptIndex === null || attemptIndex === undefined || String(attemptIndex).length === 0 ? "all" : String(attemptIndex);
  return `${taskId}:${attemptKey}`;
}

function traceStepLoadingKey(taskId: string, seq: any): string {
  return `${taskId}:${String(seq ?? "")}`;
}

function taskTraceStepDetails(task: any): AnyRecord {
  return task?._traceStepDetails && typeof task._traceStepDetails === "object" && !Array.isArray(task._traceStepDetails) ? task._traceStepDetails : {};
}

function attemptSegmentIndex(attempt: any, position: number): number {
  const raw = Number(attempt?.index);
  return Number.isFinite(raw) ? raw : position + 1;
}

function isSyntheticAttemptSegment(attempt: any, attemptIndex: any): boolean {
  return Boolean(attempt?.synthetic) || Number(attemptIndex) <= 0;
}

function attemptDataIndex(attemptIndex: any): string | undefined {
  const value = Number(attemptIndex);
  return Number.isFinite(value) ? String(value) : undefined;
}

function taskDurationLabel(task: any): string {
  const timing = task?.timing && typeof task.timing === "object" ? task.timing : {};
  const status = String(task?.status || "");
  if (["queued"].includes(status)) return `等待 ${fmtDuration(timing.queueWaitMs ?? timing.totalElapsedMs)}`;
  if (["running", "judging", "retry_wait"].includes(status)) return `耗时 ${fmtDuration(timing.durationMs ?? timing.totalElapsedMs)}`;
  return `耗时 ${fmtDuration(timing.durationMs ?? timing.totalElapsedMs)}`;
}

function taskQueueLabel(task: any): string {
  return String(task?.queueId || "default");
}

function queuedReasonRecord(task: any): AnyRecord | null {
  const reason = objectRecord(task?.queuedReason);
  return reason;
}

function queuedReasonLabel(task: any): string {
  const explicit = String(task?.queuedReasonLabel || "").trim();
  if (explicit.length > 0) return explicit.toUpperCase();
  const reason = queuedReasonRecord(task);
  const label = String(reason?.label || "").trim();
  return label.length > 0 ? label.toUpperCase() : "";
}

function taskStatusBadgeText(task: any): string {
  const status = String(task?.status || "unknown");
  if (status !== "queued") return status;
  const reason = queuedReasonLabel(task);
  return reason.length > 0 ? `QUEUED(${reason})` : "QUEUED";
}

function taskStatusBadgeTitle(task: any): string | undefined {
  if (String(task?.status || "") !== "queued") return undefined;
  const reason = queuedReasonRecord(task);
  const message = String(reason?.message || "").trim();
  const label = queuedReasonLabel(task);
  if (message.length > 0 && label.length > 0) return `${label}: ${message}`;
  if (message.length > 0) return message;
  return label.length > 0 ? label : undefined;
}

function channelLabel(channel: string): string {
  const labels: Record<string, string> = {
    system: "SYS",
    user: "YOU",
    assistant: "GPT",
    reasoning: "THINK",
    command: "CMD",
    diff: "DIFF",
    tool: "TOOL",
    error: "ERR",
  };
  return labels[channel] || channel.toUpperCase();
}

function taskIsActive(task: any): boolean {
  return ["running", "judging", "retry_wait"].includes(String(task?.status || ""));
}

function taskIsExecuting(task: any): boolean {
  return String(task?.status || "") === "running";
}

function taskIsTerminal(task: any): boolean {
  return ["succeeded", "failed", "canceled"].includes(String(task?.status || ""));
}

function taskPromptEditable(task: any): boolean {
  if (task?.promptEditable === true) return true;
  if (task?.promptEditable === false) return false;
  return String(task?.status || "") === "queued"
    && !task?.startedAt
    && Number(task?.currentAttempt || 0) === 0
    && !task?.codexThreadId
    && !task?.nextMode;
}

function taskIsUnreadTerminal(task: any): boolean {
  if (!taskIsTerminal(task)) return false;
  if (task?.terminalUnread === true) return true;
  if (task?.terminalUnread === false) return false;
  return !task?.readAt;
}

function countNumber(value: any): number {
  const number = Number(value || 0);
  return Number.isFinite(number) ? number : 0;
}

function queueWaitingCount(counts: AnyRecord): number {
  return countNumber(counts.queued) + countNumber(counts.retry_wait);
}

function queueRunningCount(counts: AnyRecord): number {
  return countNumber(counts.running) + countNumber(counts.judging);
}

function taskStatistics(data: any, fallbackQueue: any): AnyRecord {
  return objectRecord(data?.statistics) || objectRecord(fallbackQueue?.statistics) || {};
}

function firstDefined(...values: any[]): any {
  return values.find((value) => value !== undefined && value !== null);
}

function statsNumber(value: any): number | null {
  const number = Number(value);
  return Number.isFinite(number) && number >= 0 ? number : null;
}

function statsCountValue(...values: any[]): number {
  for (const value of values) {
    const number = statsNumber(value);
    if (number !== null) return Math.floor(number);
  }
  return 0;
}

function statsDurationValue(...values: any[]): number | null {
  for (const value of values) {
    const number = statsNumber(value);
    if (number !== null) return Math.round(number);
  }
  return null;
}

function taskStatisticsRawRows(stats: any): any[] {
  for (const value of [
    stats?.daily,
    stats?.dailyBuckets,
    stats?.daily_buckets,
    stats?.buckets,
    stats?.rows,
    stats?.series,
  ]) {
    if (Array.isArray(value)) return value;
  }
  return [];
}

function taskStatisticsRows(stats: any): any[] {
  return taskStatisticsRawRows(stats)
    .map((row: any, index: number) => {
      const record = objectRecord(row) || {};
      const date = String(firstDefined(record.date, record.day, record.bucketDate, record.bucket, `day-${index}`) || "");
      return {
        ...record,
        date,
        executedTasks: statsCountValue(record.executedTasks, record.tasks, record.taskCount, record.startedTasks, record.started, record.executed, record.count),
        completedTasks: statsCountValue(record.completedTasks, record.terminalTasks, record.terminalCount, record.finishedTasks, record.finished, record.completed),
        retryAttempts: statsCountValue(record.retryAttempts, record.retries, record.retryCount, record.retryTasks),
        succeededTasks: statsCountValue(record.succeededTasks, record.succeeded, record.success),
        failedTasks: statsCountValue(record.failedTasks, record.failed, record.failures),
        canceledTasks: statsCountValue(record.canceledTasks, record.cancelledTasks, record.canceled, record.cancelled),
        totalDurationMs: statsCountValue(record.totalDurationMs, record.durationTotalMs, record.totalCompletionDurationMs),
        durationSamples: statsCountValue(record.durationSamples, record.avgDurationSamples, record.samples, record.sampleCount),
        avgDurationMs: statsDurationValue(record.avgDurationMs, record.averageDurationMs, record.avgCompletedDurationMs, record.averageCompletionMs, record.averageDuration, record.durationMs),
      };
    })
    .filter((row: any) => row.date.length > 0);
}

function sumStatRows(rows: any[], key: string): number {
  return rows.reduce((sum, row) => sum + countNumber(row?.[key]), 0);
}

function weightedAverageDuration(rows: any[]): number | null {
  let totalDuration = 0;
  let samples = 0;
  for (const row of rows) {
    const rowSamples = countNumber(row?.durationSamples);
    const average = statsDurationValue(row?.avgDurationMs);
    if (rowSamples > 0 && average !== null) {
      totalDuration += average * rowSamples;
      samples += rowSamples;
    }
  }
  return samples > 0 ? Math.round(totalDuration / samples) : null;
}

function taskStatisticsTotals(stats: any, rows: any[] = taskStatisticsRows(stats)): AnyRecord {
  const totals = objectRecord(stats?.totals) || objectRecord(stats?.summary) || {};
  const durationSamples = statsCountValue(totals.durationSamples, totals.avgDurationSamples, totals.samples, stats?.durationSamples, stats?.samples, sumStatRows(rows, "durationSamples"));
  const totalDurationMs = statsCountValue(totals.totalDurationMs, totals.durationTotalMs, stats?.totalDurationMs, sumStatRows(rows, "totalDurationMs"));
  const avgDurationMs = statsDurationValue(
    totals.avgDurationMs,
    totals.averageDurationMs,
    totals.avgCompletedDurationMs,
    stats?.avgDurationMs,
    stats?.averageDurationMs,
    durationSamples > 0 && totalDurationMs > 0 ? totalDurationMs / durationSamples : null,
    weightedAverageDuration(rows),
  );
  return {
    ...totals,
    executedTasks: statsCountValue(totals.executedTasks, totals.tasks, totals.taskCount, stats?.executedTasks, stats?.tasks, stats?.taskCount, sumStatRows(rows, "executedTasks")),
    completedTasks: statsCountValue(totals.completedTasks, totals.terminalTasks, totals.terminalCount, totals.finishedTasks, stats?.completedTasks, stats?.terminalTasks, stats?.terminalCount, sumStatRows(rows, "completedTasks")),
    retryAttempts: statsCountValue(totals.retryAttempts, totals.retries, totals.retryCount, stats?.retryAttempts, stats?.retries, stats?.retryCount, sumStatRows(rows, "retryAttempts")),
    succeededTasks: statsCountValue(totals.succeededTasks, stats?.succeededTasks, sumStatRows(rows, "succeededTasks")),
    failedTasks: statsCountValue(totals.failedTasks, stats?.failedTasks, sumStatRows(rows, "failedTasks")),
    canceledTasks: statsCountValue(totals.canceledTasks, totals.cancelledTasks, stats?.canceledTasks, stats?.cancelledTasks, sumStatRows(rows, "canceledTasks")),
    durationSamples,
    totalDurationMs,
    avgDurationMs,
  };
}

function taskStatisticsReason(stats: any): string {
  const raw = firstDefined(stats?.reason, stats?.degradedReason, stats?.statsReason, stats?.error, stats?.message, stats?.detail);
  if (typeof raw === "string" && raw.trim().length > 0) return shortText(raw, 180);
  if (stats?.skipped === true) return "统计 API 返回 skipped，当前后端未提供 daily buckets。";
  if (stats?.unavailable === true) return "统计 API 当前不可用。";
  return "统计 API 未返回可用的 daily buckets。";
}

function taskStatisticsState(stats: any, rows: any[], totals: AnyRecord): AnyRecord {
  const hasStatsObject = objectRecord(stats) !== null;
  const explicitUnavailable = stats?.unavailable === true || stats?._unavailable === true || stats?.available === false;
  const skipped = stats?.skipped === true;
  const degraded = stats?.degraded === true || stats?.isDegraded === true || explicitUnavailable || skipped;
  const totalActivity = countNumber(totals.executedTasks) + countNumber(totals.retryAttempts) + countNumber(totals.completedTasks);
  if (!hasStatsObject) {
    return { state: "loading", label: "统计同步中", reason: "正在读取 Code Queue stats API。" };
  }
  if (explicitUnavailable || skipped || (degraded && rows.length === 0)) {
    return { state: "unavailable", label: "统计不可用", reason: taskStatisticsReason(stats), degraded: true };
  }
  if (degraded) {
    return { state: "degraded", label: "统计降级", reason: taskStatisticsReason(stats), degraded: true };
  }
  if (rows.length === 0 && totalActivity === 0) {
    return { state: "empty", label: "暂无统计", reason: "任务开始执行后会生成按天汇总的曲线。" };
  }
  return { state: "ready", label: "统计就绪", reason: "" };
}

function taskStatisticsUnavailable(error: unknown): AnyRecord {
  return {
    source: "frontend-stats-fetch",
    unavailable: true,
    degraded: true,
    reason: errorText(error, "统计 API 不可用"),
    daily: [],
    totals: null,
  };
}

function statMetric(row: any, key: string): number {
  const value = Number(row?.[key] ?? 0);
  return Number.isFinite(value) && value > 0 ? value : 0;
}

function statMetricMax(rows: any[], key: string): number {
  return rows.reduce((max, row) => Math.max(max, statMetric(row, key)), 0);
}

const statChartWidth = 700;
const statChartHeight = 220;
const statChartPaddingX = 30;
const statChartTopY = 24;
const statChartBaselineY = 184;
const statChartValueHeight = statChartBaselineY - statChartTopY;

function statPointX(index: number, total: number): number {
  if (total <= 1) return statChartWidth / 2;
  return statChartPaddingX + (index * (statChartWidth - statChartPaddingX * 2)) / (total - 1);
}

function statPointY(value: number, max: number): number {
  const denominator = max > 0 ? max : 1;
  return statChartBaselineY - Math.min(1, value / denominator) * statChartValueHeight;
}

function statLinePoints(rows: any[], key: string, max: number): string {
  const source = rows.length > 0 ? rows : [{ [key]: 0 }];
  const chartRows = source.length > 1 ? source : [source[0], source[0]];
  return chartRows
    .map((row, index) => `${statPointX(index, chartRows.length).toFixed(2)},${statPointY(statMetric(row, key), max).toFixed(2)}`)
    .join(" ");
}

function statDateLabel(value: any): string {
  const text = String(value || "");
  return /^\d{4}-\d{2}-\d{2}$/u.test(text) ? text.slice(5) : text || "--";
}

function statPointId(point: any): string {
  if (!point) return "";
  return `${String(point.seriesKey || "")}:${String(point.row?.date || point.index || "")}`;
}

function statPointFor(row: any, index: number, total: number, series: AnyRecord): AnyRecord {
  const value = statMetric(row, series.key);
  return {
    ...series,
    row,
    index,
    value,
    valueLabel: series.format(value),
    x: statPointX(index, total),
    y: statPointY(value, series.max),
    seriesKey: series.key,
  };
}

function taskListRank(task: any): number {
  if (taskIsUnreadTerminal(task)) return 0;
  const statusRank: Record<string, number> = { running: 1, judging: 2, retry_wait: 3, queued: 4, succeeded: 8, failed: 8, canceled: 8 };
  return statusRank[String(task?.status || "")] ?? 9;
}

function taskHasDetail(task: any): boolean {
  return Boolean(task?._detailLoaded)
    || Boolean(task?._traceSummaryLoaded)
    || (Array.isArray(task?.promptHistory) && task.promptHistory.length > 0)
    || (Array.isArray(task?.transcript) && task.transcript.length > 0)
    || (Array.isArray(task?.output) && task.output.length > 0)
    || (Array.isArray(task?.events) && task.events.length > 0);
}

function taskNeedsFullDetail(task: any): boolean {
  if (!task) return false;
  if (task?._traceSummaryLoaded === true) return false;
  return task?.summaryOnly === true || task?._metaLoaded !== true;
}

function taskHasFullMetadata(task: any): boolean {
  return Boolean(task?._metaLoaded) || task?.summaryOnly === false;
}

function preferLongerText(existingTask: any, patch: AnyRecord, key: string): string {
  const existingText = String(existingTask?.[key] || "");
  const incomingText = String(patch?.[key] || "");
  return existingText.length > incomingText.length ? existingText : incomingText;
}

function preferRicherArray(existingTask: any, patch: AnyRecord, key: string): any[] {
  const existingRows = Array.isArray(existingTask?.[key]) ? existingTask[key] : [];
  const incomingRows = Array.isArray(patch?.[key]) ? patch[key] : [];
  if (incomingRows.length === 0 && existingRows.length > 0) return existingRows;
  return existingRows.length > incomingRows.length ? existingRows : incomingRows;
}

function mergeTaskPatch(existingTask: any, patch: AnyRecord): AnyRecord {
  const incomingSummary = patch?.summaryOnly === true && taskHasFullMetadata(existingTask);
  const merged: AnyRecord = { ...existingTask, ...patch };
  if (!incomingSummary) return merged;
  for (const key of ["prompt", "basePrompt", "displayPrompt", "finalResponse"]) {
    merged[key] = preferLongerText(existingTask, patch, key);
  }
  for (const key of ["promptHistory", "attempts", "output", "events"]) {
    merged[key] = preferRicherArray(existingTask, patch, key);
  }
  if (existingTask?.referenceInjection?.items && !patch?.referenceInjection?.items) merged.referenceInjection = existingTask.referenceInjection;
  if (existingTask?.referenceInjectionSummary && !patch?.referenceInjectionSummary) merged.referenceInjectionSummary = existingTask.referenceInjectionSummary;
  merged.summaryOnly = existingTask?.summaryOnly === false ? false : patch.summaryOnly;
  merged._metaLoaded = existingTask?._metaLoaded;
  merged._detailLoaded = existingTask?._detailLoaded;
  merged._transcriptComplete = existingTask?._transcriptComplete;
  merged._transcriptPreview = Object.prototype.hasOwnProperty.call(patch, "_transcriptPreview")
    ? patch._transcriptPreview
    : existingTask?._transcriptPreview;
  for (const key of ["_traceSummary", "_traceSummaryLoaded", "_traceSteps", "_traceStepsLoaded", "_traceStepsByAttempt", "_traceStepsLoadedByAttempt", "_traceStepsNextAfterSeqByAttempt", "_traceStepDetails", "_promptDetails"]) {
    if (!Object.prototype.hasOwnProperty.call(patch, key) && Object.prototype.hasOwnProperty.call(existingTask || {}, key)) {
      merged[key] = existingTask[key];
    }
  }
  return merged;
}

function overviewSelectedTask(data: any): any | null {
  const selected = data?.selected;
  const selectedTask = selected?.task && typeof selected.task === "object" ? selected.task : null;
  if (selectedTask !== null) {
    const previewOnly = Boolean(selected?.preview);
    return {
      ...selectedTask,
      transcript: Array.isArray(selected?.transcript) ? selected.transcript : [],
      _detailLoaded: Array.isArray(selected?.transcript) && selected.transcript.length > 0,
      _transcriptComplete: Boolean(!previewOnly && !selected?.hasMore && taskIsTerminal(selectedTask)),
      _transcriptPreview: previewOnly,
      _summaryLoaded: true,
    };
  }
  const first = taskRows(data)[0];
  return first ? { ...first, _summaryLoaded: true } : null;
}

function mergeTranscriptRows(existing: any[], incoming: any[]): any[] {
  const byKey = new Map<string, any>();
  for (const item of [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(incoming) ? incoming : [])]) {
    const key = `${Number(item?.seq ?? 0)}:${String(item?.kind || "message")}`;
    const previous = byKey.get(key);
    if (!previous) {
      byKey.set(key, item);
      continue;
    }
    const next = { ...previous, ...item };
    for (const [textKey, omittedKey] of [["bodyPreview", "bodyOmittedLines"], ["commandPreview", "commandOmittedLines"]] as const) {
      const previousText = String(previous?.[textKey] || "");
      const incomingText = String(item?.[textKey] || "");
      if (previousText.length > incomingText.length) {
        next[textKey] = previous[textKey];
        next[omittedKey] = previous[omittedKey];
      }
    }
    byKey.set(key, next);
  }
  return Array.from(byKey.values()).sort((left, right) => Number(left?.seq ?? 0) - Number(right?.seq ?? 0));
}

function transcriptMaxSeq(transcript: any[]): number {
  return (Array.isArray(transcript) ? transcript : []).reduce((max, item) => Math.max(max, Number(item?.seq ?? 0)), 0);
}

function transcriptResumeSeq(transcript: any[], overlapRows = 8): number {
  const seqs = Array.from(new Set((Array.isArray(transcript) ? transcript : [])
    .map((item) => Number(item?.seq ?? 0))
    .filter((seq) => Number.isFinite(seq) && seq > 0)))
    .sort((left, right) => left - right);
  if (seqs.length === 0) return 0;
  const anchor = seqs[Math.max(0, seqs.length - overlapRows)] ?? 0;
  return Math.max(0, anchor - 0.001);
}

function codexModelOptions(queue: any, currentModel: string): string[] {
  const configured = Array.isArray(queue?.codeModels) ? queue.codeModels : Array.isArray(queue?.codexModels) ? queue.codexModels : [];
  const fallback = ["gpt-5.5", "gpt-5.4-mini", "gpt-5.4", "deepseek-chat", "minimax-m2.7"];
  return Array.from(new Set([...configured, ...fallback, currentModel].map((item) => String(item || "").trim()).filter(Boolean)));
}

function codexProviderOptions(queue: any, currentProviderId: string): any[] {
  const configured = Array.isArray(queue?.executionProviders) ? queue.executionProviders : [];
  const rows = configured
    .map((item: any) => ({
      id: String(item?.id || "").trim(),
      label: String(item?.label || item?.id || "").trim(),
      defaultWorkdir: String(item?.defaultWorkdir || "").trim(),
      supportsWindowsNativeCodex: item?.supportsWindowsNativeCodex === true,
      windowsNativeDefaultWorkdir: String(item?.windowsNativeDefaultWorkdir || "").trim(),
      kind: String(item?.kind || "").trim(),
    }))
    .filter((item: any) => item.id.length > 0);
  const fallbackMain = String(queue?.mainProviderId || queue?.defaultProviderId || "D601").trim() || "D601";
  const byId = new Map<string, any>();
  for (const item of [
    ...rows,
    { id: fallbackMain, label: `${fallbackMain} (local)`, defaultWorkdir: String(queue?.defaultWorkdir || "/workspace"), supportsWindowsNativeCodex: false, windowsNativeDefaultWorkdir: "", kind: "local" },
    currentProviderId ? { id: currentProviderId, label: currentProviderId, defaultWorkdir: providerDefaultWorkdir(queue, currentProviderId), supportsWindowsNativeCodex: currentProviderId !== fallbackMain, windowsNativeDefaultWorkdir: String(queue?.windowsNativeCodexDefaultWorkdir || "/mnt/f/Work/ConStart"), kind: "" } : null,
  ].filter(Boolean) as any[]) {
    if (!byId.has(item.id)) byId.set(item.id, item);
  }
  return Array.from(byId.values());
}

function codexExecutionModeOptions(queue: any, currentMode: string): any[] {
  const configured = Array.isArray(queue?.executionModes) ? queue.executionModes : [];
  const rows = configured
    .map((item: any) => ({
      id: String(item?.id || item?.kind || "").trim(),
      label: String(item?.label || item?.id || item?.kind || "").trim(),
      description: String(item?.description || "").trim(),
      defaultWorkdir: String(item?.defaultWorkdir || "").trim(),
      requiresProvider: item?.requiresProvider === true,
      requiresWindowsCwd: item?.requiresWindowsCwd === true,
    }))
    .filter((item: any) => item.id.length > 0);
  const fallback = [
    { id: "default", label: "默认容器/本机", description: "Code Queue 所在节点用本机 Codex；远程 Provider 用执行容器 Codex。", defaultWorkdir: "", requiresProvider: false, requiresWindowsCwd: false },
    { id: "windows-native", label: "Windows 原生 Codex", description: "启动执行容器，但容器只做 stdio relay，Codex 运行在 Provider 的 Windows 宿主。", defaultWorkdir: String(queue?.windowsNativeCodexDefaultWorkdir || "/mnt/f/Work/ConStart"), requiresProvider: true, requiresWindowsCwd: true },
  ];
  const byId = new Map<string, any>();
  for (const item of [...rows, ...fallback, currentMode ? { id: currentMode, label: currentMode, description: "", defaultWorkdir: "", requiresProvider: currentMode === "windows-native", requiresWindowsCwd: currentMode === "windows-native" } : null].filter(Boolean) as any[]) {
    if (!byId.has(item.id)) byId.set(item.id, item);
  }
  return Array.from(byId.values());
}

function executionModeDefaultWorkdir(queue: any, mode: string, providerId: string): string {
  if (mode !== "windows-native") return providerDefaultWorkdir(queue, providerId);
  const option = Array.isArray(queue?.executionModes) ? queue.executionModes.find((item: any) => String(item?.id || item?.kind || "") === "windows-native") : null;
  const provider = Array.isArray(queue?.executionProviders) ? queue.executionProviders.find((item: any) => String(item?.id || "") === providerId) : null;
  return String(provider?.windowsNativeDefaultWorkdir || option?.defaultWorkdir || queue?.windowsNativeCodexDefaultWorkdir || "/mnt/f/Work/ConStart");
}

function providerDefaultWorkdir(queue: any, providerId: string): string {
  const id = String(providerId || "").trim();
  const map = queue?.defaultWorkdirByProvider && typeof queue.defaultWorkdirByProvider === "object" ? queue.defaultWorkdirByProvider : {};
  if (typeof map[id] === "string" && String(map[id]).trim().length > 0) return String(map[id]).trim();
  const option = Array.isArray(queue?.executionProviders) ? queue.executionProviders.find((item: any) => String(item?.id || "") === id) : null;
  if (typeof option?.defaultWorkdir === "string" && option.defaultWorkdir.trim().length > 0) return option.defaultWorkdir.trim();
  const mainProvider = String(queue?.mainProviderId || queue?.defaultProviderId || "D601");
  return id === mainProvider ? String(queue?.defaultWorkdir || "/workspace") : String(queue?.remoteDefaultWorkdir || "/home/ubuntu");
}

function normalizedWorkdirPath(value: any): string {
  return String(value || "").trim().replace(/\/+$/u, "") || "/";
}

function workdirRecordMatches(record: any, providerId: string, executionMode: string): boolean {
  return String(record?.providerId || "") === String(providerId || "")
    && String(record?.executionMode || "default") === String(executionMode || "default")
    && String(record?.path || "").trim().length > 0;
}

function workdirOptions(queue: any, records: any[], providerId: string, executionMode: string, cwd: string): any[] {
  const byPath = new Map<string, any>();
  const currentPath = normalizedWorkdirPath(cwd);
  const add = (pathValue: any, source: string, record: any = {}) => {
    const path = normalizedWorkdirPath(pathValue);
    if (path.length === 0 || byPath.has(path)) return;
    byPath.set(path, {
      providerId,
      executionMode,
      path,
      source,
      createdAt: record?.createdAt || "",
      updatedAt: record?.updatedAt || "",
    });
  };
  add(executionModeDefaultWorkdir(queue, executionMode, providerId), "default");
  for (const record of Array.isArray(records) ? records : []) {
    if (workdirRecordMatches(record, providerId, executionMode)) add(record.path, "saved", record);
  }
  add(cwd, "current");
  return Array.from(byPath.values()).sort((left, right) => {
    if (left.path === currentPath) return -1;
    if (right.path === currentPath) return 1;
    if (left.source === "default" && right.source !== "default") return -1;
    if (right.source === "default" && left.source !== "default") return 1;
    return left.path.localeCompare(right.path);
  });
}

function taskStepCount(task: any): number | null {
  return canonicalTaskStepCount(task);
}

function TaskCard({ task, selected, onSelect, onCopy, onReference, onMarkRead, copied, markingRead }: AnyRecord) {
  const judge = task?.lastJudge || {};
  const taskId = String(task?.id || "");
  const unread = taskIsUnreadTerminal(task);
  const updatedAt = latestTimestampValue(task?.updatedAt, taskTraceSummary(task)?.updatedAt);
  const recentUpdateLabel = `最近更新: ${fmtRelativeAge(updatedAt)}`;
  const stepState = traceStepCountState(task);
  const stepTitle = stepState.title;
  return h("article", {
    role: "button",
    tabIndex: 0,
    className: `codex-task-card ${selected ? "selected" : ""} ${unread ? "unread-terminal" : ""}`,
    onClick: onSelect,
    onKeyDown: (event: any) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        onSelect();
      }
    },
    "data-unread-terminal": unread ? "true" : "false",
    "data-testid": `codex-task-${task?.id || "unknown"}`,
  },
    unread ? h("span", { className: "codex-unread-badge", title: "待读", "aria-label": "待读", "data-testid": `codex-unread-task-${taskId || "unknown"}` }) : null,
    h("div", { className: "codex-task-card-head" },
      h("div", { className: "codex-task-status-line" },
        h(StatusBadge, { status: task?.status, title: taskStatusBadgeTitle(task) }, taskStatusBadgeText(task)),
      ),
      h("span", { className: "mono-text" }, `${task?.currentAttempt || 0}/${task?.maxAttempts || 0}`),
    ),
    h("div", { className: "codex-task-id-row" },
      h("code", { title: taskId }, taskId || "unknown"),
      h("div", { className: "codex-task-id-actions" },
        h("button", {
          type: "button",
          className: "codex-copy-id-btn",
          onClick: (event: any) => {
            event.stopPropagation();
            onReference(taskId);
          },
          "data-testid": `codex-reference-task-${taskId || "unknown"}`,
        }, "引用"),
        h("button", {
          type: "button",
          className: "codex-copy-id-btn",
          onClick: (event: any) => {
            event.stopPropagation();
            onCopy(taskId);
          },
          "data-testid": `codex-copy-task-id-${taskId || "unknown"}`,
        }, copied ? "已复制" : "复制ID"),
        unread ? h("button", {
          type: "button",
          className: "codex-copy-id-btn codex-mark-read-btn",
          disabled: Boolean(markingRead),
          onClick: (event: any) => {
            event.stopPropagation();
            onMarkRead(taskId);
          },
          "data-testid": `codex-mark-task-read-${taskId || "unknown"}`,
        }, markingRead ? "标记中" : "标为已读") : null,
      ),
    ),
    h("strong", null, shortText(taskDisplayPrompt(task, { preview: true }), 120) || "空任务"),
    h("div", { className: "codex-task-meta" },
      h("span", null, `queue=${taskQueueLabel(task)}`),
      h("span", null, `provider=${task?.providerId || "D601"}`),
      h("span", null, `mode=${task?.executionMode || "default"}`),
      h("span", null, task?.model || "--"),
      h("span", null, taskDurationLabel(task)),
    ),
    h("div", { className: "codex-task-meta codex-task-update-meta" },
      h("span", { className: `codex-task-recent-update codex-task-step-count ${stepState.state}`, title: stepTitle, "data-testid": `codex-task-step-count-${taskId || "unknown"}`, "data-step-state": stepState.state, "data-step-source": stepState.source }, traceStepCountLabel(stepState)),
      h("span", { className: "codex-task-recent-update", title: updatedAt ? `更新时间: ${fmtDate(updatedAt)}` : recentUpdateLabel, "data-testid": `codex-task-recent-update-${taskId || "unknown"}` }, recentUpdateLabel),
      h("span", null, fmtDate(updatedAt || task?.updatedAt)),
    ),
    taskPromptEditable(task) ? h("div", { className: "codex-judge-line", "data-testid": `codex-task-prompt-editable-${taskId || "unknown"}` }, "queued prompt 可编辑") : null,
    judge?.decision ? h("div", { className: "codex-judge-line" }, `judge=${judge.decision} ${Math.round(Number(judge.confidence || 0) * 100)}%`) : null,
  );
}

function TaskListSection({ title, tasks, selectedId, onSelect, onCopy, onReference, onMarkRead, copiedTaskId, markingReadTaskId, emptyText }: AnyRecord) {
  const rows = Array.isArray(tasks) ? tasks : [];
  return h("section", { className: "codex-task-section" },
    h("div", { className: "codex-task-section-head" },
      h("span", null, title),
      h("code", null, String(rows.length)),
    ),
    rows.length === 0
      ? h("p", { className: "codex-task-section-empty" }, emptyText)
      : h("div", { className: "codex-task-section-list" }, rows.map((task: any) => h(TaskCard, {
        key: task.id,
        task,
        selected: selectedId === task.id,
        onSelect: () => onSelect(task.id),
        onCopy,
        onReference,
        onMarkRead,
        copied: copiedTaskId === task.id,
        markingRead: markingReadTaskId === task.id,
      }))),
  );
}

function CodexStatsIcon() {
  return h("span", { className: "codex-stats-icon", "aria-hidden": "true" },
    h("svg", { viewBox: "0 0 36 24", focusable: "false" },
      h("path", { className: "grid", d: "M3 20.5H33M3 12.5H33M3 4.5H33" }),
      h("polyline", { className: "line tasks", points: "3,18 9,14 15,15 21,8 27,10 33,4" }),
      h("polyline", { className: "line retry", points: "3,20 9,17 15,18 21,13 27,14 33,9" }),
    ),
  );
}

function LivenessMetric({ label, value, hint, tone }: AnyRecord) {
  return h("div", { className: `codex-liveness-metric ${tone || ""}` },
    h("span", null, label),
    h("strong", null, value ?? "--"),
    hint ? h("code", null, hint) : null,
  );
}

function CodeQueueLivenessPanel({ diagnostics, queue, onRaw }: AnyRecord) {
  const state = String(diagnostics?.state || diagnostics?.health || "unknown");
  const oaPublisher = objectRecord(diagnostics?.oaPublisher);
  const reasons = stringArray(diagnostics?.reasons).slice(0, 3);
  const heartbeatRiskTaskIds = diagnosticsHeartbeatRiskTaskIds(diagnostics);
  const splitBrainLive = splitBrainLiveDiagnostics(diagnostics);
  const effectiveLiveness = diagnosticsEffectiveLiveness(diagnostics);
  const recommendedAction = String(diagnostics?.recommendedAction || (heartbeatRiskTaskIds.length > 0 ? "investigate-heartbeat-risk" : splitBrainLive ? "continue-supervision" : effectiveLiveness === "degraded" ? "observe-degraded" : "none"));
  const livenessText = String(splitBrainLive
    ? "控制面/执行面观测分裂，但 heartbeat/trace 新鲜，继续监督。"
    : heartbeatRiskTaskIds.length > 0
      ? "存在 expired/missing/stale heartbeat 风险，请先确认执行面状态。"
      : diagnostics?.livenessSummary || (effectiveLiveness === "degraded"
          ? "Diagnostics are degraded; inspect heartbeat, trace, and OA progress together."
          : "Execution diagnostics are healthy."));
  const tone = diagnosticsTone(diagnostics);
  const stateLabel = splitBrainLive ? "split-brain live" : state;
  return h(Panel, {
    title: "执行活性",
    eyebrow: `${String(diagnostics?.executionStateSource || queue?.executionStateSource || "unknown")} / ${String(diagnostics?.controlPlane || "code-queue")}`,
    summary: h("div", { className: "codex-trace-status" },
      h("span", { className: `codex-trace-status-chip liveness ${tone}` }, h("b", null, "状态"), stateLabel),
      h("span", { className: `codex-trace-status-chip liveness ${tone}` }, h("b", null, "liveness"), effectiveLiveness),
      h("span", { className: "codex-trace-status-chip" }, h("b", null, "DB active"), String(diagnostics?.databaseActiveTaskCount ?? queue?.databaseActiveTaskCount ?? 0)),
      h("span", { className: "codex-trace-status-chip" }, h("b", null, "scheduler slots"), String(diagnostics?.schedulerActiveRunSlotCount ?? queue?.activeRunSlotCount ?? 0)),
      h("span", { className: "codex-trace-status-chip" }, h("b", null, "heartbeat"), `${stringArray(diagnostics?.heartbeatFreshTaskIds).length} fresh / ${stringArray(diagnostics?.heartbeatExpiredTaskIds).length} expired`),
      oaPublisher ? h("span", { className: "codex-trace-status-chip" }, h("b", null, "OA"), `${Number(oaPublisher.pending || 0)} pending${oaPublisher.lastError ? " / error" : ""}`) : null,
    ),
    actions: h(RawButton, { title: "Code Queue Execution Diagnostics", data: diagnostics, onOpen: onRaw, testId: "raw-code-queue-execution-diagnostics" }),
    className: "codex-liveness-panel",
  },
    h("div", { className: "codex-liveness-grid", "data-testid": "codex-liveness-diagnostics" },
      h(LivenessMetric, { tone, label: "健康状态", value: stateLabel, hint: recommendedAction }),
      h(LivenessMetric, { tone, label: "Effective liveness", value: effectiveLiveness, hint: livenessText }),
      h(LivenessMetric, { label: "PostgreSQL active", value: String(diagnostics?.databaseActiveTaskCount ?? queue?.databaseActiveTaskCount ?? 0), hint: compactIdList(diagnostics?.databaseActiveTaskIds ?? queue?.databaseActiveTaskIds) }),
      h(LivenessMetric, { label: "Scheduler active", value: String(diagnostics?.schedulerActiveRunSlotCount ?? queue?.activeRunSlotCount ?? 0), hint: compactIdList(diagnostics?.schedulerActiveTaskIds ?? queue?.activeTaskIds) }),
      h(LivenessMetric, { label: "Fresh heartbeat", value: String(stringArray(diagnostics?.heartbeatFreshTaskIds).length), hint: compactIdList(diagnostics?.heartbeatFreshTaskIds) }),
      h(LivenessMetric, { tone: heartbeatRiskTaskIds.length > 0 ? "failed" : splitBrainLive ? "degraded-live" : "", label: "Heartbeat risk", value: String(heartbeatRiskTaskIds.length), hint: heartbeatRiskTaskIds.length > 0 ? compactIdList(heartbeatRiskTaskIds) : splitBrainLive ? "fresh heartbeat/trace: keep supervising" : "--" }),
      h(LivenessMetric, { tone: stringArray(diagnostics?.traceGapNotStaleTaskIds).length > 0 ? "warn" : "", label: "Trace gap", value: String(stringArray(diagnostics?.traceGapTaskIds).length), hint: compactIdList(diagnostics?.traceGapNotStaleTaskIds) }),
      h(LivenessMetric, { tone: stringArray(diagnostics?.staleRecoveryCandidateTaskIds).length > 0 ? "failed" : "", label: "Stale candidates", value: String(stringArray(diagnostics?.staleRecoveryCandidateTaskIds).length), hint: compactIdList(diagnostics?.staleRecoveryCandidateTaskIds) }),
      h(LivenessMetric, { label: "Last scheduler heartbeat", value: fmtRelativeAge(diagnostics?.lastSchedulerHeartbeatAt), hint: String(diagnostics?.lastSchedulerHeartbeatAt || "--") }),
      h(LivenessMetric, { label: "Last agent event", value: fmtRelativeAge(diagnostics?.lastObservedAgentEventAt), hint: String(diagnostics?.lastObservedAgentEventAt || "--") }),
      h(LivenessMetric, { label: "Last trace persist", value: fmtRelativeAge(diagnostics?.lastPersistedTraceAt), hint: String(diagnostics?.lastPersistedTraceAt || "--") }),
      h(LivenessMetric, { tone: oaPublisher?.lastError ? "warn" : "", label: "OA publisher", value: `${Number(oaPublisher?.pending || 0)} pending`, hint: oaPublisher?.lastError ? shortText(oaPublisher.lastError, 90) : "ok" }),
    ),
    h("div", { className: `codex-liveness-advisory ${tone}` },
      h("b", null, splitBrainLive ? "Observing split" : heartbeatRiskTaskIds.length > 0 ? "Heartbeat risk" : "Liveness note"),
      h("span", null, livenessText),
      h("code", null, recommendedAction),
    ),
    reasons.length > 0 ? h("div", { className: "codex-liveness-reasons" }, reasons.map((reason: string) => h("span", { key: reason }, reason))) : null,
  );
}

function CodexStatsPanel({ stats, queueName: activeQueueName, onRaw }: AnyRecord) {
  const rows = taskStatisticsRows(stats);
  const totals = taskStatisticsTotals(stats, rows);
  const latest = rows.at(-1) || {};
  const executedMax = statMetricMax(rows, "executedTasks");
  const retryMax = statMetricMax(rows, "retryAttempts");
  const durationMax = statMetricMax(rows, "avgDurationMs");
  const hasRows = rows.length > 0;
  const statsRange = objectRecord(stats?.range) || {};
  const statsState = taskStatisticsState(stats, rows, totals);
  const statsStateLabel = String(statsState.label || "");
  const statsStateReason = String(statsState.reason || "");
  const chartDescription = statsState.state === "ready" || statsState.state === "degraded"
    ? "将鼠标悬停到曲线数据点查看明细，点击数据点可固定。"
    : statsStateReason || "等待统计数据。";
  const [hoveredStatPoint, setHoveredStatPoint] = useState(null);
  const [pinnedStatPoint, setPinnedStatPoint] = useState(null);
  const maxLabelParts: string[] = [];
  if (executedMax > 0) maxLabelParts.push(`tasks ${executedMax}`);
  if (retryMax > 0) maxLabelParts.push(`retry ${retryMax}`);
  if (durationMax > 0) maxLabelParts.push(`avg ${fmtDuration(durationMax)}`);
  const statSeries = [
    { key: "executedTasks", className: "tasks", label: "执行任务", max: executedMax, format: (value: any) => `${countNumber(value)} tasks` },
    { key: "retryAttempts", className: "retry", label: "重试次数", max: retryMax, format: (value: any) => `${countNumber(value)} retries` },
    { key: "avgDurationMs", className: "duration", label: "平均耗时", max: durationMax, format: (value: any) => fmtDuration(value) },
  ];
  const activeStatPoint = hoveredStatPoint || pinnedStatPoint;
  const activeStatPointId = statPointId(activeStatPoint);
  const activeDate = String(activeStatPoint?.row?.date || "");
  const activeTooltipStyle = activeStatPoint ? {
    left: `${Math.max(8, Math.min(92, (Number(activeStatPoint.x) / statChartWidth) * 100))}%`,
    top: `${Math.max(14, Math.min(86, (Number(activeStatPoint.y) / statChartHeight) * 100))}%`,
  } : undefined;
  useEffect(() => {
    setHoveredStatPoint(null);
    setPinnedStatPoint(null);
  }, [activeQueueName, statsRange.startDate, statsRange.endDate, rows.length]);
  const activateStatPoint = (point: AnyRecord) => {
    setHoveredStatPoint(point);
  };
  const togglePinnedStatPoint = (point: AnyRecord) => {
    const pointId = statPointId(point);
    setPinnedStatPoint((current: any) => statPointId(current) === pointId ? null : point);
    setHoveredStatPoint(point);
  };
  const statPointNodes = statSeries.flatMap((series) => rows.map((row: any, index: number) => {
    const point = statPointFor(row, index, rows.length, series);
    const pointId = statPointId(point);
    const active = activeStatPointId === pointId;
    const date = String(row?.date || `day-${index}`);
    const ariaLabel = `${statDateLabel(date)} ${series.label}: ${point.valueLabel}`;
    return h("g", {
      key: `${series.key}-${date}`,
      className: `stat-point-group ${series.className} ${active ? "active" : ""}`,
      role: "button",
      tabIndex: 0,
      "aria-label": ariaLabel,
      "data-testid": `codex-stats-point-${series.className}-${date}`,
      onMouseEnter: () => activateStatPoint(point),
      onFocus: () => activateStatPoint(point),
      onClick: () => togglePinnedStatPoint(point),
      onKeyDown: (event: any) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          togglePinnedStatPoint(point);
        }
      },
    },
      h("circle", { className: "stat-hit-point", cx: point.x, cy: point.y, r: 13 }),
      h("circle", { className: `stat-point ${series.className} ${active ? "active" : ""}`, cx: point.x, cy: point.y, r: active ? 5.6 : 4.2 }),
    );
  }));
  return h(Panel, {
    title: "统计曲线",
    eyebrow: `Daily task stats / ${activeQueueName}`,
    className: `codex-stats-panel ${statsState.state}`,
    summary: h("span", null, `${statDateLabel(statsRange.startDate)} -> ${statDateLabel(statsRange.endDate)} · ${displayTimeZone()} · ${statsStateLabel}`),
    actions: objectRecord(stats) ? h(RawButton, { title: "Code Queue Stats", data: stats, onOpen: onRaw, testId: "raw-codex-stats" }) : null,
  },
    h("div", { className: "codex-stats-hero", "data-testid": "codex-stats-panel", "data-stats-state": statsState.state, "data-stats-degraded": statsState.degraded === true ? "true" : "false" },
      h(CodexStatsIcon),
      h("div", null,
        h("strong", null, `${countNumber(totals.executedTasks)} tasks / ${countNumber(totals.retryAttempts)} retries`),
        h("span", null, `平均完成耗时 ${fmtDuration(totals.avgDurationMs ?? undefined)} · 终态 ${countNumber(totals.completedTasks)} 个`),
      ),
    ),
    statsState.degraded === true ? h("div", { className: `codex-stats-diagnostic ${statsState.state}`, "data-testid": "codex-stats-diagnostic" },
      h("b", null, statsStateLabel),
      h("span", null, statsStateReason),
      stats?.source ? h("code", null, `source=${String(stats.source)}`) : null,
    ) : null,
    h("div", { className: `codex-stats-chart ${hasRows ? "has-data" : "no-data"}`, "data-testid": "codex-stats-chart", "data-empty": hasRows ? "false" : "true", onMouseLeave: () => setHoveredStatPoint(null) },
      h("svg", { viewBox: `0 0 ${statChartWidth} ${statChartHeight}`, preserveAspectRatio: "none", role: "img", "aria-label": "Code Queue daily task statistics" },
        h("line", { className: "axis", x1: statChartPaddingX, x2: statChartWidth - statChartPaddingX, y1: statChartBaselineY, y2: statChartBaselineY }),
        h("line", { className: "grid", x1: statChartPaddingX, x2: statChartWidth - statChartPaddingX, y1: statChartTopY + statChartValueHeight / 2, y2: statChartTopY + statChartValueHeight / 2 }),
        h("line", { className: "grid", x1: statChartPaddingX, x2: statChartWidth - statChartPaddingX, y1: statChartTopY, y2: statChartTopY }),
        h("polyline", { className: "stat-line tasks", points: statLinePoints(rows, "executedTasks", executedMax) }),
        h("polyline", { className: "stat-line retry", points: statLinePoints(rows, "retryAttempts", retryMax) }),
        h("polyline", { className: "stat-line duration", points: statLinePoints(rows, "avgDurationMs", durationMax) }),
        activeStatPoint ? h("g", { className: "stat-cursor-layer", "data-testid": "codex-stats-active-point" },
          h("line", { className: "stat-cursor", x1: activeStatPoint.x, x2: activeStatPoint.x, y1: statChartTopY, y2: statChartBaselineY }),
          h("circle", { className: `stat-point-active ${activeStatPoint.className}`, cx: activeStatPoint.x, cy: activeStatPoint.y, r: 8 }),
        ) : null,
        h("g", { className: "stat-point-layer" }, statPointNodes),
      ),
      activeStatPoint ? h("div", { className: "codex-stats-tooltip active", style: activeTooltipStyle, "data-testid": "codex-stats-tooltip" },
        h("b", null, statDateLabel(activeStatPoint.row?.date)),
        h("span", null, `${activeStatPoint.label} · ${activeStatPoint.valueLabel}`),
          h("code", null, `${countNumber(activeStatPoint.row?.executedTasks)} exec / ${countNumber(activeStatPoint.row?.retryAttempts)} retry / ${fmtDuration(activeStatPoint.row?.avgDurationMs ?? undefined)}`),
      ) : null,
      !hasRows ? h("div", { className: "codex-stats-chart-empty", "data-testid": "codex-stats-empty" },
        h("strong", null, statsStateLabel),
        h("span", null, chartDescription),
      ) : null,
      h("div", { className: "codex-stats-legend" },
        h("span", { className: "tasks" }, "执行任务"),
        h("span", { className: "retry" }, "重试次数"),
        h("span", { className: "duration" }, "平均耗时"),
      ),
      h("div", { className: "codex-stats-scale" },
        h("span", null, statDateLabel(rows[0]?.date)),
        h("span", null, maxLabelParts.join(" · ") || "暂无峰值"),
        h("span", null, statDateLabel(rows.at(-1)?.date)),
      ),
      h("div", { className: `codex-stats-focus ${activeStatPoint ? "active" : ""}`, "data-testid": "codex-stats-focus" },
        activeStatPoint ? h(React.Fragment, null,
          h("div", null,
            h("strong", null, statDateLabel(activeStatPoint.row?.date)),
            h("span", null, `${activeStatPoint.label} · ${activeStatPoint.valueLabel}`),
          ),
          h("div", { className: "codex-stats-focus-metrics" },
            h("code", null, `${countNumber(activeStatPoint.row?.executedTasks)} exec`),
            h("code", null, `${countNumber(activeStatPoint.row?.retryAttempts)} retry`),
            h("code", null, fmtDuration(activeStatPoint.row?.avgDurationMs ?? undefined)),
          ),
        ) : h("span", null, chartDescription),
      ),
    ),
    h("div", { className: "codex-stats-summary-grid" },
      h("article", null, h("span", null, "今日执行"), h("strong", null, String(countNumber(latest.executedTasks))), h("code", null, statDateLabel(latest.date))),
      h("article", null, h("span", null, "今日重试"), h("strong", null, String(countNumber(latest.retryAttempts))), h("code", null, `累计 ${countNumber(totals.retryAttempts)}`)),
      h("article", null, h("span", null, "平均耗时"), h("strong", null, fmtDuration(totals.avgDurationMs ?? undefined)), h("code", null, `${countNumber(totals.durationSamples)} samples`)),
    ),
    h("div", { className: "codex-stats-daily-list", "data-testid": "codex-stats-daily-list" },
      rows.length === 0 ? h("div", { className: `codex-stats-daily-row empty ${statsState.state}`, "data-testid": "codex-stats-day-empty" },
        h("span", null, statsStateLabel),
        h("b", null, statsStateReason),
        h("b", null, "--"),
        h("code", null, statsState.state === "empty" ? "true empty" : "diagnostic"),
      ) : rows.slice(-7).map((row: any) => h("div", { key: String(row?.date || ""), className: `codex-stats-daily-row ${activeDate === String(row?.date || "") ? "active" : ""}`, "data-testid": `codex-stats-day-${String(row?.date || "unknown")}` },
        h("span", null, statDateLabel(row?.date)),
        h("b", null, `${countNumber(row?.executedTasks)} exec`),
        h("b", null, `${countNumber(row?.retryAttempts)} retry`),
        h("code", null, fmtDuration(row?.avgDurationMs ?? undefined)),
      )),
    ),
  );
}

function TaskQueueMoveControl({ task, queueRows, busy, frozen, onMove }: AnyRecord) {
  const taskId = String(task?.id || "");
  const currentQueue = taskQueueLabel(task);
  const [targetQueue, setTargetQueue] = useState(currentQueue);
  useEffect(() => {
    setTargetQueue(currentQueue);
  }, [taskId, currentQueue]);
  const disabled = frozen || !taskId || busy || ["running", "judging", "retry_wait"].includes(String(task?.status || ""));
  return h("div", { className: "codex-task-move-control", "data-testid": "codex-task-queue-move-control" },
    h("label", null, "任务 queue",
      h("select", {
        value: targetQueue,
        disabled: frozen || !taskId || busy,
        onChange: (event: any) => setTargetQueue(String(event.target.value || currentQueue)),
        "data-testid": "codex-task-queue-move-select",
      },
        queueRows.map((row: any) => h("option", { key: String(row?.id || ""), value: String(row?.id || "") }, queueOptionLabel(row))),
      ),
    ),
    h("button", {
      type: "button",
      className: "ghost-btn",
      disabled: disabled || targetQueue === currentQueue,
      onClick: () => onMove(targetQueue),
      title: frozen ? "旧 Code Queue 任务移动已冻结" : disabled ? "运行中 / judging / retry_wait 的任务不能移动；请先打断或等当前 turn 结束" : "移动已创建任务到另一个 queue",
      "data-testid": "codex-task-queue-move-button",
    }, "移动"),
  );
}

function listPreview(items: any[], limit = 4): string {
  const rows = (Array.isArray(items) ? items : []).map((item) => String(item || "").trim()).filter(Boolean);
  if (rows.length === 0) return "--";
  const shown = rows.slice(0, limit).join(" / ");
  return rows.length > limit ? `${shown} +${rows.length - limit}` : shown;
}

function ProgressivePromptBlock({ task, loading, onLoadPromptPart, testId = "codex-initial-prompt-full", textTestId = "codex-initial-prompt-full-text", baseTextTestId = "codex-initial-prompt-base" }: AnyRecord) {
  const promptSummary = taskPromptSummary(task);
  const promptDetails = taskPromptDetails(task);
  const basePrompt = taskBasePromptText(task).trimEnd();
  const fullPrompt = String(promptDetails.full?.text || "");
  const hasReference = taskHasReferencePrompt(task);
  const fullChars = Number(promptSummary.promptChars || task?.promptChars || fullPrompt.length);
  const baseLines = Number(promptSummary.basePromptLines || promptLineCount(basePrompt));
  const fullLines = Number(promptSummary.promptLines || promptLineCount(fullPrompt));
  return h("section", { className: "codex-progressive-card codex-progressive-prompt", "data-testid": "codex-progressive-prompt" },
    h("div", { className: "codex-progressive-card-head" },
      h("span", { className: "codex-output-channel" }, "Prompt"),
      h("strong", null, "Submitted prompt / 原始用户 prompt"),
      h("code", null, `${baseLines || promptLineCount(basePrompt)} lines / ${basePrompt.length} chars`),
    ),
    h("pre", { className: "codex-prompt-full", "data-testid": baseTextTestId }, basePrompt || "空 prompt"),
    hasReference ? h("details", {
      className: "codex-reference-injection codex-progressive-full-prompt",
      "data-testid": testId,
      onToggle: (event: any) => {
        if (event.currentTarget?.open && !fullPrompt) onLoadPromptPart?.("full");
      },
    },
      h("summary", null,
        h("span", null, "引用注入已折叠，点击按需拉取最终进入 Code agent 的完整 prompt"),
        h("code", null, fullPrompt
          ? `${fullLines || promptLineCount(fullPrompt)} lines / ${fullPrompt.length} chars`
          : `${Number.isFinite(fullChars) && fullChars > 0 ? fullChars : "--"} chars`),
      ),
      h("pre", { className: "codex-prompt-full codex-prompt-final-full", "data-testid": textTestId }, fullPrompt || (loading ? "正在按需拉取完整 prompt..." : "展开后将只请求 full prompt，不拉取完整 transcript。")),
    ) : null,
  );
}

function ProgressiveExecutionSummary({ task, attempt, attemptIndex, traceStepsLoading, traceStepLoading, onLoadSteps, onLoadStep, testId = "codex-execution-summary" }: AnyRecord) {
  const steps = coalesceTraceSteps(taskTraceSteps(task, attemptIndex));
  const execution = canonicalExecutionSummary(attemptExecutionSummary(task, attempt));
  const stats = attempt ? attemptOaTraceStats(task, attempt) : taskOaTraceStats(task);
  const stepDetails = taskTraceStepDetails(task);
  const stepsLoaded = taskTraceStepsLoaded(task, attemptIndex);
  const taskId = String(task?.id || "");
  const stepsLoading = Boolean(traceStepsLoading?.[traceStepsLoadingKey(taskId, attemptIndex)]);
  const errorCount = statCount(stats?.errorCount);
  const fallbackStepCount = rawTraceStepCountFallback(
    steps.length > 0 ? steps.length : null,
    attempt?.stepCount,
    attempt?.execution?.stepCount,
    execution.traceLineCount,
    execution.stepCount,
    attempt?.outputCount,
  );
  const statsStepCount = statCount(stats?.stepCount ?? stats?.llmStepCount);
  const toolCount = statsStepCount ?? fallbackStepCount;
  const readCount = statCount(stats?.readCount);
  const editCount = statCount(stats?.editCount);
  const runCount = statCount(stats?.runCount);
  const stepCount = statsStepCount ?? fallbackStepCount;
  const countSource = statsStepCount !== null ? "oa-event-flow" : fallbackStepCount !== null ? "raw-trace" : taskIsActive(task) ? "syncing" : "unavailable";
  const toolsLabel = toolCount === null ? (countSource === "syncing" ? "sync" : "N/A") : String(toolCount);
  const stepLabel = stepCount === null ? (countSource === "syncing" ? "sync" : "N/A") : `${stepCount}${countSource === "raw-trace" ? " raw" : ""}`;
  const stepTitle = countSource === "oa-event-flow"
    ? "STEP 来自 OA Event Flow 统计中心"
    : countSource === "raw-trace"
      ? "OA STEP 统计不可用，当前显示 raw trace fallback 行数"
      : countSource === "syncing"
        ? "STEP 统计同步中；展开后会按需读取当前 attempt trace"
        : "当前 attempt 没有可用 STEP 统计";
  const editedFiles = Array.isArray(execution.editedFiles) ? execution.editedFiles : [];
  const commands = Array.isArray(execution.commands) ? execution.commands : [];
  const synthetic = isSyntheticAttemptSegment(attempt, attemptIndex);
  const labelSuffix = synthetic ? ` · ${String(attempt?.label || "recovered thread execution")}` : attemptIndex ? ` #${attemptIndex}` : "";
  const updatedAt = attemptExecutionUpdatedAt(task, attempt, attemptIndex, execution);
  const recentUpdateLabel = `最近更新: ${fmtRelativeAge(updatedAt)}`;
  const running = attemptExecutionIsRunning(task, attempt, attemptIndex);
  return h("details", {
    className: `codex-progressive-card codex-execution-summary ${running ? "running" : ""}`,
    "data-testid": testId,
    "data-attempt-index": attemptDataIndex(attemptIndex),
    "data-running": running ? "true" : "false",
    onToggle: (event: any) => {
      if (event.currentTarget?.open && !stepsLoaded) onLoadSteps?.(attemptIndex);
    },
  },
    h("summary", null,
      h("div", { className: "codex-progressive-card-head" },
        h("span", { className: "codex-output-channel" }, "Summary"),
        h("strong", null, `执行过程摘要${labelSuffix}`),
        running ? h("span", { className: "codex-summary-running-pill", "data-testid": `${testId}-running` }, "执行中") : null,
        h("code", { title: `${updatedAt ? `最近更新: ${fmtDate(updatedAt)}` : recentUpdateLabel}；${stepTitle}` },
          `${fmtDuration(execution.durationMs ?? execution.totalElapsedMs)} / ${toolsLabel} tools / ${recentUpdateLabel}`),
      ),
      h("div", { className: "codex-execution-digest" },
        h("span", { title: "来自 OA Event Flow 统计中心" }, `read ${readCount === null ? "--" : readCount}`),
        h("span", { title: "来自 OA Event Flow 统计中心" }, `edit ${editCount === null ? "--" : editCount}`),
        h("span", { title: "来自 OA Event Flow 统计中心" }, `run ${runCount === null ? "--" : runCount}`),
        h("span", { title: stepTitle, "data-testid": `${testId}-step-count`, "data-step-state": countSource }, `STEP ${stepLabel}`),
        errorCount !== null && errorCount > 0 ? h("span", { className: "codex-execution-error-pill", "data-testid": `${testId}-error-count` }, `Error ${errorCount}`) : null,
      ),
    ),
    h("div", { className: "codex-execution-digest expanded" },
      h("span", null, `修改文件：${listPreview(editedFiles, 6)}`),
      h("span", null, `执行命令：${listPreview(commands, 4)}`),
    ),
    steps.length === 0
      ? h("div", { className: "codex-output-empty" }, stepsLoading ? "正在按需拉取步骤 summary..." : "展开后将只请求执行步骤 summary，不拉取单步骤全量。")
      : h("div", { className: "codex-trace-step-list" }, steps.map((step: any) => {
        const seq = String(step?.seq ?? "");
        const detail = stepDetails[seq];
        const detailLoading = Boolean(traceStepLoading?.[traceStepLoadingKey(taskId, seq)]);
        const summaryLines = Array.isArray(step?.summaryLines) ? step.summaryLines.slice(0, 4) : [];
        const inlineSummary = summaryLines.find((line: any) => String(line || "").trim().length > 0);
        return h("details", {
          key: seq || `${step?.title}-${step?.at}`,
          className: `codex-trace-step ${String(step?.kind || "message")} ${traceStepIsError(step) ? "error" : ""}`,
          "data-testid": `codex-trace-step-${seq || "unknown"}`,
          onToggle: (event: any) => {
            if (event.currentTarget?.open && !detail) onLoadStep?.(step?.seq);
          },
        },
          h("summary", null,
            h("span", { className: "codex-output-channel" }, traceStepKindLabel(step?.kind)),
            h("strong", null, String(step?.title || "Trace step")),
            step?.status ? h("code", null, String(step.status)) : null,
            inlineSummary ? h("span", { className: "codex-trace-step-inline-summary", title: String(inlineSummary) }, String(inlineSummary)) : null,
            h("time", null, fmtDate(step?.at)),
          ),
          h("div", { className: "codex-trace-step-summary" },
            summaryLines.length > 0 ? summaryLines.map((line: any, index: number) => h("pre", { key: `${seq}-${index}` }, String(line || ""))) : h("span", null, "无 summary"),
          ),
          detail?.line
            ? h(TraceView, {
              items: [detail.line],
              autoScroll: false,
              loading: false,
              hasDetail: true,
              emptyText: "无步骤详情",
              testId: `codex-trace-step-detail-${seq || "unknown"}`,
              className: "codex-transcript codex-step-detail-transcript",
              collapseTools: false,
            })
            : h("div", { className: "codex-output-empty" }, detailLoading ? "正在按需拉取这个步骤的全量数据..." : "展开后将只请求这个单步骤的全量数据。"),
        );
      })),
  );
}

function traceStepKindLabel(kind: any): string {
  const value = String(kind || "");
  if (value === "ran") return "Ran";
  if (value === "explored") return "Explored";
  if (value === "edited") return "Edited";
  if (value === "error") return "Error";
  if (value === "system") return "System";
  return "Message";
}

function ProgressiveFinalResponse({ task, attempt, attemptIndex, testId = "codex-final-response" }: AnyRecord) {
  const text = attemptFinalResponseText(task, attempt);
  if (text.length === 0) return null;
  const chars = Number(attempt?.finalResponseChars || text.length);
  const labelSuffix = attemptIndex ? ` #${attemptIndex}` : "";
  return h("section", { className: "codex-progressive-card codex-final-response", "data-testid": testId, "data-attempt-index": attemptDataIndex(attemptIndex) },
    h("div", { className: "codex-progressive-card-head" },
      h("span", { className: "codex-output-channel" }, "Final"),
      h("strong", null, `最终 response${labelSuffix}`),
      h("code", null, `${Number.isFinite(chars) ? chars : text.length} chars`),
    ),
    h(MarkdownBody, { markdown: text, className: "codex-transcript-body codex-markdown", testId: `${testId}-markdown` }),
  );
}

function ProgressiveJudge({ task, attempt, attemptIndex, testId = "codex-progressive-judge" }: AnyRecord) {
  const judge = attemptJudge(task, attempt, attemptIndex);
  if (!judge?.decision) return null;
  const labelSuffix = attemptIndex ? ` #${attemptIndex}` : "";
  return h("section", { className: "codex-progressive-card codex-progressive-judge", "data-testid": testId, "data-attempt-index": attemptDataIndex(attemptIndex) },
    h("div", { className: "codex-progressive-card-head" },
      h("span", { className: "codex-output-channel" }, "Judge"),
      h("strong", null, `完成判定${labelSuffix}`),
      h("code", null, `${judge.decision} ${Math.round(Number(judge.confidence || 0) * 100)}%`),
    ),
    h("div", { className: "codex-judge-card", "data-testid": `${testId}-card` },
      h(StatusBadge, { status: judge.decision }, judge.decision),
      h("strong", null, `${Math.round(Number(judge.confidence || 0) * 100)}% confidence`),
      h("p", { "data-testid": `${testId}-reason` }, judge.reason || "--"),
      h(JudgeFailureDetails, { judge, testId: `${testId}-failure-details` }),
      judge.continuePrompt ? h("pre", { "data-testid": `${testId}-continue-prompt` }, String(judge.continuePrompt || "")) : null,
    ),
  );
}

function ProgressiveJudgeFeedbackPrompt({ task, attempt, attemptIndex, loading, onLoadPromptPart, testId = "codex-judge-feedback-prompt" }: AnyRecord) {
  const feedback = attemptFeedbackPrompt(task, attempt, attemptIndex);
  if (feedback === null) return null;
  const detailKey = feedbackPromptDetailKey(attemptIndex);
  const promptDetails = taskPromptDetails(task);
  const detail = promptDetails[detailKey];
  const detailText = String(detail?.text || "").trimEnd();
  const preview = String(feedback.preview || feedback.text || "").trimEnd();
  const visibleText = detailText || String(feedback.text || "").trimEnd();
  const chars = Number(detail?.chars || feedback.chars || visibleText.length || preview.length);
  const lines = Number(detail?.lines || feedback.lines || promptLineCount(visibleText || preview));
  const forAttempt = detail?.forAttempt || feedback.forAttempt || Number(attemptIndex || 0) + 1;
  return h("details", {
    className: "codex-progressive-card codex-judge-feedback-prompt",
    "data-testid": testId,
    "data-attempt-index": attemptDataIndex(attemptIndex),
    onToggle: (event: any) => {
      if (event.currentTarget?.open && !detailText) onLoadPromptPart?.("feedback", attemptIndex);
    },
  },
    h("summary", null,
      h("div", { className: "codex-progressive-card-head" },
        h("span", { className: "codex-output-channel" }, "Prompt"),
        h("strong", null, `judge feedback prompt #${attemptIndex} -> #${forAttempt}`),
        h("code", null, `${lines || "--"} lines / ${Number.isFinite(chars) ? chars : preview.length} chars`),
      ),
      h("p", { className: "codex-feedback-preview", "data-testid": `${testId}-preview` }, preview || "展开后按需拉取 judge feedback prompt。"),
    ),
    h("pre", { className: "codex-prompt-full codex-feedback-full", "data-testid": `${testId}-text` },
      visibleText || (loading ? "正在按需拉取 judge feedback prompt..." : "展开后将只请求这一次 judge feedback prompt。")),
  );
}

function ProgressiveAttemptCycle({ task, attempt, position, loading, traceStepsLoading, traceStepLoading, onLoadPromptPart, onLoadSteps, onLoadStep }: AnyRecord) {
  const attemptIndex = attemptSegmentIndex(attempt, position);
  const current = attemptIsActiveCurrent(task, attemptIndex);
  const first = position === 0 && !current;
  const synthetic = isSyntheticAttemptSegment(attempt, attemptIndex);
  const title = synthetic ? String(attempt?.label || "Recovered thread execution") : `Attempt ${attemptIndex}`;
  return h("section", { className: "codex-attempt-cycle", "data-testid": `codex-attempt-cycle-${attemptIndex}` },
    h("div", { className: "codex-attempt-cycle-head" },
      h("span", { className: "codex-output-channel" }, title),
      h("strong", null, String(attempt?.mode || (attemptIndex <= 1 ? "initial" : "retry"))),
      attempt?.terminalStatus ? h(StatusBadge, { status: attempt.terminalStatus }, attempt.terminalStatus) : null,
      h("code", null, `${fmtDate(attempt?.startedAt)} -> ${fmtDate(attempt?.finishedAt)}`),
    ),
    h(ProgressiveExecutionSummary, {
      task,
      attempt,
      attemptIndex,
      traceStepsLoading,
      traceStepLoading,
      onLoadSteps,
      onLoadStep,
      testId: current ? "codex-execution-summary-current" : first ? "codex-execution-summary" : `codex-execution-summary-attempt-${attemptIndex}`,
    }),
    synthetic ? null : h(ProgressiveFinalResponse, {
      task,
      attempt,
      attemptIndex,
      testId: current ? "codex-final-response-current" : first ? "codex-final-response" : `codex-final-response-attempt-${attemptIndex}`,
    }),
    synthetic ? null : h(ProgressiveJudge, {
      task,
      attempt,
      attemptIndex,
      testId: current ? "codex-progressive-judge-current" : first ? "codex-progressive-judge" : `codex-progressive-judge-attempt-${attemptIndex}`,
    }),
    synthetic ? null : h(ProgressiveJudgeFeedbackPrompt, {
      task,
      attempt,
      attemptIndex,
      loading,
      onLoadPromptPart,
      testId: current ? "codex-judge-feedback-prompt-current" : first ? "codex-judge-feedback-prompt" : `codex-judge-feedback-prompt-attempt-${attemptIndex}`,
    }),
  );
}

function ProgressiveTrace({ task, loading, traceStepsLoading, traceStepLoading, onLoadPromptPart, onLoadSteps, onLoadStep }: AnyRecord) {
  if (!task) return h(EmptyState, { title: "未选择任务", text: "从左侧队列选择任务，或提交新 Codex 任务。" });
  const attempts = taskProgressiveAttempts(task);
  return h("div", { className: "codex-transcript codex-progressive-trace", "data-testid": "codex-output" },
    loading && !taskTraceSummary(task) ? h("div", { className: "codex-output-empty" }, "正在加载 Trace Summary...") : null,
    h(ProgressivePromptBlock, { task, loading, onLoadPromptPart }),
    attempts.length > 0
      ? attempts.map((attempt: any, index: number) => h(ProgressiveAttemptCycle, { key: `${attempt?.index || index + 1}-${attempt?.startedAt || index}`, task, attempt, position: index, loading, traceStepsLoading, traceStepLoading, onLoadPromptPart, onLoadSteps, onLoadStep }))
      : [
        h(ProgressiveExecutionSummary, { key: "execution", task, traceStepsLoading, traceStepLoading, onLoadSteps, onLoadStep }),
        h(ProgressiveFinalResponse, { key: "final", task }),
        h(ProgressiveJudge, { key: "judge", task }),
      ],
  );
}


function RawTranscript({ task }: AnyRecord) {
  const output = taskOutput(task);
  if (!task || output.length === 0) return h(EmptyState, { title: "暂无原始消息", text: "原始 Codex app-server 消息会保留在任务 JSON 中。" });
  return h("details", { className: "codex-raw-output" },
    h("summary", null, `原始 messages (${output.length})`),
    h("div", null,
      output.map((item: any) => h("article", { key: `${item.seq}-${item.channel}`, className: `codex-output-line ${item.channel || "system"}` },
        h("div", { className: "codex-output-meta" },
          h("span", { className: "codex-output-channel" }, channelLabel(String(item.channel || "system"))),
          h("span", null, fmtDate(item.at)),
          item.method ? h("code", null, item.method) : null,
        ),
        h("pre", null, String(item.text || "")),
      )),
      ),
  );
}

function AttemptTable({ task }: AnyRecord) {
  const attempts = taskAttempts(task).slice().reverse();
  if (attempts.length === 0) return h(EmptyState, { title: "尚无 attempt", text: "任务开始运行后，这里会记录 Codex 终态、传输中断和 stderr tail。" });
  return h("div", { className: "table-wrap codex-attempt-table" },
    h("table", null,
      h("thead", null, h("tr", null,
        h("th", null, "#"),
        h("th", null, "模式"),
        h("th", null, "终态"),
        h("th", null, "传输"),
        h("th", null, "退出"),
        h("th", null, "完成时间"),
      )),
      h("tbody", null, attempts.map((attempt: any) => h("tr", { key: `${attempt.index}-${attempt.startedAt}` },
        h("td", null, attempt.index),
        h("td", null, attempt.mode),
        h("td", null, h(StatusBadge, { status: attempt.terminalStatus || "unknown" }, attempt.terminalStatus || "unknown")),
        h("td", null, attempt.transportClosedBeforeTerminal ? h(StatusBadge, { status: "failed" }, "closed-before-terminal") : h(StatusBadge, { status: "succeeded" }, "normal")),
        h("td", null, `code=${attempt.appServerExitCode ?? "--"} signal=${attempt.appServerSignal ?? "--"}`),
        h("td", null, fmtDate(attempt.finishedAt)),
      ))),
    ),
  );
}

export function CodeQueuePage({ microservices, onRaw, apiBaseUrl = "/api", initialTasksData = null, standalone = false }: AnyRecord) {
  const service = microservices.find((item: any) => item.id === "code-queue") || null;
  const initialSelectedTask = overviewSelectedTask(initialTasksData);
  const initialSelectedId = String(initialSelectedTask?.id || "");
  const initialSessionCache = new Map<string, AnyRecord>();
  if (initialSelectedTask !== null && initialSelectedId.length > 0) {
    initialSessionCache.set(initialSelectedId, {
      task: initialSelectedTask,
      maxSeq: transcriptMaxSeq(Array.isArray(initialSelectedTask.transcript) ? initialSelectedTask.transcript : []),
      complete: Boolean(initialSelectedTask._transcriptComplete),
      completeUpdatedAt: initialSelectedTask._transcriptComplete ? String(initialSelectedTask.updatedAt || "") : "",
    });
  }
  const initialLoadMs = typeof performance === "undefined" ? 0 : performance.now();
  const selectedIdRef = useRef(initialSelectedId);
  const queueLoadTokenRef = useRef(0);
  const searchLoadTokenRef = useRef(0);
  const detailLoadTokenRef = useRef(0);
  const enqueueInFlightRef = useRef(false);
  const loadMoreInFlightRef = useRef(false);
  const searchLoadMoreInFlightRef = useRef(false);
  const detailInFlightRef = useRef<{ taskId: string; token: number; promise: Promise<void> } | null>(null);
  const traceSummaryInFlightRef = useRef<Map<string, { promise: Promise<void>; refreshAfter: boolean }>>(new Map());
  const promptDetailInFlightRef = useRef<Map<string, Promise<void>>>(new Map());
  const traceStepsInFlightRef = useRef<Map<string, Promise<void>>>(new Map());
  const traceStepInFlightRef = useRef<Map<string, Promise<void>>>(new Map());
  const autoTraceLoadKeysRef = useRef<Set<string>>(new Set());
  const eventRefreshTimerRef = useRef<number | null>(null);
  const traceEventRefreshTimerRef = useRef<number | null>(null);
  const traceEventRefreshPendingStepsRef = useRef(false);
  const trackedLoadInFlightRef = useRef(false);
  const initialLoadSkippedRef = useRef(Boolean(initialTasksData));
  const locallyReadTaskIdsRef = useRef<Map<string, string>>(new Map());
  const dismissedReadTaskIdsRef = useRef<Set<string>>(new Set());
  const sessionCacheRef = useRef<Map<string, AnyRecord>>(initialSessionCache);
  const tasksDataRef = useRef(initialTasksData);
  const [health, setHealth] = useState(null);
  const [tasksData, setTasksDataState] = useState(initialTasksData);
  const [statisticsData, setStatisticsData] = useState(objectRecord(initialTasksData?.statistics) as AnyRecord | null);
  const [selectedId, setSelectedId] = useState(initialSelectedId);
  const [selectedTask, setSelectedTask] = useState(initialSelectedTask);
  const [selectedDetailLoading, setSelectedDetailLoading] = useState(false);
  const [traceStepsLoading, setTraceStepsLoading] = useState<AnyRecord>({});
  const [traceStepLoading, setTraceStepLoading] = useState<AnyRecord>({});
  const [taskSearchQuery, setTaskSearchQuery] = useState("");
  const [searchTasksData, setSearchTasksData] = useState(null);
  const [searchLoading, setSearchLoading] = useState(false);
  const [searchLoadingMoreTasks, setSearchLoadingMoreTasks] = useState(false);
  const initialQueueConfig = initialTasksData?.queue || {};
  const initialProviderId = String(initialQueueConfig?.mainProviderId || initialQueueConfig?.defaultProviderId || "D601").trim() || "D601";
  const [prompt, setPrompt] = useState("");
  const [referenceTaskId, setReferenceTaskId] = useState("");
  const [queueId, setQueueId] = useState("default");
  const [selectedQueueId, setSelectedQueueId] = useState(allQueuesId);
  const [mergeDialogOpen, setMergeDialogOpen] = useState(false);
  const [mergeSourceQueueId, setMergeSourceQueueId] = useState("");
  const [providerId, setProviderId] = useState(initialProviderId);
  const [executionMode, setExecutionMode] = useState("default");
  const [model, setModel] = useState("gpt-5.5");
  const [cwd, setCwd] = useState(executionModeDefaultWorkdir(initialQueueConfig, "default", initialProviderId) || "/workspace");
  const [maxAttempts, setMaxAttempts] = useState(99);
  const [repeatCount, setRepeatCount] = useState(1);
  const [batchConfirmed, setBatchConfirmed] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [steerPrompt, setSteerPrompt] = useState("");
  const [editPrompt, setEditPrompt] = useState("");
  const [editReferenceTaskId, setEditReferenceTaskId] = useState("");
  const [autoScroll, setAutoScroll] = useState(true);
  const [queueSidebarOpen, setQueueSidebarOpen] = useState(() => typeof window === "undefined" ? true : window.matchMedia(queueDesktopMediaQuery).matches);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const { addNotification } = useNotification();
  const [copiedTaskId, setCopiedTaskId] = useState("");
  const [markingReadTaskId, setMarkingReadTaskId] = useState("");
  const [markingAllRead, setMarkingAllRead] = useState(false);
  const [workdirData, setWorkdirData] = useState(null);
  const [workdirBusy, setWorkdirBusy] = useState(false);
  const [loadStats, setLoadStats] = useState(initialTasksData ? {
    phase: "complete",
    taskId: initialSelectedId,
    queueMs: 0,
    detailMs: 0,
    totalMs: initialLoadMs,
    chunks: initialSelectedTask ? 1 : 0,
    transcriptRows: Array.isArray(initialSelectedTask?.transcript) ? initialSelectedTask.transcript.length : 0,
    partial: Boolean(initialTasksData?.selected?.hasMore || taskNeedsFullDetail(initialSelectedTask)),
    completedAt: new Date(),
  } : null);
  const [refreshedAt, setRefreshedAt] = useState(initialTasksData ? new Date() : null);
  const [loadingMoreTasks, setLoadingMoreTasks] = useState(false);

  const tasks = applyLocalReadStateToRows(taskRows(tasksData));
  const loadedUnreadTerminalTasks = tasks.filter(taskIsUnreadTerminal);
  const queue = tasksData?.queue || health?.body?.queue || health?.queue || {};
  const executionDiagnostics = executionDiagnosticsFromQueue(queue, health);
  const statistics = statisticsData || taskStatistics(tasksData, queue);
  const pagination = taskPagination(tasksData);
  const queueRows = knownQueueRows(queue, queueId);
  const mergeTargetQueueId = String(queueId || "default").trim() || "default";
  const mergeSourceQueueRows = queueRows.filter((row: any) => String(row?.id || "") !== mergeTargetQueueId);
  const viewQueueRow = selectedQueueRow(queueRows, selectedQueueId);
  const totalTaskCount = Number((isAllQueues(selectedQueueId) ? queue?.total : viewQueueRow?.total) ?? pagination.total ?? tasks.length);
  const globalActiveIds = activeTaskIds(queue);
  const activeIds = isAllQueues(selectedQueueId)
    ? globalActiveIds
    : [String(selectedQueueRow(queueRows, selectedQueueId)?.activeTaskId || "")].filter(Boolean);
  const activeTaskId = queueActiveTaskId(queue, queueRows, selectedQueueId, tasks);
  const counts = isAllQueues(selectedQueueId) ? queueCounts(queue) : queueCounts(viewQueueRow || {});
  const globalCounts = queueCounts(queue);
  const overallQueuedCount = queueWaitingCount(globalCounts);
  const overallRunningCount = Math.max(queueRunningCount(globalCounts), globalActiveIds.length);
  const rawUnreadTerminalCount = countNumber((isAllQueues(selectedQueueId) ? queue?.unreadTerminal : viewQueueRow?.unreadTerminal) ?? loadedUnreadTerminalTasks.length);
  const overallUnreadTerminalCount = tasksData ? loadedUnreadTerminalTasks.length : rawUnreadTerminalCount;
  const selectedQueueName = isAllQueues(selectedQueueId) ? "All queues" : queueDisplayName(viewQueueRow || { id: selectedQueueId, name: selectedQueueId });
  const normalizedSearchQuery = normalizedTaskSearchQuery(taskSearchQuery);
  const searchActive = normalizedSearchQuery.length > 0;
  const searchTasks = searchActive ? applyLocalReadStateToRows(taskRows(searchTasksData)) : [];
  const searchPagination = taskPagination(searchTasksData);
  const sidebarTasks = searchActive ? searchTasks : tasks;
  const unreadTerminalTasks = sidebarTasks.filter(taskIsUnreadTerminal);
  const queuedTasks = sidebarTasks.filter((task: any) => !taskIsTerminal(task)).sort(compareTaskQueueOrder);
  const historyTasks = sidebarTasks.filter((task: any) => taskIsTerminal(task) && !taskIsUnreadTerminal(task));
  const sidebarPagination = searchActive ? searchPagination : pagination;
  const sidebarTotalTaskCount = searchActive ? Number(searchPagination.total ?? searchTasks.length) : totalTaskCount;
  const sidebarHasMoreTasks = sidebarPagination.hasMore === true && String(sidebarPagination.nextBeforeId || "").length > 0;
  const sidebarLoadingMoreTasks = searchActive ? searchLoadingMoreTasks : loadingMoreTasks;
  const runtime = service ? microserviceRuntime(service) : {};
  const backend = service ? microserviceBackend(service) : {};
  const promptParts = useMemo(() => splitPromptTasks(prompt), [prompt]);
  const enqueueItems = useMemo(() => {
    const count = repeatCountValue(repeatCount);
    return promptParts.flatMap((text: string) => Array.from({ length: count }, () => withReferenceHint(text, referenceTaskId)));
  }, [promptParts, repeatCount, referenceTaskId]);
  const enqueueCount = enqueueItems.length;
  const batchNeedsConfirmation = enqueueCount > 1 && !batchConfirmed;
  const legacyCodeQueueFrozen = true;
  const submitDisabled = legacyCodeQueueFrozen || submitting || busy || enqueueCount === 0 || batchNeedsConfirmation;
  const codexModels = codexModelOptions(queue, model);
  const providerOptions = codexProviderOptions(queue, providerId);
  const executionModeRows = codexExecutionModeOptions(queue, executionMode);
  const currentProviderDefaultWorkdir = executionModeDefaultWorkdir(queue, executionMode, providerId);
  const savedWorkdirs = Array.isArray(workdirData?.workdirs) ? workdirData.workdirs : [];
  const currentWorkdirOptions = workdirOptions(queue, savedWorkdirs, providerId, executionMode, cwd);
  const currentWorkdirSaved = currentWorkdirOptions.some((item: any) => item.source === "saved" && normalizedWorkdirPath(item.path) === normalizedWorkdirPath(cwd));
  const selectedCanSteer = !legacyCodeQueueFrozen && selectedTask?.id && selectedTask?.activeTurnId && String(selectedTask?.status) === "running";
  const selectedCanInterrupt = selectedTask?.id && !["succeeded", "failed", "canceled"].includes(String(selectedTask?.status || ""));
  const selectedCanRetry = !legacyCodeQueueFrozen && selectedTask?.id && ["succeeded", "failed", "canceled"].includes(String(selectedTask?.status || ""));
  const selectedCanEditPrompt = !legacyCodeQueueFrozen && selectedTask?.id && taskPromptEditable(selectedTask);

  function setTasksData(nextOrUpdater: any): any {
    const next = typeof nextOrUpdater === "function" ? nextOrUpdater(tasksDataRef.current) : nextOrUpdater;
    tasksDataRef.current = next;
    const nextStats = objectRecord(next?.statistics);
    if (nextStats) setStatisticsData(nextStats);
    setTasksDataState(next);
    return next;
  }

  async function refreshStatistics(queueFilterId = selectedQueueId): Promise<void> {
    if (!service) return;
    try {
      const result = await loadTaskStatistics(apiBaseUrl, queueFilterId);
      const nextStats = objectRecord(result?.statistics) || objectRecord(result?.stats) || objectRecord(result);
      if (nextStats) setStatisticsData(nextStats);
      if (result?.queue) {
        setTasksData((previous: any) => previous ? { ...previous, queue: result.queue } : { ok: true, queue: result.queue, tasks: [], pagination: { returned: 0, total: 0, hasMore: false } });
      }
    } catch (err) {
      setStatisticsData(taskStatisticsUnavailable(err));
    }
  }

  function rememberLocalReadState(taskIds: string[], readAt: string, hideFromSidebar = true): string[] {
    const ids = Array.from(new Set(taskIds.map((id) => String(id || "")).filter(Boolean)));
    for (const id of ids) {
      locallyReadTaskIdsRef.current.set(id, readAt);
      if (hideFromSidebar) dismissedReadTaskIdsRef.current.add(id);
    }
    return ids;
  }

  function forgetLocalReadState(taskIds: string[]): void {
    for (const id of taskIds.map((value) => String(value || "")).filter(Boolean)) {
      locallyReadTaskIdsRef.current.delete(id);
      dismissedReadTaskIdsRef.current.delete(id);
    }
  }

  function taskWithLocalReadState(task: any): any {
    const id = String(task?.id || "");
    const localReadAt = id ? locallyReadTaskIdsRef.current.get(id) : undefined;
    if (!localReadAt) return task;
    const status = String(task?.status || "");
    if (status.length > 0 && !taskIsTerminal(task)) {
      locallyReadTaskIdsRef.current.delete(id);
      dismissedReadTaskIdsRef.current.delete(id);
      return task;
    }
    return { ...task, readAt: task?.readAt || localReadAt, terminalUnread: false };
  }

  function taskDismissedAfterRead(task: any): boolean {
    const id = String(task?.id || "");
    return id.length > 0 && dismissedReadTaskIdsRef.current.has(id) && taskIsTerminal(task);
  }

  function applyLocalReadStateToRows(rows: any[], hideDismissed = true): any[] {
    const normalized: any[] = [];
    for (const task of Array.isArray(rows) ? rows : []) {
      const patchedTask = taskWithLocalReadState(task);
      if (hideDismissed && taskDismissedAfterRead(patchedTask)) continue;
      normalized.push(patchedTask);
    }
    return normalized;
  }

  function applyLocalReadStateToResult(result: any, hideDismissed = true): any {
    if (!result || !Array.isArray(result?.tasks)) return result;
    const rows = applyLocalReadStateToRows(taskRows(result), hideDismissed);
    const pagination = taskPagination(result);
    return {
      ...result,
      tasks: rows,
      pagination: result.pagination ? { ...pagination, returned: rows.length } : result.pagination,
    };
  }

  function taskVisibleInQueueFilter(task: any, queueFilterId: string): boolean {
    return isAllQueues(queueFilterId) || taskQueueLabel(task) === queueFilterId;
  }

  function taskMatchesCurrentSearch(task: any): boolean {
    const query = normalizedSearchQuery.toLowerCase();
    if (query.length === 0) return true;
    const haystack = [
      task?.id,
      task?.status,
      task?.queueId,
      task?.providerId,
      task?.model,
      task?.cwd,
      task?.displayPrompt,
      task?.basePrompt,
      task?.prompt,
      previewTextField(task?.displayPromptPreview),
      previewTextField(task?.basePromptPreview),
      previewTextField(task?.promptPreview),
      task?.finalResponse,
      task?.lastError?.message,
    ].map((value) => String(value || "").toLowerCase()).join("\n");
    return haystack.includes(query);
  }

  function mergeCreatedTasksIntoCurrentView(createdTasks: any[], queuePatch: any): void {
    const rows = createdTasks.filter((task) => String(task?.id || "").length > 0);
    if (rows.length === 0 && !queuePatch) return;
    const firstTask = rows[0] || null;
    const firstId = String(firstTask?.id || "");
    const filteredRows = rows.filter((task) => taskVisibleInQueueFilter(task, selectedQueueId));
    const searchableRows = filteredRows.filter(taskMatchesCurrentSearch);
    const activeSortId = String(queuePatch?.activeTaskId || activeTaskIds(queuePatch)[0] || firstId || activeTaskId || "");
    for (const task of rows) {
      const taskId = String(task?.id || "");
      if (!taskId) continue;
      const transcript = Array.isArray(task?.transcript) ? task.transcript : [];
      sessionCacheRef.current.set(taskId, {
        ...(sessionCacheRef.current.get(taskId) || {}),
        task: {
          ...task,
          _summaryLoaded: true,
          _detailLoaded: transcript.length > 0,
          _transcriptComplete: false,
          _transcriptPreview: false,
        },
        maxSeq: transcriptMaxSeq(transcript),
        complete: false,
        completeUpdatedAt: "",
      });
    }
    setTasksData((previous: any) => {
      if (!previous && (filteredRows.length === 0 || !queuePatch)) return previous;
      const previousRows = taskRows(previous);
      const mergedRows = applyLocalReadStateToRows(mergeTaskRowsPreferLatest([previousRows, filteredRows], activeSortId));
      return {
        ...(previous || {}),
        queue: queuePatch || previous?.queue,
        tasks: mergedRows,
        pagination: previous?.pagination ? { ...taskPagination(previous), returned: mergedRows.length } : previous?.pagination,
      };
    });
    if (searchActive) {
      setSearchTasksData((previous: any) => {
        if (!previous || searchableRows.length === 0) return previous;
        const mergedRows = applyLocalReadStateToRows(mergeTaskRowsPreferLatest([taskRows(previous), searchableRows], activeSortId));
        return {
          ...previous,
          queue: queuePatch || previous.queue,
          tasks: mergedRows,
          pagination: previous.pagination ? { ...taskPagination(previous), returned: mergedRows.length } : previous.pagination,
        };
      });
    }
    if (firstTask && taskVisibleInQueueFilter(firstTask, selectedQueueId) && taskMatchesCurrentSearch(firstTask)) {
      detailLoadTokenRef.current += 1;
      selectedIdRef.current = firstId;
      setSelectedId(firstId);
      setSelectedTask(sessionCacheRef.current.get(firstId)?.task || firstTask);
      setSelectedDetailLoading(false);
      setLoadStats({
        phase: "complete",
        taskId: firstId,
        queueMs: 0,
        detailMs: 0,
        totalMs: 0,
        chunks: 1,
        transcriptRows: Array.isArray(firstTask?.transcript) ? firstTask.transcript.length : 0,
        partial: true,
        completedAt: new Date(),
      });
    }
    setRefreshedAt(new Date());
  }

  function changeSubmitProvider(nextProviderId: string): void {
    const next = String(nextProviderId || queue?.mainProviderId || "D601").trim() || "D601";
    setProviderId(next);
    setCwd(executionModeDefaultWorkdir(queue, executionMode, next));
    setWorkdirData(null);
    void loadWorkdirs().catch((err) => setError(errorText(err, "加载工作目录失败")));
  }

  function changeSubmitExecutionMode(nextMode: string): void {
    const next = String(nextMode || "default").trim() || "default";
    let nextProvider = providerId;
    if (next === "windows-native") {
      const current = providerOptions.find((provider: any) => provider.id === providerId);
      if (!current?.supportsWindowsNativeCodex) {
        nextProvider = String(providerOptions.find((provider: any) => provider.supportsWindowsNativeCodex)?.id || providerId || "D601");
        setProviderId(nextProvider);
      }
    }
    setExecutionMode(next);
    setCwd(executionModeDefaultWorkdir(queue, next, nextProvider));
    setWorkdirData(null);
    void loadWorkdirs().catch((err) => setError(errorText(err, "加载工作目录失败")));
  }

  function patchLoadedReadState(taskIds: string[], readAt: string, queuePatch: any = null, taskPatch: any = null): void {
    const ids = new Set(rememberLocalReadState(taskIds, readAt));
    if (ids.size === 0 && taskPatch === null && queuePatch === null) return;
    setTasksData((previous: any) => {
      if (!previous) return previous;
      const rows = taskRows(previous).flatMap((task: any) => {
        const id = String(task?.id || "");
        if (!ids.has(id)) {
          const patchedTask = taskWithLocalReadState(task);
          return taskDismissedAfterRead(patchedTask) ? [] : [patchedTask];
        }
        const patch = taskPatch && String(taskPatch?.id || "") === id ? taskPatch : {};
        const updatedTask = { ...task, ...patch, readAt, terminalUnread: false };
        return taskDismissedAfterRead(updatedTask) ? [] : [updatedTask];
      });
      return { ...previous, queue: queuePatch || previous.queue, tasks: ids.size > 0 ? mergeTaskRowsPreferLatest([rows], activeTaskId) : rows };
    });
    for (const id of ids) {
      const cached = sessionCacheRef.current.get(id);
      if (cached?.task) {
        const patch = taskPatch && String(taskPatch?.id || "") === id ? taskPatch : {};
        const task = { ...cached.task, ...patch, readAt, terminalUnread: false };
        sessionCacheRef.current.set(id, { ...cached, task });
        if (selectedIdRef.current === id) setSelectedTask(task);
      }
    }
  }

  useEffect(() => {
    setBatchConfirmed(false);
  }, [prompt, repeatCount, referenceTaskId]);

  useEffect(() => {
    const query = normalizedTaskSearchQuery(taskSearchQuery);
    searchLoadTokenRef.current += 1;
    const token = searchLoadTokenRef.current;
    if (!service || query.length === 0) {
      setSearchTasksData(null);
      setSearchLoading(false);
      setSearchLoadingMoreTasks(false);
      searchLoadMoreInFlightRef.current = false;
      return undefined;
    }
    setSearchLoading(true);
    setSearchTasksData(null);
    const timer = window.setTimeout(() => {
      void (async () => {
        try {
          const result = await loadTaskList(apiBaseUrl, selectedQueueId, query);
          if (token !== searchLoadTokenRef.current) return;
          setSearchTasksData(applyLocalReadStateToResult(result));
        } catch (err) {
          if (token === searchLoadTokenRef.current) {
            setSearchTasksData(null);
            setError(errorText(err, "搜索 Codex tasks 失败"));
          }
        } finally {
          if (token === searchLoadTokenRef.current) setSearchLoading(false);
        }
      })();
    }, 240);
    return () => window.clearTimeout(timer);
  }, [service?.id, apiBaseUrl, selectedQueueId, taskSearchQuery]);

  useEffect(() => {
    setEditPrompt(selectedTask ? taskBasePromptText(selectedTask) : "");
    setEditReferenceTaskId(Array.isArray(selectedTask?.referenceTaskIds) ? selectedTask.referenceTaskIds.join(" ") : "");
  }, [selectedId]);

  function publishCachedTask(taskId: string, patch: AnyRecord, token: number): AnyRecord {
    const cached = sessionCacheRef.current.get(taskId) || {};
    const existingTask = cached.task || {};
    const existingTranscript = Array.isArray(existingTask.transcript) ? existingTask.transcript : [];
    const mergedPatch = mergeTaskPatch(existingTask, patch);
    const nextTranscript = Object.prototype.hasOwnProperty.call(patch, "transcript")
      ? mergeTranscriptRows(existingTranscript, Array.isArray(patch.transcript) ? patch.transcript : [])
      : existingTranscript;
    const task = {
      ...existingTask,
      ...mergedPatch,
      transcript: nextTranscript,
      output: Array.isArray(mergedPatch.output) ? preferRicherArray(existingTask, mergedPatch, "output") : (Array.isArray(existingTask.output) ? existingTask.output : []),
      events: Array.isArray(mergedPatch.events) ? preferRicherArray(existingTask, mergedPatch, "events") : (Array.isArray(existingTask.events) ? existingTask.events : []),
    };
    const taskWithReadState = taskWithLocalReadState(task);
    const taskUpdatedAt = String(taskWithReadState?.updatedAt || "");
    const patchComplete = Boolean(patch._transcriptComplete) && taskIsTerminal(taskWithReadState);
    const cachedComplete = Boolean(cached.complete)
      && taskIsTerminal(taskWithReadState)
      && String(cached.completeUpdatedAt || "") === taskUpdatedAt;
    const complete = patchComplete || cachedComplete;
    const entry = {
      ...cached,
      task: taskWithReadState,
      maxSeq: transcriptMaxSeq(nextTranscript),
      complete,
      completeUpdatedAt: complete ? taskUpdatedAt : "",
    };
    sessionCacheRef.current.set(taskId, entry);
    if (token === detailLoadTokenRef.current && selectedIdRef.current === taskId) setSelectedTask(taskWithReadState);
    return entry;
  }

  async function ensureTraceSummary(taskId: string, force = false, loadStartedAt?: number, queueMs?: number): Promise<void> {
    if (!service || !taskId) return;
    const cached = sessionCacheRef.current.get(taskId);
    const cachedTask = cached?.task;
    if (!force && traceSummaryIsCurrent(cachedTask)) return;
    const key = taskId;
    const existing = traceSummaryInFlightRef.current.get(key);
    if (existing) {
      if (force || !traceSummaryIsCurrent(cachedTask)) existing.refreshAfter = true;
      return existing.promise;
    }
    const token = detailLoadTokenRef.current;
    const startedAt = performance.now();
    if (selectedIdRef.current === taskId) setSelectedDetailLoading(true);
    const inFlight = { promise: Promise.resolve(), refreshAfter: false };
    const promise = (async () => {
      try {
        const result = await loadTaskTraceSummary(apiBaseUrl, taskId);
        if (token !== detailLoadTokenRef.current || selectedIdRef.current !== taskId) return;
        const summary = result?.summary || {};
        const summaryUpdatedAt = String(summary.updatedAt || "");
        publishCachedTask(taskId, {
          id: taskId,
          status: summary.status,
          updatedAt: summaryUpdatedAt,
          startedAt: summary.startedAt,
          finishedAt: summary.finishedAt,
          currentAttempt: summary.currentAttempt,
          maxAttempts: summary.maxAttempts,
          finalResponse: summary.finalResponse,
          lastJudge: summary.lastJudge,
          lastError: summary.lastError,
          attempts: Array.isArray(summary.attempts) ? summary.attempts : [],
          stepCount: summary.stepCount,
          llmStepCount: summary.llmStepCount,
          traceStats: summary.traceStats,
          statsSource: summary.statsSource,
          timing: summary.timing,
          _traceSummary: summary,
          _traceSummaryLoaded: true,
          _traceSummaryUpdatedAt: summaryUpdatedAt,
          _detailLoaded: true,
        }, token);
        setLoadStats({
          phase: "complete",
          taskId,
          queueMs: queueMs ?? 0,
          detailMs: performance.now() - startedAt,
          totalMs: loadStartedAt === undefined ? performance.now() - startedAt : performance.now() - loadStartedAt,
          chunks: 1,
          transcriptRows: Number(summary?.execution?.traceLineCount || summary?.execution?.stepCount || 0),
          partial: false,
          completedAt: new Date(),
        });
      } finally {
        const shouldRefreshAfter = Boolean(inFlight.refreshAfter && selectedIdRef.current === taskId && !traceSummaryIsCurrent(sessionCacheRef.current.get(taskId)?.task));
        traceSummaryInFlightRef.current.delete(key);
        if (token === detailLoadTokenRef.current && selectedIdRef.current === taskId) setSelectedDetailLoading(false);
        if (shouldRefreshAfter) {
          window.setTimeout(() => {
            void ensureTraceSummary(taskId, true).catch((err) => setError(errorText(err, "自动刷新 Trace Summary 失败")));
          }, 0);
        }
      }
    })();
    inFlight.promise = promise;
    traceSummaryInFlightRef.current.set(key, inFlight);
    await promise;
  }

  async function ensurePromptPart(part: string, attemptIndex: any = null): Promise<void> {
    const taskId = selectedIdRef.current;
    if (!service || !taskId || !part) return;
    const cachedTask = sessionCacheRef.current.get(taskId)?.task;
    const details = taskPromptDetails(cachedTask);
    const detailKey = part === "feedback" || part === "judge-feedback" ? feedbackPromptDetailKey(attemptIndex) : part;
    if (details[detailKey]?.text) return;
    const key = `${taskId}:${detailKey}`;
    const existing = promptDetailInFlightRef.current.get(key);
    if (existing) return existing;
    const token = detailLoadTokenRef.current;
    if (selectedIdRef.current === taskId) setSelectedDetailLoading(true);
    const promise = (async () => {
      try {
        const result = await loadTaskPromptPart(apiBaseUrl, taskId, part, attemptIndex);
        if (token !== detailLoadTokenRef.current || selectedIdRef.current !== taskId) return;
        const currentTask = sessionCacheRef.current.get(taskId)?.task;
        const currentDetails = taskPromptDetails(currentTask);
        publishCachedTask(taskId, {
          ...(part === "full" ? { prompt: String(result?.text || ""), promptChars: Number(result?.chars || 0) } : {}),
          _promptDetails: { ...currentDetails, [detailKey]: result },
        }, token);
      } finally {
        promptDetailInFlightRef.current.delete(key);
        if (token === detailLoadTokenRef.current && selectedIdRef.current === taskId) setSelectedDetailLoading(false);
      }
    })();
    promptDetailInFlightRef.current.set(key, promise);
    await promise;
  }

  async function ensureTraceSteps(attemptIndex: any = null, options: AnyRecord = {}): Promise<void> {
    const taskId = selectedIdRef.current;
    if (!service || !taskId) return;
    const cachedTask = sessionCacheRef.current.get(taskId)?.task;
    const attemptKey = attemptIndex === null || attemptIndex === undefined || String(attemptIndex).length === 0 ? "" : String(attemptIndex);
    const loaded = taskTraceStepsLoaded(cachedTask, attemptKey || null);
    const force = Boolean(options.force);
    const incremental = Boolean(options.incremental);
    if (loaded && !force) return;
    const existingSteps = taskTraceSteps(cachedTask, attemptKey || null);
    const afterSeq = incremental && existingSteps.length > 0 ? traceStepsMaxSeq(existingSteps) : 0;
    const key = `${taskId}:${attemptKey || "all"}:${afterSeq}`;
    const existing = traceStepsInFlightRef.current.get(key);
    if (existing) return existing;
    const token = detailLoadTokenRef.current;
    const loadingKey = traceStepsLoadingKey(taskId, attemptKey || null);
    setTraceStepsLoading((prev: AnyRecord) => ({ ...prev, [loadingKey]: true }));
    if (selectedIdRef.current === taskId) setSelectedDetailLoading(true);
    const promise = (async () => {
      try {
        const result = await loadTaskTraceSteps(apiBaseUrl, taskId, afterSeq, 500, attemptKey || null);
        if (token !== detailLoadTokenRef.current || selectedIdRef.current !== taskId) return;
        const incomingSteps = Array.isArray(result?.steps) ? result.steps : [];
        const steps = afterSeq > 0 ? mergeTraceStepRows(existingSteps, incomingSteps) : incomingSteps;
        if (attemptKey) {
          const currentTask = sessionCacheRef.current.get(taskId)?.task;
          const byAttempt = objectRecord(currentTask?._traceStepsByAttempt) || {};
          const loadedByAttempt = objectRecord(currentTask?._traceStepsLoadedByAttempt) || {};
          const nextSeqByAttempt = objectRecord(currentTask?._traceStepsNextAfterSeqByAttempt) || {};
          publishCachedTask(taskId, {
            _traceStepsByAttempt: { ...byAttempt, [attemptKey]: steps },
            _traceStepsLoadedByAttempt: { ...loadedByAttempt, [attemptKey]: true },
            _traceStepsNextAfterSeqByAttempt: { ...nextSeqByAttempt, [attemptKey]: result?.nextAfterSeq },
          }, token);
        } else {
          publishCachedTask(taskId, {
            _traceSteps: steps,
            _traceStepsLoaded: true,
            _traceStepsHasMore: Boolean(result?.hasMore),
            _traceStepsNextAfterSeq: result?.nextAfterSeq,
          }, token);
        }
      } finally {
        traceStepsInFlightRef.current.delete(key);
        setTraceStepsLoading((prev: AnyRecord) => {
          const next = { ...prev };
          delete next[loadingKey];
          return next;
        });
        if (token === detailLoadTokenRef.current && selectedIdRef.current === taskId) setSelectedDetailLoading(false);
      }
    })();
    traceStepsInFlightRef.current.set(key, promise);
    await promise;
  }

  async function ensureTraceStep(seq: any): Promise<void> {
    const taskId = selectedIdRef.current;
    const seqKey = String(seq ?? "");
    if (!service || !taskId || seqKey.length === 0) return;
    const cachedTask = sessionCacheRef.current.get(taskId)?.task;
    const details = taskTraceStepDetails(cachedTask);
    if (details[seqKey]?.line) return;
    const key = `${taskId}:${seqKey}`;
    const existing = traceStepInFlightRef.current.get(key);
    if (existing) return existing;
    const token = detailLoadTokenRef.current;
    const loadingKey = traceStepLoadingKey(taskId, seqKey);
    setTraceStepLoading((prev: AnyRecord) => ({ ...prev, [loadingKey]: true }));
    if (selectedIdRef.current === taskId) setSelectedDetailLoading(true);
    const promise = (async () => {
      try {
        const result = await loadTaskTraceStep(apiBaseUrl, taskId, seq);
        if (token !== detailLoadTokenRef.current || selectedIdRef.current !== taskId) return;
        const currentTask = sessionCacheRef.current.get(taskId)?.task;
        const currentDetails = taskTraceStepDetails(currentTask);
        publishCachedTask(taskId, {
          _traceStepDetails: { ...currentDetails, [seqKey]: result },
        }, token);
      } finally {
        traceStepInFlightRef.current.delete(key);
        setTraceStepLoading((prev: AnyRecord) => {
          const next = { ...prev };
          delete next[loadingKey];
          return next;
        });
        if (token === detailLoadTokenRef.current && selectedIdRef.current === taskId) setSelectedDetailLoading(false);
      }
    })();
    traceStepInFlightRef.current.set(key, promise);
    await promise;
  }

  function refreshLoadedTraceSteps(taskId: string): void {
    if (selectedIdRef.current !== taskId) return;
    const cachedTask = sessionCacheRef.current.get(taskId)?.task;
    if (!cachedTask) return;
    if (taskTraceStepsLoaded(cachedTask, null)) {
      void ensureTraceSteps(null, { force: true, incremental: true }).catch((err) => setError(errorText(err, "增量刷新 Trace Steps 失败")));
    }
    const loadedByAttempt = objectRecord(cachedTask?._traceStepsLoadedByAttempt) || {};
    for (const attemptKey of Object.keys(loadedByAttempt).filter((key) => loadedByAttempt[key])) {
      void ensureTraceSteps(attemptKey, { force: true, incremental: true }).catch((err) => setError(errorText(err, "增量刷新 Attempt Trace Steps 失败")));
    }
  }

  async function loadTaskDetail(taskId: string, loadStartedAt?: number, queueMs?: number): Promise<void> {
    if (!service || !taskId) return;
    const detailStartedAt = performance.now();
    const token = detailLoadTokenRef.current;
    const cached = sessionCacheRef.current.get(taskId);
    if (cached?.task) {
      setSelectedTask(cached.task);
      setSelectedDetailLoading(taskNeedsFullDetail(cached.task) || !cached.complete);
      if (!taskNeedsFullDetail(cached.task) && cached.complete && taskIsTerminal(cached.task) && String(cached.completeUpdatedAt || "") === String(cached.task?.updatedAt || "")) {
        setLoadStats({
          phase: "complete",
          taskId,
          queueMs: queueMs ?? 0,
          detailMs: 0,
          totalMs: loadStartedAt === undefined ? 0 : performance.now() - loadStartedAt,
          chunks: 0,
          transcriptRows: Array.isArray(cached.task.transcript) ? cached.task.transcript.length : 0,
          completedAt: new Date(),
        });
        return;
      }
    } else {
      setSelectedDetailLoading(true);
    }
    const existing = detailInFlightRef.current;
    if (existing?.taskId === taskId && existing.token === token) return existing.promise;
    const promise = (async () => {
      try {
        const meta = await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}?meta=1`));
        if (token !== detailLoadTokenRef.current || selectedIdRef.current !== taskId) return;
        const current = sessionCacheRef.current.get(taskId);
        const currentTranscript = Array.isArray(current?.task?.transcript) ? current.task.transcript : [];
        const metaTask = meta?.task || {};
        const currentCompleteForMeta = Boolean(current?.complete) && String(current?.completeUpdatedAt || "") === String(metaTask?.updatedAt || "");
        publishCachedTask(taskId, { ...metaTask, summaryOnly: false, _metaLoaded: true, transcript: currentTranscript, _detailLoaded: currentTranscript.length > 0, _transcriptComplete: currentCompleteForMeta }, token);
        const restartFromBeginning = taskNeedsFullDetail(current?.task) || Boolean(current?.task?._transcriptPreview);
        const startSeq = restartFromBeginning ? 0 : currentTranscript.length > 0 ? transcriptResumeSeq(currentTranscript) : 0;
        let afterSeq = !restartFromBeginning && current?.complete && taskIsTerminal(metaTask) && String(current?.completeUpdatedAt || "") === String(metaTask?.updatedAt || "")
          ? transcriptMaxSeq(currentTranscript)
          : startSeq;
        let hasMore = true;
        let chunks = 0;
        let transcriptRows = currentTranscript.length;
        while (hasMore) {
          const chunk = await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/transcript?afterSeq=${encodeURIComponent(String(afterSeq))}&limit=${codexTranscriptChunkLimit}&fullText=1`));
          if (token !== detailLoadTokenRef.current || selectedIdRef.current !== taskId) return;
          const cachedNow = sessionCacheRef.current.get(taskId);
          const existingTranscript = Array.isArray(cachedNow?.task?.transcript) ? cachedNow.task.transcript : [];
          const mergedTranscript = mergeTranscriptRows(existingTranscript, Array.isArray(chunk?.transcript) ? chunk.transcript : []);
          chunks += 1;
          transcriptRows = mergedTranscript.length;
          const complete = Boolean(!chunk?.hasMore);
          publishCachedTask(taskId, {
            status: chunk?.status || metaTask.status,
            updatedAt: chunk?.updatedAt || metaTask.updatedAt,
            transcript: mergedTranscript,
            _detailLoaded: complete || mergedTranscript.length > 0,
            _transcriptComplete: complete,
            _transcriptPreview: restartFromBeginning && !complete,
          }, token);
          hasMore = Boolean(chunk?.hasMore);
          afterSeq = Number(chunk?.nextAfterSeq ?? transcriptMaxSeq(mergedTranscript));
          if (!hasMore) break;
          await new Promise((resolve) => window.setTimeout(resolve, 0));
        }
        setLoadStats({
          phase: "complete",
          taskId,
          queueMs: queueMs ?? 0,
          detailMs: performance.now() - detailStartedAt,
          totalMs: loadStartedAt === undefined ? performance.now() - detailStartedAt : performance.now() - loadStartedAt,
          chunks,
          transcriptRows,
          completedAt: new Date(),
        });
      } finally {
        if (detailInFlightRef.current?.taskId === taskId && detailInFlightRef.current?.token === token) detailInFlightRef.current = null;
        if (token === detailLoadTokenRef.current && selectedIdRef.current === taskId) setSelectedDetailLoading(false);
      }
    })();
    detailInFlightRef.current = { taskId, token, promise };
    await promise;
  }

  async function load(preferId = selectedIdRef.current, trackLoad = true, queueFilterId = selectedQueueId): Promise<void> {
    if (!service) return;
    if (!trackLoad && trackedLoadInFlightRef.current) return;
    const startedAt = performance.now();
    if (trackLoad) trackedLoadInFlightRef.current = true;
    if (trackLoad) {
      setLoadStats({
        phase: "loading",
        taskId: String(preferId || selectedIdRef.current || ""),
        startedAt: new Date(),
      });
    }
    const token = queueLoadTokenRef.current + 1;
    queueLoadTokenRef.current = token;
    const requestedId = String(preferId || selectedIdRef.current || "");
    const requestedCached = requestedId ? sessionCacheRef.current.get(requestedId) : null;
    const requestedTranscript = Array.isArray(requestedCached?.task?.transcript) ? requestedCached.task.transcript : [];
    const overviewAfterSeq = transcriptResumeSeq(requestedTranscript);
    let tasksResult = null;
    const firstPaintListOnly = trackLoad && requestedId.length === 0;
    tasksResult = firstPaintListOnly
      ? await loadTaskList(apiBaseUrl, queueFilterId, "")
      : await loadTaskOverview(apiBaseUrl, requestedId, overviewAfterSeq, queueFilterId, "", true, { stats: false });
    if (token !== queueLoadTokenRef.current) {
      if (trackLoad) trackedLoadInFlightRef.current = false;
      return;
    }
    const queueMs = performance.now() - startedAt;
    setHealth(health || {});
    const resultQueue = tasksResult?.queue || {};
    const activeSortId = String(resultQueue?.activeTaskId || activeTaskIds(resultQueue)[0] || "");
    let mergedTasksResult = tasksResult;
    setTasksData((previous: any) => {
      const incomingRows = taskRows(tasksResult);
      const previousRows = taskRows(previous);
      const mergedRows = previousRows.length > 0
        ? mergeTaskRowsPreferLatest([previousRows, incomingRows], activeSortId)
        : mergeTaskRowsPreferLatest([incomingRows], activeSortId);
      const visibleRows = applyLocalReadStateToRows(mergedRows);
      const incomingPagination = taskPagination(tasksResult);
      const previousPagination = taskPagination(previous);
      const preserveCursor = previousRows.length > incomingRows.length && (previousPagination.hasMore === false || String(previousPagination.nextBeforeId || "").length > 0);
      const pagination = {
        ...incomingPagination,
        ...(preserveCursor ? { hasMore: previousPagination.hasMore, nextBeforeId: previousPagination.nextBeforeId } : {}),
        returned: visibleRows.length,
      };
      mergedTasksResult = { ...tasksResult, tasks: visibleRows, pagination };
      return mergedTasksResult;
    });
    const rows = taskRows(mergedTasksResult);
    const resultQueueRows = knownQueueRows(resultQueue, queueId);
    const queuePrimaryId = queueActiveTaskId(resultQueue, resultQueueRows, queueFilterId, rows);
    const queueRunnableId = queueRunnableTaskId(resultQueueRows, queueFilterId, rows);
    const latestRequestedId = requestedId || selectedIdRef.current;
    const overviewSelected = mergedTasksResult?.selected || null;
    const overviewTask = overviewSelected?.task || null;
    const overviewTranscript = Array.isArray(overviewSelected?.transcript) ? overviewSelected.transcript : null;
    const nextId = latestRequestedId || queuePrimaryId || queueRunnableId || rows[0]?.id || "";
    const previousId = selectedIdRef.current;
    if (previousId !== nextId) detailLoadTokenRef.current += 1;
    selectedIdRef.current = nextId;
    setSelectedId(nextId);
    const row = rows.find((task: any) => task.id === nextId);
    if (row) {
      const cached = sessionCacheRef.current.get(nextId);
      if (cached?.task) sessionCacheRef.current.set(nextId, { ...cached, task: { ...row, ...cached.task, status: row.status, updatedAt: row.updatedAt } });
    }
    if (firstPaintListOnly && row) {
      publishCachedTask(nextId, {
        ...row,
        _summaryLoaded: false,
        transcript: [],
        _detailLoaded: false,
        _transcriptComplete: false,
        _transcriptPreview: true,
      }, detailLoadTokenRef.current);
      setSelectedDetailLoading(true);
      setLoadStats({
        phase: "complete",
        taskId: nextId,
        queueMs,
        detailMs: 0,
        totalMs: performance.now() - startedAt,
        chunks: 0,
        transcriptRows: 0,
        partial: true,
        completedAt: new Date(),
      });
      setRefreshedAt(new Date());
      if (trackLoad) trackedLoadInFlightRef.current = false;
      void ensureTraceSummary(nextId, true)
        .catch((err) => setError(errorText(err, "加载 Codex Trace Summary 失败")));
      void loadTaskOverview(apiBaseUrl, nextId, 0, queueFilterId, "", false)
        .then((full: any) => {
          if (token !== queueLoadTokenRef.current) return;
          const fullRows = taskRows(full);
          const selected = overviewSelectedTask(full);
          if (fullRows.length > 0) {
            setTasksData((previous: any) => {
              const mergedRows = mergeTaskRowsPreferLatest([taskRows(previous), fullRows], activeSortId);
              return { ...previous, statistics: full?.statistics || previous?.statistics, tasks: applyLocalReadStateToRows(mergedRows) };
            });
          }
          if (selected?.id === selectedIdRef.current) {
            const transcript = Array.isArray(selected.transcript) ? selected.transcript : [];
            publishCachedTask(selected.id, {
              ...selected,
              transcript,
              _summaryLoaded: true,
              _detailLoaded: transcript.length > 0,
              _transcriptPreview: Boolean(full?.selected?.preview),
            }, detailLoadTokenRef.current);
          }
        })
        .catch(() => {});
      return;
    }
    if (overviewTask?.id === nextId && overviewTranscript !== null) {
      const cached = sessionCacheRef.current.get(nextId);
      const existingTranscript = Array.isArray(cached?.task?.transcript) ? cached.task.transcript : [];
      const mergedTranscript = mergeTranscriptRows(existingTranscript, overviewTranscript);
      const overviewPreviewOnly = Boolean(overviewSelected?.preview);
      publishCachedTask(nextId, {
        ...overviewTask,
        _summaryLoaded: true,
        transcript: mergedTranscript,
        _detailLoaded: !overviewSelected?.hasMore || mergedTranscript.length > 0,
        _transcriptComplete: !overviewPreviewOnly && !overviewSelected?.hasMore && taskIsTerminal(overviewTask),
        _transcriptPreview: overviewPreviewOnly,
      }, detailLoadTokenRef.current);
      setSelectedDetailLoading(false);
      if (trackLoad) {
        setLoadStats({
          phase: "complete",
          taskId: nextId,
          queueMs,
          detailMs: Math.max(0, performance.now() - startedAt - queueMs),
          totalMs: performance.now() - startedAt,
          chunks: 1,
          transcriptRows: mergedTranscript.length,
          partial: Boolean(overviewPreviewOnly || overviewSelected?.hasMore || taskNeedsFullDetail(overviewTask)),
          completedAt: new Date(),
        });
      }
      setRefreshedAt(new Date());
      if (trackLoad) trackedLoadInFlightRef.current = false;
      // Overview is intentionally small and may only contain the latest attempt.
      // Load the canonical Trace Summary as a follow-up so retry/judge feedback
      // cards are shown for historical multi-attempt sessions too.
      void ensureTraceSummary(nextId, false, trackLoad ? startedAt : undefined, trackLoad ? queueMs : undefined)
        .catch((err) => setError(errorText(err, "加载 Codex Trace Summary 失败")));
      // Background refresh with trace stats to populate stepCount in task list
      void loadTaskOverview(apiBaseUrl, requestedId, overviewAfterSeq, queueFilterId, "", false)
        .then((full: any) => {
          if (token !== queueLoadTokenRef.current) return;
          const fullRows = taskRows(full);
          if (fullRows.length > 0) {
            setTasksData((previous: any) => {
              const mergedRows = mergeTaskRowsPreferLatest([taskRows(previous), fullRows], activeSortId);
              return { ...previous, tasks: applyLocalReadStateToRows(mergedRows) };
            });
          }
        })
        .catch(() => {});
      return;
    }
    if (trackLoad) {
      setLoadStats({
        phase: "session",
        taskId: nextId,
        queueMs,
        totalMs: queueMs,
        startedAt: new Date(Date.now() - queueMs),
      });
    }
    if (nextId) void ensureTraceSummary(nextId, true, trackLoad ? startedAt : undefined, trackLoad ? queueMs : undefined).catch((err) => setError(errorText(err, "加载 Codex Trace Summary 失败")));
    else {
      detailLoadTokenRef.current += 1;
      setSelectedTask(null);
      setSelectedDetailLoading(false);
      if (trackLoad) {
        setLoadStats({
          phase: "complete",
          taskId: "",
          queueMs,
          detailMs: 0,
          totalMs: performance.now() - startedAt,
          chunks: 0,
          transcriptRows: 0,
          completedAt: new Date(),
        });
      }
    }
    setRefreshedAt(new Date());
    if (trackLoad) trackedLoadInFlightRef.current = false;
    void refreshStatistics(queueFilterId).catch((err) => setStatisticsData(taskStatisticsUnavailable(err)));
  }

  async function loadMoreTasks(): Promise<void> {
    if (searchActive) {
      if (!service || searchLoadingMoreTasks || searchLoadMoreInFlightRef.current) return;
      const beforeId = String(searchPagination.nextBeforeId || "");
      if (!beforeId) return;
      searchLoadMoreInFlightRef.current = true;
      setSearchLoadingMoreTasks(true);
      setError("");
      try {
        const result = await loadTaskPage(apiBaseUrl, selectedQueueId, beforeId, codexMoreTaskLimit, normalizedSearchQuery);
        const incomingRows = taskRows(result);
        const resultQueue = result?.queue || queue || {};
        const activeSortId = String(resultQueue?.activeTaskId || activeTaskIds(resultQueue)[0] || activeTaskId || "");
        setSearchTasksData((previous: any) => {
          const mergedRows = applyLocalReadStateToRows(mergeTaskRowsPreferLatest([taskRows(previous), incomingRows], activeSortId));
          const incomingPagination = taskPagination(result);
          return {
            ...(previous || {}),
            queue: resultQueue,
            tasks: mergedRows,
            pagination: {
              ...incomingPagination,
              returned: mergedRows.length,
            },
          };
        });
      } catch (err) {
        setError(errorText(err, "加载更多搜索结果失败"));
      } finally {
        searchLoadMoreInFlightRef.current = false;
        setSearchLoadingMoreTasks(false);
      }
      return;
    }
    if (!service || loadingMoreTasks || loadMoreInFlightRef.current) return;
    const beforeId = String(taskPagination(tasksData).nextBeforeId || "");
    if (!beforeId) return;
    loadMoreInFlightRef.current = true;
    setLoadingMoreTasks(true);
    setError("");
    try {
      const result = await loadTaskPage(apiBaseUrl, selectedQueueId, beforeId);
      const incomingRows = taskRows(result);
      const resultQueue = result?.queue || queue || {};
      const activeSortId = String(resultQueue?.activeTaskId || activeTaskIds(resultQueue)[0] || activeTaskId || "");
      setTasksData((previous: any) => {
        const mergedRows = applyLocalReadStateToRows(mergeTaskRowsPreferLatest([taskRows(previous), incomingRows], activeSortId));
        const incomingPagination = taskPagination(result);
        return {
          ...(previous || {}),
          queue: resultQueue,
          statistics: result?.statistics || previous?.statistics,
          tasks: mergedRows,
          pagination: {
            ...incomingPagination,
            returned: mergedRows.length,
          },
        };
      });
    } catch (err) {
      setError(errorText(err, "加载更早 Codex tasks 失败"));
    } finally {
      loadMoreInFlightRef.current = false;
      setLoadingMoreTasks(false);
    }
  }

  function handleTaskListScroll(event: any): void {
    const element = event.currentTarget as HTMLElement;
    if (!element || sidebarLoadingMoreTasks || !sidebarHasMoreTasks) return;
    const distanceToBottom = element.scrollHeight - element.scrollTop - element.clientHeight;
    if (distanceToBottom < 120) void loadMoreTasks();
  }

  async function guarded(action: () => Promise<void>, message: string): Promise<void> {
    setBusy(true);
    setError("");
    try {
      await action();
    } catch (err) {
      setError(errorText(err, message));
    } finally {
      setBusy(false);
    }
  }

  async function copyTaskId(taskId: string): Promise<void> {
    if (!taskId) return;
    try {
      let copied = false;
      try {
        if (navigator.clipboard?.writeText) {
          await navigator.clipboard.writeText(taskId);
          copied = true;
        }
      } catch {
        copied = false;
      }
      if (!copied) {
        const textarea = document.createElement("textarea");
        textarea.value = taskId;
        textarea.style.position = "fixed";
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.select();
        copied = document.execCommand("copy");
        document.body.removeChild(textarea);
      }
      if (!copied) throw new Error("browser clipboard rejected the copy request");
      setCopiedTaskId(taskId);
      const msg = `已复制任务 ID：${taskId}`;
      setNotice(msg);
      addNotification("success", msg);
      window.setTimeout(() => setCopiedTaskId((value: string) => value === taskId ? "" : value), 1600);
    } catch (err) {
      setError(`复制任务 ID 失败：${errorText(err)}`);
    }
  }

  function referenceTask(taskId: string): void {
    if (!taskId) return;
    setReferenceTaskId(taskId);
    const msg = `已引用任务 ID：${taskId}；提交时后端会读取并注入该任务上下文`;
    setNotice(msg);
    addNotification("success", msg);
  }

  async function markTaskRead(taskId: string): Promise<void> {
    if (!service || !taskId) return;
    const optimisticReadAt = new Date().toISOString();
    queueLoadTokenRef.current += 1;
    patchLoadedReadState([taskId], optimisticReadAt, null, { id: taskId, readAt: optimisticReadAt, terminalUnread: false });
    setMarkingReadTaskId(taskId);
    let marked = false;
    await guarded(async () => {
      const result = await markTaskReadRequest(apiBaseUrl, taskId);
      const task = result?.task || { id: taskId, readAt: new Date().toISOString(), terminalUnread: false };
      const readAt = String(task?.readAt || new Date().toISOString());
      patchLoadedReadState([taskId], readAt, result?.queue || null, task);
      marked = true;
      const msg = `已将任务 ${taskId} 标为已读`;
      setNotice(msg);
      addNotification("success", msg);
    }, "标记 Codex task 已读失败");
    if (!marked) {
      forgetLocalReadState([taskId]);
      void load(selectedIdRef.current, false).catch((err) => setError(errorText(err, "刷新 Codex tasks 失败")));
    }
    setMarkingReadTaskId((value: string) => value === taskId ? "" : value);
  }

  async function markAllTerminalRead(): Promise<void> {
    if (!service || markingAllRead) return;
    setMarkingAllRead(true);
    const optimisticReadAt = new Date().toISOString();
    const optimisticReadIds = Array.from(new Set([
      ...taskRows(tasksDataRef.current)
        .filter(taskIsUnreadTerminal)
        .map((task: any) => String(task?.id || ""))
        .filter(Boolean),
      ...(Array.from(sessionCacheRef.current.entries()) as [string, AnyRecord][])
        .filter(([, value]) => taskIsUnreadTerminal(value?.task))
        .map(([id]) => id),
    ]));
    queueLoadTokenRef.current += 1;
    if (optimisticReadIds.length > 0) patchLoadedReadState(optimisticReadIds, optimisticReadAt);
    let marked = false;
    await guarded(async () => {
      const result = await markAllTerminalReadRequest(apiBaseUrl);
      const readAt = String(result?.readAt || new Date().toISOString());
      const loadedUnreadIds = taskRows(tasksDataRef.current)
        .filter(taskIsUnreadTerminal)
        .map((task: any) => String(task?.id || ""))
        .filter(Boolean);
      const cachedUnreadIds = (Array.from(sessionCacheRef.current.entries()) as [string, AnyRecord][])
        .filter(([, value]) => taskIsUnreadTerminal(value?.task))
        .map(([id]) => id);
      const readIds = Array.from(new Set([...optimisticReadIds, ...loadedUnreadIds, ...cachedUnreadIds]));
      patchLoadedReadState(readIds, readAt, result?.queue || null);
      const markedCount = Number(result?.count || readIds.length);
      marked = true;
      const msg = `已将 ${markedCount} 个已结束未读任务标为已读`;
      setNotice(msg);
      addNotification("success", msg);
    }, "全部标为已读失败");
    if (!marked && optimisticReadIds.length > 0) {
      forgetLocalReadState(optimisticReadIds);
      void load(selectedIdRef.current, false).catch((err) => setError(errorText(err, "刷新 Codex tasks 失败")));
    }
    setMarkingAllRead(false);
  }

  function changeSelectedQueue(nextQueueId: string): void {
    const next = nextQueueId || allQueuesId;
    setSelectedQueueId(next);
    if (!isAllQueues(next)) setQueueId(next);
    setTasksData(null);
    const keepSelected = isAllQueues(next) ? selectedIdRef.current : "";
    if (!keepSelected) {
      selectedIdRef.current = "";
      detailLoadTokenRef.current += 1;
      setSelectedId("");
      setSelectedTask(null);
      setSelectedDetailLoading(true);
    }
  }

  async function loadWorkdirs(): Promise<void> {
    if (!service) return;
    const result = await requestJson(codexApi(apiBaseUrl, "/api/workdirs"));
    setWorkdirData(result);
  }

  async function createWorkdirPreset(): Promise<void> {
    const defaultPath = cwd.trim() || currentProviderDefaultWorkdir || "/workspace";
    const proposed = typeof window === "undefined" ? defaultPath : window.prompt("输入新的工作目录绝对路径", defaultPath);
    const path = String(proposed || "").trim();
    if (!path) return;
    setWorkdirBusy(true);
    await guarded(async () => {
      const result = await requestJson(codexApi(apiBaseUrl, "/api/workdirs"), {
        method: "POST",
        body: { providerId, executionMode, path, ensure: true },
      });
      setWorkdirData((previous: any) => ({ ...(previous || {}), ...result }));
      setCwd(String(result?.workdir?.path || path));
      const msg = `已保存工作目录：${String(result?.workdir?.path || path)}`;
      setNotice(msg);
      addNotification("success", msg);
    }, "创建工作目录失败");
    setWorkdirBusy(false);
  }

  async function deleteWorkdirPreset(): Promise<void> {
    const path = normalizedWorkdirPath(cwd);
    if (!currentWorkdirSaved) {
      setNotice("当前工作目录还没有保存到下拉菜单。");
      return;
    }
    const confirmed = typeof window === "undefined" ? true : window.confirm(`从下拉菜单删除工作目录选项？\n${path}\n\n不会删除磁盘上的实际目录。`);
    if (!confirmed) return;
    setWorkdirBusy(true);
    await guarded(async () => {
      const result = await requestJson(codexApi(apiBaseUrl, `/api/workdirs/${encodeURIComponent(providerId)}/${encodeURIComponent(executionMode)}/${encodeURIComponent(path)}`), { method: "DELETE" });
      setWorkdirData((previous: any) => ({ ...(previous || {}), ...result }));
      const msg = `已从下拉菜单删除工作目录：${path}`;
      setNotice(msg);
      addNotification("success", msg);
    }, "删除工作目录失败");
    setWorkdirBusy(false);
  }

  async function createQueue(): Promise<void> {
    const proposed = typeof window === "undefined" ? "" : window.prompt("输入新的 Codex queue ID（字母/数字/._-，最长 64）", "new-lane");
    const nextQueueId = String(proposed || "").trim();
    if (!nextQueueId) return;
    await guarded(async () => {
      const result = await requestJson(codexApi(apiBaseUrl, "/api/queues"), { method: "POST", body: { queueId: nextQueueId } });
      const createdId = String(result?.queue?.id || nextQueueId);
      setQueueId(createdId);
      setSelectedQueueId(createdId);
      setTasksData(null);
      selectedIdRef.current = "";
      detailLoadTokenRef.current += 1;
      setSelectedId("");
      setSelectedTask(null);
      const msg = `已创建并切换到 queue：${createdId}`;
      setNotice(msg);
      addNotification("success", msg);
      await load("", true, createdId);
    }, "创建 Codex queue 失败");
  }

  async function renameQueue(): Promise<void> {
    const targetQueueId = String(queueId || "default").trim() || "default";
    const row = selectedQueueRow(queueRows, targetQueueId) || { id: targetQueueId, name: targetQueueId };
    const proposed = typeof window === "undefined"
      ? null
      : window.prompt(`输入 queue 显示名称（ID 不变：${targetQueueId}；留空恢复为 ID）`, queueName(row));
    if (proposed === null) return;
    await guarded(async () => {
      const result = await requestJson(codexApi(apiBaseUrl, `/api/queues/${encodeURIComponent(targetQueueId)}`), { method: "PATCH", body: { name: String(proposed) } });
      const updatedQueue = result?.queue || { id: targetQueueId, name: String(proposed || targetQueueId) };
      if (result?.summary) {
        setTasksData((previous: any) => previous ? { ...previous, queue: result.summary } : previous);
      }
      const msg = `已更新 queue 名称：${queueDisplayName(updatedQueue)}`;
      setNotice(msg);
      addNotification("success", msg);
      await load(selectedIdRef.current, true, selectedQueueId);
    }, "修改 Codex queue 名称失败");
  }

  function openMergeQueueDialog(): void {
    if (mergeSourceQueueRows.length === 0) {
      const msg = "没有可合并的其他 queue；请先创建或选择另一个 queue。";
      setNotice(msg);
      return;
    }
    const existingSource = mergeSourceQueueRows.some((row: any) => String(row?.id || "") === mergeSourceQueueId)
      ? mergeSourceQueueId
      : "";
    setMergeSourceQueueId(existingSource);
    setMergeDialogOpen(true);
  }

  async function mergeQueue(): Promise<void> {
    const targetQueueId = mergeTargetQueueId;
    if (mergeSourceQueueRows.length === 0) {
      const msg = "没有可合并的其他 queue；请先创建或选择另一个 queue。";
      setNotice(msg);
      return;
    }
    const proposed = mergeSourceQueueId || "";
    const sourceQueueId = String(proposed || "").trim();
    if (!sourceQueueId) {
      setNotice("请先选择要合并的源 queue。");
      return;
    }
    if (sourceQueueId === targetQueueId) {
      setError("源 queue 和目标 queue 不能相同。");
      return;
    }
    await guarded(async () => {
      const result = await requestJson(codexApi(apiBaseUrl, `/api/queues/${encodeURIComponent(targetQueueId)}/merge`), { method: "POST", body: { sourceQueueId } });
      if (result?.summary) {
        setTasksData((previous: any) => previous ? { ...previous, queue: result.summary } : previous);
      }
      setQueueId(targetQueueId);
      setSelectedQueueId(targetQueueId);
      setTasksData(null);
      const count = Number(result?.mergedTaskCount || 0);
      const msg = `已将 queue=${sourceQueueId} 合并到 ${targetQueueId}，移动 ${count} 个任务；源 queue 已自动删除。`;
      setNotice(msg);
      addNotification("success", msg);
      setMergeDialogOpen(false);
      setMergeSourceQueueId("");
      await load(selectedIdRef.current, true, targetQueueId);
    }, "合并 Codex queue 失败");
  }

  async function enqueue(event: any): Promise<void> {
    event.preventDefault();
    if (enqueueInFlightRef.current) {
      const msg = "任务正在提交中，请等待当前请求完成，已阻止重复提交。";
      setNotice(msg);
      return;
    }
    if (enqueueItems.length > 1 && !batchConfirmed) {
      setError(`检测到将创建 ${enqueueItems.length} 个任务；请先勾选“确认批量入队”，避免误传多个任务。`);
      return;
    }
    enqueueInFlightRef.current = true;
    setSubmitting(true);
    setNotice("正在提交 Code Queue 任务，请等待后端确认，输入已临时锁定。");
    await guarded(async () => {
      if (enqueueItems.length === 0) throw new Error("prompt 不能为空");
      const referenceTaskIds = parseReferenceTaskIds(referenceTaskId);
      const submitQueueId = queueId.trim() || "default";
      const submittingItems = [...enqueueItems];
      const taskPayload = (text: string) => ({
        prompt: text,
        queueId: submitQueueId,
        providerId,
        executionMode,
        model,
        cwd,
        maxAttempts: Number(maxAttempts),
        ...(referenceTaskIds.length > 0 ? { referenceTaskIds } : {}),
      });
      const body = submittingItems.length === 1
        ? taskPayload(submittingItems[0])
        : { tasks: submittingItems.map(taskPayload) };
      const result = await requestJson(codexApi(apiBaseUrl, submittingItems.length === 1 ? "/api/tasks" : "/api/tasks/batch"), { method: "POST", body });
      const firstId = result?.tasks?.[0]?.id || "";
      const ids = Array.isArray(result?.tasks) ? result.tasks.map((task: any) => String(task?.id || "")).filter(Boolean) : [];
      const msg = `已创建 ${ids.length || submittingItems.length} 个任务${ids.length > 0 ? `：${ids.join(" / ")}` : ""}`;
      mergeCreatedTasksIntoCurrentView(Array.isArray(result?.tasks) ? result.tasks : [], result?.queue || null);
      setNotice(msg);
      addNotification("success", msg);
      setPrompt("");
      setReferenceTaskId("");
      setBatchConfirmed(false);
      setQueueId(submitQueueId);
      if (firstId && taskVisibleInQueueFilter(result?.tasks?.[0], selectedQueueId) && taskMatchesCurrentSearch(result?.tasks?.[0])) {
        void ensureTraceSummary(String(firstId), false).catch((err) => setError(errorText(err, "加载 Codex Trace Summary 失败")));
      }
    }, "Codex 任务入队失败");
    enqueueInFlightRef.current = false;
    setSubmitting(false);
  }

  async function steer(event: any): Promise<void> {
    event.preventDefault();
    if (!selectedTask?.id) return;
    await guarded(async () => {
      await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(selectedTask.id)}/steer`), { method: "POST", body: { prompt: steerPrompt } });
      setSteerPrompt("");
      await load(selectedTask.id);
    }, "追加 prompt 失败");
  }

  async function editSelectedQueuedPrompt(event: any): Promise<void> {
    event.preventDefault();
    const taskId = String(selectedTask?.id || "");
    if (!taskId || !selectedCanEditPrompt) return;
    await guarded(async () => {
      const referenceTaskIds = parseReferenceTaskIds(editReferenceTaskId);
      const result = await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/edit`), {
        method: "POST",
        body: { prompt: editPrompt, referenceTaskIds },
      });
      const updatedTask = {
        ...(result?.task || selectedTask || {}),
        _traceSummary: null,
        _traceSummaryLoaded: false,
        _traceSummaryUpdatedAt: "",
        _promptDetails: {},
        _traceSteps: [],
        _traceStepsLoaded: false,
        _traceStepsByAttempt: {},
        _traceStepsLoadedByAttempt: {},
        _traceStepsNextAfterSeqByAttempt: {},
        _traceStepDetails: {},
      };
      sessionCacheRef.current.set(taskId, { ...(sessionCacheRef.current.get(taskId) || {}), task: updatedTask, complete: false, completeUpdatedAt: "" });
      selectedIdRef.current = taskId;
      setSelectedTask(updatedTask);
      setSelectedId(taskId);
      setEditPrompt(taskBasePromptText(updatedTask));
      setEditReferenceTaskId(Array.isArray(updatedTask?.referenceTaskIds) ? updatedTask.referenceTaskIds.join(" ") : "");
      setTasksData((previous: any) => {
        if (!previous) return previous;
        const rows = taskRows(previous).map((task: any) => String(task?.id || "") === taskId ? { ...task, ...updatedTask } : task);
        return { ...previous, queue: result?.queue || previous.queue, tasks: mergeTaskRowsPreferLatest([rows], activeTaskId) };
      });
      const msg = result?.changed === false ? `任务 ${taskId} 的 prompt 未变化` : `已更新 queued 任务 ${taskId} 的用户 prompt`;
      setNotice(msg);
      addNotification("success", msg);
      await load(taskId, true, selectedQueueId);
    }, "编辑 queued 任务 prompt 失败");
  }

  async function interrupt(): Promise<void> {
    if (!selectedTask?.id) return;
    await guarded(async () => {
      await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(selectedTask.id)}/interrupt`), { method: "POST", body: {} });
      await load(selectedTask.id);
    }, "打断 Codex session 失败");
  }

  async function retry(): Promise<void> {
    if (!selectedTask?.id) return;
    await guarded(async () => {
      await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(selectedTask.id)}/retry`), { method: "POST", body: {} });
      await load(selectedTask.id);
    }, "重新入队失败");
  }

  async function moveSelectedTaskQueue(targetQueueId: string): Promise<void> {
    const taskId = String(selectedTask?.id || "");
    const nextQueueId = String(targetQueueId || "").trim();
    if (!taskId || !nextQueueId) return;
    const currentQueue = taskQueueLabel(selectedTask);
    if (nextQueueId === currentQueue) {
      setNotice(`任务 ${taskId} 已在 queue=${nextQueueId}`);
      return;
    }
    await guarded(async () => {
      const result = await requestJson(codexApi(apiBaseUrl, `/api/tasks/${encodeURIComponent(taskId)}/move`), { method: "POST", body: { queueId: nextQueueId } });
      const movedTask = result?.task || { ...selectedTask, queueId: nextQueueId };
      sessionCacheRef.current.set(taskId, { ...(sessionCacheRef.current.get(taskId) || {}), task: movedTask });
      selectedIdRef.current = taskId;
      setSelectedTask(movedTask);
      setSelectedId(taskId);
      setQueueId(nextQueueId);
      if (!isAllQueues(selectedQueueId)) {
        setTasksData(null);
        setSelectedQueueId(nextQueueId);
      }
      const msg = `已将任务 ${taskId} 从 ${currentQueue} 移动到 ${nextQueueId}`;
      setNotice(msg);
      addNotification("success", msg);
      await load(taskId, true, isAllQueues(selectedQueueId) ? allQueuesId : nextQueueId);
    }, "移动任务 queue 失败");
  }

  async function loadFullTrace(): Promise<void> {
    const taskId = selectedIdRef.current;
    if (!taskId) return;
    const startedAt = performance.now();
    await guarded(async () => {
      setLoadStats({
        phase: "session",
        taskId,
        queueMs: 0,
        totalMs: 0,
        partial: true,
        startedAt: new Date(),
      });
      await ensureTraceSummary(taskId, true, startedAt, 0);
    }, "刷新 Trace Summary 失败");
  }

  function selectTask(taskId: string): void {
    selectedIdRef.current = taskId;
    detailLoadTokenRef.current += 1;
    setSelectedId(taskId);
    const cached = sessionCacheRef.current.get(taskId);
    if (cached?.task) {
      setSelectedTask(cached.task);
      setSelectedDetailLoading(false);
    } else {
      setSelectedDetailLoading(true);
      const row = tasks.find((task: any) => task.id === taskId);
      if (row) setSelectedTask(row);
      else setSelectedTask(null);
    }
    void load(taskId).catch((err) => setError(errorText(err, "切换 Codex session 失败")));
  }

  function selectTaskFromSidebar(taskId: string): void {
    selectTask(taskId);
    if (isMobileQueueViewport()) setQueueSidebarOpen(false);
  }

  function patchRowsForTaskEvent(data: any, taskId: string, patch: AnyRecord): any {
    if (!data || !Array.isArray(data?.tasks) || taskId.length === 0 || Object.keys(patch).length === 0) return data;
    let changed = false;
    const rows = taskRows(data).map((task: any) => {
      if (String(task?.id || "") !== taskId) return task;
      changed = true;
      return taskWithLocalReadState(mergeTaskPatch(task, patch));
    });
    return changed ? { ...data, tasks: rows } : data;
  }

  function patchSidebarTaskFromEvent(taskId: string, patch: AnyRecord): void {
    setTasksData((previous: any) => patchRowsForTaskEvent(previous, taskId, patch));
    setSearchTasksData((previous: any) => patchRowsForTaskEvent(previous, taskId, patch));
  }

  function taskEventNeedsOverviewRefresh(event: AnyRecord, taskId: string, previousTask: any): boolean {
    const type = String(event?.type || "");
    if (type === "queue-updated") return true;
    if (type === "trace-stats-updated" || type === "trace-step-created") return false;
    if (taskId.length === 0) return true;
    if (!previousTask) return true;
    if (event?.queueId && String(event.queueId) !== taskQueueLabel(previousTask)) return true;
    if (event?.status && String(event.status) !== String(previousTask?.status || "")) return true;
    return String(event?.reason || "") !== "output";
  }

  function scheduleEventDrivenOverviewRefresh(): void {
    if (!service || !isDocumentVisible()) return;
    if (eventRefreshTimerRef.current !== null) window.clearTimeout(eventRefreshTimerRef.current);
    eventRefreshTimerRef.current = window.setTimeout(() => {
      eventRefreshTimerRef.current = null;
      // SSE refreshes should update the sidebar data around the user's current
      // selection, not jump to whichever task emitted the latest event.
      void load(selectedIdRef.current, false).catch((err) => setError(errorText(err, "Code Queue 事件刷新失败")));
    }, 120);
  }

  function scheduleSelectedTraceEventRefresh(taskId: string, includeSteps: boolean): void {
    if (!service || !isDocumentVisible() || selectedIdRef.current !== taskId) return;
    traceEventRefreshPendingStepsRef.current = traceEventRefreshPendingStepsRef.current || includeSteps;
    if (traceEventRefreshTimerRef.current !== null) return;
    traceEventRefreshTimerRef.current = window.setTimeout(() => {
      traceEventRefreshTimerRef.current = null;
      const refreshSteps = traceEventRefreshPendingStepsRef.current;
      traceEventRefreshPendingStepsRef.current = false;
      void ensureTraceSummary(taskId, true).catch((err) => setError(errorText(err, "事件刷新 Trace Summary 失败")));
      if (refreshSteps) refreshLoadedTraceSteps(taskId);
    }, 250);
  }

  function normalizeOaCodeQueueEvent(event: AnyRecord): AnyRecord {
    const payload = objectRecord(event?.payload) || event;
    const stats = objectRecord(payload?.stats);
    const type = String(event?.type || payload?.type || "");
    const subjectKind = String(payload?.subjectKind || stats?.subjectKind || "");
    const scopeId = String(payload?.scopeId || stats?.scopeId || "");
    const taskId = String(payload?.taskId || (subjectKind === "task" ? payload?.subjectId : "") || stats?.taskId || event?.taskId || "");
    const attemptValue = payload?.attemptIndex ?? stats?.attemptIndex;
    const attemptIndex = attemptValue === null || attemptValue === undefined || attemptValue === "" ? null : statCount(attemptValue);
    const traceStats = stats || objectRecord(payload?.traceStats);
    const stepCount = traceStats?.stepCount ?? traceStats?.llmStepCount;
    const outputMaxSeq = traceStats?.outputMaxSeq;
    return {
      ...payload,
      type,
      eventId: event?.eventId || payload?.eventId,
      sequence: event?.sequence ?? payload?.sequence,
      taskId,
      subjectKind,
      scopeId,
      attemptIndex,
      stepCount,
      outputMaxSeq,
      updatedAt: traceStats?.updatedAt || payload?.updatedAt || event?.createdAt,
      traceStats,
      statsSource: traceStats ? "oa-event-flow" : payload?.statsSource,
    };
  }

  function applyCodeQueueEvent(event: AnyRecord): void {
    const normalizedEvent = normalizeOaCodeQueueEvent(event);
    const taskId = String(normalizedEvent?.taskId || "");
    const scopeId = String(normalizedEvent?.scopeId || normalizedEvent?.traceStats?.scopeId || "");
    const isAttemptStats = String(normalizedEvent?.subjectKind || normalizedEvent?.traceStats?.subjectKind || "") === "task-attempt"
      || Number(normalizedEvent?.attemptIndex) > 0
      || /:attempt:\d+$/u.test(scopeId);
    const stepCount = nonNegativeCount(normalizedEvent?.stepCount);
    const patch: AnyRecord = {};
    const previousTask = taskId.length > 0
      ? taskRows(tasksDataRef.current).find((task: any) => String(task?.id || "") === taskId)
      : null;
    if (taskId.length > 0) {
      if (normalizedEvent?.status) patch.status = String(normalizedEvent.status);
      if (normalizedEvent?.updatedAt) patch.updatedAt = String(normalizedEvent.updatedAt);
      if (normalizedEvent?.queueId) patch.queueId = String(normalizedEvent.queueId);
      if (!isAttemptStats && Number.isFinite(Number(normalizedEvent?.stepCount))) {
        patch.stepCount = stepCount;
        patch.llmStepCount = stepCount;
      }
      if (!isAttemptStats && Number.isFinite(Number(normalizedEvent?.outputMaxSeq))) patch.outputMaxSeq = nonNegativeCount(normalizedEvent.outputMaxSeq);
      if (!isAttemptStats && objectRecord(normalizedEvent?.traceStats)) {
        patch.traceStats = normalizedEvent.traceStats;
        patch.statsSource = "oa-event-flow";
      }
      if (Object.keys(patch).length > 0 && (sessionCacheRef.current.has(taskId) || selectedIdRef.current === taskId)) {
        publishCachedTask(taskId, patch, detailLoadTokenRef.current);
      }
      if (Object.keys(patch).length > 0) patchSidebarTaskFromEvent(taskId, patch);
      if (selectedIdRef.current === taskId && (normalizedEvent?.type === "trace-step-created" || normalizedEvent?.type === "task-updated" || normalizedEvent?.type === "trace-stats-updated")) {
        const previousStepCount = canonicalTaskStepCount(previousTask);
        const shouldRefreshSteps = normalizedEvent?.type === "trace-step-created"
          || (normalizedEvent?.type === "trace-stats-updated" && Number.isFinite(Number(normalizedEvent?.stepCount)) && (isAttemptStats || previousStepCount === null || stepCount > previousStepCount));
        scheduleSelectedTraceEventRefresh(taskId, shouldRefreshSteps);
      }
    }
    if (taskEventNeedsOverviewRefresh(normalizedEvent, taskId, previousTask)) scheduleEventDrivenOverviewRefresh();
  }

  useEffect(() => {
    if (initialLoadSkippedRef.current) {
      initialLoadSkippedRef.current = false;
      return;
    }
    void guarded(() => load(selectedIdRef.current), "Code Queue 加载失败");
  }, [service?.id, selectedQueueId]);

  useEffect(() => {
    if (!service || typeof EventSource === "undefined") return undefined;
    const source = new EventSource(oaCodeQueueEventsApi(apiBaseUrl), { withCredentials: true });
    const onEvent = (message: MessageEvent): void => {
      try {
        applyCodeQueueEvent(JSON.parse(String(message.data || "{}")));
      } catch (err) {
        setError(errorText(err, "解析 Code Queue 事件失败"));
      }
    };
    const onVisible = (): void => {
      if (isDocumentVisible()) scheduleEventDrivenOverviewRefresh();
    };
    source.addEventListener("trace-step-created", onEvent);
    source.addEventListener("task-updated", onEvent);
    source.addEventListener("queue-updated", onEvent);
    source.addEventListener("trace-stats-updated", onEvent);
    document.addEventListener("visibilitychange", onVisible);
    return () => {
      source.close();
      document.removeEventListener("visibilitychange", onVisible);
      if (eventRefreshTimerRef.current !== null) {
        window.clearTimeout(eventRefreshTimerRef.current);
        eventRefreshTimerRef.current = null;
      }
      if (traceEventRefreshTimerRef.current !== null) {
        window.clearTimeout(traceEventRefreshTimerRef.current);
        traceEventRefreshTimerRef.current = null;
      }
    };
  }, [service?.id, apiBaseUrl, selectedQueueId]);

  useEffect(() => {
    if (!service || !selectedTask || selectedDetailLoading) return;
    const taskId = String(selectedTask.id || "");
    if (!taskId) return;
    const updatedAt = String(selectedTask.updatedAt || "");
    if (traceSummaryIsCurrent(selectedTask)) return;
    const key = `${taskId}:${updatedAt || "unknown"}:${String(selectedTask?._traceSummaryUpdatedAt || "")}`;
    if (autoTraceLoadKeysRef.current.has(key)) return;
    autoTraceLoadKeysRef.current.add(key);
    void ensureTraceSummary(taskId, true).catch((err) => setError(errorText(err, "自动加载 Trace Summary 失败")));
  }, [service?.id, selectedTask?.id, selectedTask?.updatedAt, selectedTask?.traceStats?.statsRevision, selectedTask?._traceSummaryUpdatedAt, selectedTask?._traceSummaryLoaded, selectedDetailLoading]);

  useEffect(() => {
    if (!service || !selectedTask || selectedDetailLoading) return;
    const taskId = String(selectedTask.id || "");
    const currentAttempt = Number(taskTraceSummary(selectedTask)?.currentAttempt || selectedTask?.currentAttempt || 0);
    if (!taskId || !taskIsExecuting(selectedTask) || !Number.isFinite(currentAttempt) || currentAttempt <= 0) return;
    if (taskTraceStepsLoaded(selectedTask, currentAttempt)) return;
    const key = `${taskId}:current-attempt:${currentAttempt}:${String(selectedTask?.updatedAt || "")}`;
    if (autoTraceLoadKeysRef.current.has(key)) return;
    autoTraceLoadKeysRef.current.add(key);
    void ensureTraceSteps(currentAttempt).catch((err) => setError(errorText(err, "自动加载当前 Attempt Trace Steps 失败")));
  }, [service?.id, selectedTask?.id, selectedTask?.status, selectedTask?.currentAttempt, selectedTask?.updatedAt, selectedTask?._traceSummaryUpdatedAt, selectedDetailLoading]);

  useEffect(() => {
    if (!service) return undefined;
    void loadWorkdirs().catch((err) => setError(errorText(err, "加载工作目录失败")));
    return undefined;
  }, [service?.id]);

  useEffect(() => {
    if (!service) return undefined;
    void refreshStatistics(selectedQueueId);
    return undefined;
  }, [service?.id, apiBaseUrl, selectedQueueId]);

  const taskListContent = sidebarTasks.length === 0 ? h(EmptyState, {
    title: searchActive ? (searchLoading ? "搜索中" : "没有匹配任务") : "队列为空",
    text: searchActive ? (searchLoading ? `正在搜索包含“${normalizedSearchQuery}”的 task...` : `未找到包含“${normalizedSearchQuery}”的 task；可换个关键词或切换 queue。`) : "提交一个任务后，Codex 会串行执行并保存输出。",
  }) : [
    unreadTerminalTasks.length > 0 ? h(TaskListSection, {
      key: "unread",
      title: "已结束未读",
      tasks: unreadTerminalTasks,
      selectedId,
      emptyText: "暂无已结束未读任务。",
      onSelect: selectTaskFromSidebar,
      onCopy: copyTaskId,
      onReference: referenceTask,
      onMarkRead: markTaskRead,
      copiedTaskId,
      markingReadTaskId,
    }) : null,
    h(TaskListSection, {
      key: "active",
      title: "运行 / 排队",
      tasks: queuedTasks,
      selectedId,
      emptyText: "当前没有运行或排队任务。",
      onSelect: selectTaskFromSidebar,
      onCopy: copyTaskId,
      onReference: referenceTask,
      onMarkRead: markTaskRead,
      copiedTaskId,
      markingReadTaskId,
    }),
    h(TaskListSection, {
      key: "history",
      title: "历史 session",
      tasks: historyTasks,
      selectedId,
      emptyText: "最近没有完成、失败或取消的 session。",
      onSelect: selectTaskFromSidebar,
      onCopy: copyTaskId,
      onReference: referenceTask,
      onMarkRead: markTaskRead,
      copiedTaskId,
      markingReadTaskId,
    }),
    h("div", { key: "pagination", className: "codex-task-pagination", "data-testid": "codex-task-pagination" },
      h("span", null, searchActive
        ? `搜索“${normalizedSearchQuery}” · 已显示 ${sidebarTasks.length} / ${Number.isFinite(sidebarTotalTaskCount) ? sidebarTotalTaskCount : sidebarTasks.length}`
        : `已加载 ${sidebarTasks.length} / ${Number.isFinite(sidebarTotalTaskCount) ? sidebarTotalTaskCount : sidebarTasks.length}`),
      sidebarHasMoreTasks ? h("button", {
        type: "button",
        className: "ghost-btn",
        disabled: sidebarLoadingMoreTasks,
        onClick: () => void loadMoreTasks(),
        "data-testid": "codex-load-more-tasks-button",
      }, sidebarLoadingMoreTasks ? "加载中" : (searchActive ? "加载更多结果" : "加载更早任务")) : h("code", null, searchActive ? "已到结果末尾" : "已到队列末尾"),
    ),
  ];

  const queueSelector = (testId: string, compact = false) => h("label", { className: `code-queue-switcher ${compact ? "compact" : ""}` },
    h("span", null, compact ? "Queue" : "查看 queue"),
    h("select", { value: selectedQueueId, onChange: (event: any) => changeSelectedQueue(String(event.target.value || allQueuesId)), "data-testid": testId },
      h("option", { value: allQueuesId }, `All queues · ${Number.isFinite(totalTaskCount) ? totalTaskCount : tasks.length} tasks · ${globalActiveIds.length} running`),
      queueRows.map((row: any) => h("option", { key: String(row?.id || ""), value: String(row?.id || "") }, queueOptionLabel(row))),
    ),
  );

  const taskSearchControl = h("div", { className: "codex-task-search", "data-testid": "codex-task-search" },
    h("label", { htmlFor: "codex-task-search-input" }, "搜索 task"),
    h("div", { className: "codex-task-search-row" },
      h("input", {
        id: "codex-task-search-input",
        type: "search",
        value: taskSearchQuery,
        placeholder: "关键词 / task ID / prompt",
        autoComplete: "off",
        onChange: (event: any) => setTaskSearchQuery(String(event.target.value || "")),
        "data-testid": "codex-task-search-input",
      }),
      taskSearchQuery ? h("button", {
        type: "button",
        className: "ghost-btn",
        onClick: () => setTaskSearchQuery(""),
        "data-testid": "codex-task-search-clear",
      }, "清除") : null,
    ),
    h("small", { "data-testid": "codex-task-search-summary" }, searchActive
      ? (searchLoading ? "搜索中..." : `匹配 ${sidebarTasks.length}/${Number.isFinite(sidebarTotalTaskCount) ? sidebarTotalTaskCount : sidebarTasks.length}`)
      : "支持 task ID、prompt、状态、provider、模型和最近输出关键词"),
  );

  const traceStatusSummary = h("div", { className: "codex-trace-status", "data-testid": "codex-trace-status-summary" },
    h("span", { className: "codex-trace-status-chip queued" }, h("b", null, "排队"), String(overallQueuedCount)),
    h("span", { className: "codex-trace-status-chip running" }, h("b", null, "运行"), String(overallRunningCount)),
    h("span", { className: `codex-trace-status-chip unread ${overallUnreadTerminalCount > 0 ? "warn" : ""}` }, h("b", null, "结束未读"), String(overallUnreadTerminalCount)),
    h("span", { className: "codex-trace-status-chip service" }, h("b", null, "服务"), `${runtime.providerStatus || "unknown"} · ${service?.providerId || "D601"} · ${backend.public ? "公网暴露" : "仅 UniDesk frontend 代理访问"}`),
    h("span", { className: "codex-trace-status-chip" }, h("b", null, "执行节点"), providerOptions.map((provider: any) => provider.id).join(" / ")),
    h("span", { className: "codex-trace-status-chip" }, h("b", null, "执行模式"), executionModeRows.map((mode: any) => mode.id).join(" / ")),
    h("span", { className: "codex-trace-status-chip" }, h("b", null, "模型"), codexModels.join(" / ")),
    h("span", { className: "codex-trace-status-chip" }, h("b", null, "加载"), loadStats?.phase === "complete" ? fmtPreciseMs(loadStats?.totalMs) : String(loadStats?.phase || "idle")),
    h("span", { className: "codex-trace-status-chip" }, h("b", null, "刷新"), refreshedAt ? fmtClock(refreshedAt) : "--"),
  );

  const sessionPanel = h(Panel, {
    title: selectedTask ? `Trace ${String(selectedTask.id).slice(0, 22)}` : "Trace 输出",
    eyebrow: selectedTask ? `${selectedTask.status} / view=${selectedQueueName} / task queue=${taskQueueLabel(selectedTask)} / provider=${selectedTask.providerId || "D601"} / mode=${selectedTask.executionMode || "default"} / ${selectedTask.model} / agent loop trace` : `Agent loop trace / view=${selectedQueueName}`,
    summary: traceStatusSummary,
    loading: selectedDetailLoading || loadingMoreTasks || searchLoading || searchLoadingMoreTasks || loadStats?.phase === "loading",
    actions: h("div", { className: "panel-actions" },
      queueSelector("code-queue-filter-select"),
      h("button", {
        type: "button",
        className: "ghost-btn codex-mark-all-read-btn",
        disabled: overallUnreadTerminalCount === 0 || busy || markingAllRead,
        onClick: () => void markAllTerminalRead(),
        "data-testid": "codex-mark-all-read-button",
      }, markingAllRead ? "标记中" : `全部标已读${overallUnreadTerminalCount > 0 ? ` (${overallUnreadTerminalCount})` : ""}`),
      selectedTask ? h("button", {
        type: "button",
        className: "ghost-btn",
        disabled: selectedDetailLoading || busy,
        onClick: () => void loadFullTrace(),
        "data-testid": "codex-load-full-trace-button",
      }, selectedDetailLoading ? "加载中" : taskTraceSummary(selectedTask) ? "刷新 Summary" : "加载 Summary") : null,
      h("button", { type: "button", className: "codex-session-title-toggle", onClick: () => setQueueSidebarOpen((value: boolean) => !value), "data-testid": "code-queue-sidebar-toggle" }, queueSidebarOpen ? "收起队列" : "展开队列"),
      h("label", { className: "inline-check" }, h("input", { type: "checkbox", checked: autoScroll, onChange: (event: any) => setAutoScroll(Boolean(event.target.checked)) }), "自动滚动"),
      h("button", { type: "button", className: "ghost-btn", disabled: !selectedCanInterrupt || busy, onClick: () => void interrupt(), "data-testid": "codex-interrupt-button" }, "打断"),
      h("button", { type: "button", className: "ghost-btn", disabled: !selectedCanRetry || busy, onClick: () => void retry() }, "重试"),
      selectedTask ? h(RawButton, { title: "Codex Task", data: selectedTask, onOpen: onRaw, testId: "raw-codex-task" }) : null,
    ),
    className: "codex-output-panel",
  },
    h("div", { className: `codex-session-shell ${queueSidebarOpen ? "" : "queue-collapsed"}` },
      queueSidebarOpen ? h("aside", { className: "codex-session-sidebar", "data-testid": "codex-session-sidebar" },
        h("div", { className: "codex-session-sidebar-head" },
          h("div", null,
            h("span", null, isAllQueues(selectedQueueId) ? "All queues" : "Queue lane"),
            h("strong", null, `${selectedQueueName} · ${tasks.length}/${Number.isFinite(totalTaskCount) ? totalTaskCount : tasks.length} sessions · 未读 ${overallUnreadTerminalCount}`),
          ),
          h("button", { type: "button", className: "ghost-btn", onClick: () => setQueueSidebarOpen(false) }, "收起"),
        ),
        queueSelector("code-queue-filter-sidebar", true),
        taskSearchControl,
        h("div", { className: "codex-task-list codex-task-list-session", onScroll: handleTaskListScroll, "data-testid": "codex-task-list-scroll" }, taskListContent),
      ) : null,
      h("div", { className: "codex-session-main" },
        h("div", { className: "codex-output-stack" },
          h(ProgressiveTrace, { task: selectedTask, loading: selectedDetailLoading, traceStepsLoading, traceStepLoading, onLoadPromptPart: ensurePromptPart, onLoadSteps: ensureTraceSteps, onLoadStep: ensureTraceStep }),
          h(RawTranscript, { task: selectedTask }),
        ),
      ),
    ),
  );

  if (!service) return h(EmptyState, { title: "Code Queue 未登记", text: "请在 config.json 的 microservices 中登记用户服务 id=code-queue" });

  const loadTotalMs = Number(loadStats?.totalMs);
  const loadQueueMs = Number(loadStats?.queueMs);
  const loadDetailMs = Number(loadStats?.detailMs);
  const loadTranscriptRows = Number(loadStats?.transcriptRows);
  const loadState = loadStats?.phase === "complete" ? "complete" : String(loadStats?.phase || "idle");
  const mergeTargetQueueRow = selectedQueueRow(queueRows, mergeTargetQueueId) || { id: mergeTargetQueueId, name: mergeTargetQueueId };
  const mergeDialog = mergeDialogOpen ? h(UniDeskDialog, {
    title: "合并 queue",
    titleId: "codex-merge-dialog-title",
    className: "codex-merge-dialog",
    backdropClassName: "codex-merge-dialog-backdrop",
    bodyClassName: "codex-merge-dialog-body",
    actionsClassName: "codex-merge-dialog-actions",
    testId: "codex-merge-queue-dialog",
    closeTestId: "codex-merge-queue-close",
    disableClose: busy,
    onClose: () => setMergeDialogOpen(false),
    actions: [
      h("button", { key: "cancel", type: "button", className: "ghost-btn", onClick: () => setMergeDialogOpen(false), disabled: busy, "data-testid": "codex-merge-queue-cancel" }, "取消"),
      h("button", { key: "confirm", type: "button", className: "primary-btn", onClick: () => void mergeQueue(), disabled: legacyCodeQueueFrozen || busy || submitting || !mergeSourceQueueId, "data-testid": "codex-merge-queue-confirm" }, legacyCodeQueueFrozen ? "旧入口已冻结" : busy ? "合并中..." : "确认合并"),
    ],
  },
    h("p", { className: "codex-merge-dialog-target" }, "目标 queue：", h("code", null, queueOptionLabel(mergeTargetQueueRow))),
    h("label", null, "源 queue",
      h("select", { value: mergeSourceQueueId, disabled: legacyCodeQueueFrozen || busy || submitting, onChange: (event: any) => setMergeSourceQueueId(String(event.target.value || "")), "data-testid": "codex-merge-source-queue-select" },
        h("option", { value: "" }, "选择要合并进来的源 queue"),
        mergeSourceQueueRows.map((row: any) => h("option", { key: String(row?.id || ""), value: String(row?.id || "") }, queueOptionLabel(row))),
      ),
    ),
    h("p", { className: "codex-merge-dialog-note" }, "会把源 queue 的任务归属合并到目标 queue，并自动删除源 queue；目标 queue 会按原 queueEnteredAt/createdAt 时间顺序运行。"),
  ) : null;

  return h("div", {
    className: `code-queue-page ${standalone ? "codex-standalone-page" : ""}`,
    "data-testid": "code-queue-page",
    "data-load-state": loadState,
    "data-load-total-ms": Number.isFinite(loadTotalMs) ? String(Math.round(loadTotalMs * 10) / 10) : "",
    "data-load-queue-ms": Number.isFinite(loadQueueMs) ? String(Math.round(loadQueueMs * 10) / 10) : "",
    "data-load-detail-ms": Number.isFinite(loadDetailMs) ? String(Math.round(loadDetailMs * 10) / 10) : "",
    "data-load-transcript-rows": Number.isFinite(loadTranscriptRows) ? String(loadTranscriptRows) : "",
    "data-load-task-id": String(loadStats?.taskId || selectedId || ""),
    "data-load-partial": loadStats?.partial ? "true" : "false",
  },
    h(UniDeskErrorBanner, { error, wide: true }),
    mergeDialog,
    h("div", { className: "codex-session-stage codex-session-stage-top" },
      h(CodeQueueLivenessPanel, { diagnostics: executionDiagnostics, queue, onRaw }),
      sessionPanel,
    ),
    h("div", { className: "code-queue-layout" },
      h("div", { className: "codex-left-rail" },
        h(Panel, { title: "旧 Code Queue 入口", eyebrow: "Frozen / Archive", className: "codex-compose-panel", loading: submitting },
          h("form", { className: `codex-task-form ${submitting ? "is-submitting" : ""} ${legacyCodeQueueFrozen ? "is-frozen" : ""}`, onSubmit: enqueue, "data-testid": "code-queue-task-form", "aria-busy": submitting ? "true" : "false", "aria-disabled": legacyCodeQueueFrozen ? "true" : "false" },
            h("div", { className: "codex-freeze-notice", "data-testid": "code-queue-freeze-notice" },
              h("strong", null, "旧 Code Queue 新任务入口已冻结"),
              h("p", null, "新任务请使用 AgentRun Queue；本页保留历史任务、Trace 和排障查看。"),
              h("div", { className: "codex-freeze-command-grid" },
                h("code", null, "bun scripts/cli.ts agentrun v01 queue commander --reader-id cli"),
                h("code", null, "bun scripts/cli.ts agentrun v01 queue submit --json-stdin <<'JSON'"),
                h("code", null, "bun scripts/cli.ts agentrun v01 sessions trace <sessionId> --after-seq 0 --limit 100"),
              ),
            ),
            h("label", null, "Prompt / 多任务用单独一行 --- 分隔",
              h("textarea", { value: prompt, rows: 8, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setPrompt(event.target.value), placeholder: "旧入口已冻结；新任务使用 AgentRun Queue。" }),
            ),
            h("label", { className: "codex-reference-field" }, "引用任务 ID（可选）",
              h("input", { value: referenceTaskId, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setReferenceTaskId(event.target.value), placeholder: "codex_...；支持空格/逗号分隔多个 ID", "data-testid": "codex-reference-task-id" }),
              parseReferenceTaskIds(referenceTaskId).length > 0 ? h("code", null, `后端将解析并注入：${parseReferenceTaskIds(referenceTaskId).join(" / ")}`) : null,
            ),
            h("div", { className: "codex-form-grid" },
              h("label", { className: "codex-submit-queue-field" }, "Queue",
                h("div", { className: "codex-submit-queue-row" },
                  h("select", { className: "codex-submit-queue-select", value: queueId, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setQueueId(String(event.target.value || "default")), "data-testid": "code-queue-id-select" },
                    queueRows.map((row: any) => h("option", { key: String(row?.id || ""), value: String(row?.id || "") }, queueOptionLabel(row))),
                  ),
                  h("button", { type: "button", className: "ghost-btn codex-rename-queue-btn", onClick: () => void renameQueue(), disabled: legacyCodeQueueFrozen || busy || submitting || !queueId, title: legacyCodeQueueFrozen ? "旧 Code Queue queue 管理已冻结" : "修改当前 queue 的显示名称，ID 不变", "data-testid": "codex-rename-queue-button" }, "改名"),
                  h("button", { type: "button", className: "ghost-btn codex-merge-queue-btn", onClick: () => openMergeQueueDialog(), disabled: legacyCodeQueueFrozen || busy || submitting || mergeSourceQueueRows.length === 0, title: legacyCodeQueueFrozen ? "旧 Code Queue queue 管理已冻结" : "打开独立窗口选择源 queue 并合并到当前 queue；合并后自动删除源 queue", "data-testid": "codex-merge-queue-button" }, "合并 queue"),
                  h("button", { type: "button", className: "ghost-btn codex-create-queue-btn", onClick: () => void createQueue(), disabled: legacyCodeQueueFrozen || busy || submitting, "data-testid": "codex-create-queue-button" }, "创建 queue"),
                ),
              ),
              h("label", null, "模型",
                h("select", { value: model, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setModel(event.target.value), "data-testid": "codex-model-select" },
                  codexModels.map((name) => h("option", { key: name, value: name }, name)),
                ),
              ),
              h("label", null, "执行 Provider",
                h("select", { value: providerId, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => changeSubmitProvider(String(event.target.value || "D601")), "data-testid": "codex-provider-select" },
                  providerOptions.map((provider: any) => h("option", { key: provider.id, value: provider.id }, `${provider.label || provider.id} · ${provider.defaultWorkdir || providerDefaultWorkdir(queue, provider.id)}${provider.supportsWindowsNativeCodex ? " · Windows native" : ""}`)),
                ),
              ),
              h("label", null, "执行模式",
                h("select", { value: executionMode, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => changeSubmitExecutionMode(String(event.target.value || "default")), "data-testid": "codex-execution-mode-select" },
                  executionModeRows.map((mode: any) => h("option", { key: mode.id, value: mode.id }, `${mode.label || mode.id}${mode.id === "windows-native" ? " · 宿主 Codex" : ""}`)),
                ),
              ),
              h("label", { className: "codex-workdir-field" }, "工作目录",
                h("div", { className: "codex-workdir-row" },
                  h("input", { value: cwd, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setCwd(event.target.value), placeholder: currentProviderDefaultWorkdir || queue?.defaultWorkdir || "/workspace", "data-testid": "codex-cwd-input" }),
                  h("select", { value: normalizedWorkdirPath(cwd), disabled: legacyCodeQueueFrozen || submitting || workdirBusy, onChange: (event: any) => setCwd(String(event.target.value || "")), "data-testid": "codex-cwd-select" },
                    currentWorkdirOptions.map((item: any) => h("option", { key: `${item.providerId}:${item.executionMode}:${item.path}`, value: item.path }, `${item.path}${item.source === "default" ? " · 默认" : ""}`)),
                  ),
                  h("button", { type: "button", className: "ghost-btn codex-workdir-create-btn", disabled: legacyCodeQueueFrozen || submitting || busy || workdirBusy, onClick: () => void createWorkdirPreset(), "data-testid": "codex-cwd-create-button" }, workdirBusy ? "处理中" : "新建"),
                  h("button", { type: "button", className: "ghost-btn codex-workdir-delete-btn", disabled: legacyCodeQueueFrozen || submitting || busy || workdirBusy || !currentWorkdirSaved, onClick: () => void deleteWorkdirPreset(), title: legacyCodeQueueFrozen ? "旧 Code Queue 工作目录管理已冻结" : currentWorkdirSaved ? "从工作目录下拉菜单删除这个选项，不删除磁盘目录" : "当前工作目录尚未保存到下拉菜单", "data-testid": "codex-cwd-delete-button" }, "删除"),
                ),
              ),
              h("label", null, "最大尝试", h("input", { type: "number", min: 1, max: 99, value: maxAttempts, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setMaxAttempts(Number(event.target.value)), "data-testid": "codex-max-attempts-input" })),
              h("label", null, "入队份数", h("input", { type: "number", min: 1, max: 50, value: repeatCount, disabled: legacyCodeQueueFrozen || submitting, onChange: (event: any) => setRepeatCount(Number(event.target.value)), "data-testid": "codex-repeat-count-input" })),
            ),
            enqueueCount > 1 ? h("label", { className: `codex-batch-confirm ${batchConfirmed ? "confirmed" : ""}`, "data-testid": "codex-batch-confirm-row" },
              h("input", {
                type: "checkbox",
                checked: batchConfirmed,
                disabled: legacyCodeQueueFrozen || submitting,
                onChange: (event: any) => setBatchConfirmed(Boolean(event.target.checked)),
                "data-testid": "codex-batch-confirm-checkbox",
              }),
              h("span", null, `确认批量入队 ${enqueueCount} 个任务（prompt 分段 ${promptParts.length} × 入队份数 ${repeatCountValue(repeatCount)}）`),
            ) : null,
            legacyCodeQueueFrozen || submitting ? h("div", { className: "codex-submit-wait", "data-testid": "codex-submit-wait" }, legacyCodeQueueFrozen ? "旧入口冻结：提交、重试、steer、queue 管理不会再写入旧 Code Queue。" : "正在提交到后端，已锁定输入以防重复提交...") : null,
            h("div", { className: "codex-form-actions" },
              h("button", {
                type: "button",
                className: "ghost-btn",
                disabled: busy || submitting || (prompt.length === 0 && referenceTaskId.length === 0),
                onClick: () => {
                  setPrompt("");
                  setReferenceTaskId("");
                  setBatchConfirmed(false);
                  const msg = "已清空任务输入栏";
                  setNotice(msg);
                  addNotification("success", msg);
                },
                "data-testid": "codex-clear-input-button",
              }, "清空输入"),
              h("button", { type: "submit", className: "primary-btn", disabled: submitDisabled, "data-testid": "codex-enqueue-button" }, legacyCodeQueueFrozen ? "已冻结，使用 AgentRun Queue" : submitting ? "提交中，请等待..." : batchNeedsConfirmation ? `请确认批量入队 ${enqueueCount} 个任务` : enqueueItems.length > 1 ? `批量入队 ${enqueueItems.length} 个任务` : "入队并运行"),
            ),
          ),
        ),
      ),
      h("div", { className: "codex-main-stage" },
        h("div", { className: "codex-detail-grid" },
          h(Panel, { title: "运行控制", eyebrow: legacyCodeQueueFrozen ? "Legacy write controls frozen" : selectedCanEditPrompt ? "Queued prompt editable" : selectedCanSteer ? "Active turn steer" : "Steer when running", loading: busy },
            h("div", { className: "codex-run-control-stack" },
              h(TaskQueueMoveControl, { task: selectedTask, queueRows, busy, frozen: legacyCodeQueueFrozen, onMove: moveSelectedTaskQueue }),
              selectedTask?.id ? h("form", { className: "codex-steer-form codex-edit-prompt-form", onSubmit: editSelectedQueuedPrompt, "data-testid": "codex-edit-prompt-form" },
                h("label", null, "编辑 queued 用户 prompt",
                  h("textarea", {
                    value: editPrompt,
                    rows: 5,
                    onChange: (event: any) => setEditPrompt(event.target.value),
                    placeholder: "仅 QUEUED 且尚未开始运行的任务可在这里修改原始用户 prompt。",
                    disabled: !selectedCanEditPrompt || busy,
                    "data-testid": "codex-edit-prompt-textarea",
                  }),
                ),
                h("label", { className: "codex-reference-field" }, "引用任务 ID（可选，留空会清除引用）",
                  h("input", {
                    value: editReferenceTaskId,
                    disabled: !selectedCanEditPrompt || busy,
                    onChange: (event: any) => setEditReferenceTaskId(event.target.value),
                    placeholder: "codex_...；支持空格/逗号分隔多个 ID",
                    "data-testid": "codex-edit-reference-task-id",
                  }),
                  parseReferenceTaskIds(editReferenceTaskId).length > 0 ? h("code", null, `将保留/注入：${parseReferenceTaskIds(editReferenceTaskId).join(" / ")}`) : null,
                ),
                h("div", { className: "codex-form-actions" },
                  h("button", {
                    type: "button",
                    className: "ghost-btn",
                    disabled: !selectedTask?.id || busy,
                    onClick: () => {
                      setEditPrompt(selectedTask ? taskBasePromptText(selectedTask) : "");
                      setEditReferenceTaskId(Array.isArray(selectedTask?.referenceTaskIds) ? selectedTask.referenceTaskIds.join(" ") : "");
                    },
                    "data-testid": "codex-edit-prompt-reset",
                  }, "恢复当前值"),
                  h("button", {
                    type: "submit",
                    className: "primary-btn",
                    disabled: !selectedCanEditPrompt || busy || editPrompt.trim().length === 0,
                    title: selectedCanEditPrompt ? "保存后会重写尚未运行任务的用户 prompt" : "只有 QUEUED 且尚未开始的任务可编辑 prompt",
                    "data-testid": "codex-edit-prompt-submit",
                  }, "保存 queued prompt"),
                ),
              ) : null,
              h("form", { className: "codex-steer-form", onSubmit: steer },
                h("label", null, "追加 prompt",
                  h("textarea", { value: steerPrompt, rows: 4, onChange: (event: any) => setSteerPrompt(event.target.value), placeholder: "给正在运行的 Codex session 推入新的指令或纠偏。", disabled: !selectedCanSteer }),
                ),
                h("button", { type: "submit", className: "primary-btn", disabled: !selectedCanSteer || busy || steerPrompt.trim().length === 0, "data-testid": "codex-steer-button" }, "推入运行中 session"),
              ),
            ),
          ),
          h(Panel, { title: "完成判定", eyebrow: selectedTask?.lastJudge ? selectedTask.lastJudge.source : "judge", loading: selectedDetailLoading },
            selectedTask?.lastJudge ? h("div", { className: "codex-judge-card", "data-testid": "codex-task-judge-card" },
              h(StatusBadge, { status: selectedTask.lastJudge.decision }, selectedTask.lastJudge.decision),
              h("strong", null, `${Math.round(Number(selectedTask.lastJudge.confidence || 0) * 100)}% confidence`),
              h("p", { "data-testid": "codex-task-judge-reason" }, shortText(selectedTask.lastJudge.reason || "--", 180)),
              h(JudgeFailureDetails, { judge: selectedTask.lastJudge, testId: "codex-task-judge-failure-details" }),
              selectedTask.lastJudge.continuePrompt ? h("code", { "data-testid": "codex-task-judge-continue-prompt" }, shortText(selectedTask.lastJudge.continuePrompt, 160)) : null,
            ) : h(EmptyState, { title: "尚未判定", text: "Codex turn 结束后会由 MiniMax M2.7 或 fallback judge 判定 complete/retry/fail；retry 会在已有 thread 追加继续执行 prompt。" }),
          ),
        ),
        h(CodexStatsPanel, { stats: statistics, queueName: selectedQueueName, onRaw }),
        h(Panel, { title: "Attempts", eyebrow: "terminal vs interruption", loading: selectedDetailLoading }, h(AttemptTable, { task: selectedTask })),
      ),
    ),
  );
}
