refactor(chat/shipping): 重构发货通知模块为统一UI State驱动模式

- 重构发货通知的状态与动作获取逻辑:移除从聊天文本解析HXOPS_SHIPPING_ACTIONS注释的旧逻辑,改为统一从后端shipping_ui_state获取任务状态、动作按钮与工作流步骤
- 新增SSE实时推送shipping_ui_state事件,支持前端即时更新聊天气泡与工作台的状态与按钮
- 优化路由与登录流程:调整根路径重定向逻辑,退出登录时跳转到登录页;移除chat路由不必要的props传参;将原路由守卫中的根路径判断迁移到路由配置中
- 完善库存RPA与本地导入流程:新增本地库存文件托管接口,优化RPA回调的文件落盘与任务关联逻辑
- 新增多组单元测试覆盖焦点切换、决策处理、SSE同步等核心场景
- 修复多语言显示逻辑,使用te方法判断翻译key是否存在,避免缺失翻译时的渲染异常
- 新增reparse_inventory菜单动作,支持静默重新解析库存且不追加额外聊天消息
- 重构工作流步骤渲染函数,优先使用后端返回的步骤数据, fallback到本地推导的旧逻辑
- 清理后端旧的chat-actions API接口,将相关逻辑迁移到统一的ui_state接口中
This commit is contained in:
hugo committed 2026-07-02 01:55:19 +08:00
commit 9c036c825b
39 files changed
+3114 -456

No files matched your search

@@ -1,9 +1,9 @@
"""
services/shipping_notice/chat_actions.py
用途:chat-actions 相关符号的向后兼容 re-export 入口。
用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)。
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py。
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py,不再暴露已删除的 /chat-actions 读模型。
"""
from app.services.shipping_notice.state_machine import (
@@ -16,10 +16,8 @@ from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint,
apply_task_transition,
build_action_buttons,
build_chat_actions_payload,
build_checkpoint_catalog,
checkpoint_for_task,
format_actions_directive,
human_options_for_checkpoint,
human_options_for_task,
human_options_for_task_or_checkpoint,
@@ -43,10 +41,8 @@ __all__ = [
"action_buttons_for_checkpoint",
"apply_task_transition",
"build_action_buttons",
"build_chat_actions_payload",
"build_checkpoint_catalog",
"checkpoint_for_task",
"format_actions_directive",
"human_options_for_checkpoint",
"human_options_for_task",
"human_options_for_task_or_checkpoint",
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_file_store.py
from __future__ import annotations
import re
import shutil
import uuid
from pathlib import Path
from typing import Any
@@ -109,6 +110,57 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
return inv_file
def save_task_inventory_file_from_local_path(
task: ShippingTask,
source_path: str | Path,
*,
source_file_name: str | None = None,
) -> ShippingInventoryFile:
"""
将本地已有库存文件纳入统一库存快照模型,并为当前任务建立 active link。
【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 ShippingInventoryFile 记录时调用。
核心逻辑:复制本地文件到 inventory_file_no 对应标准目录,生成 schema preview,
再创建 task_only 的 ShippingInventoryFile 与 active ShippingTaskInventoryLink。
Args:
task: 当前发货任务,用于绑定 user/batch 与 active link。
source_path: 本地库存文件路径,必须存在。
source_file_name: 展示给用户/审计的原始文件名;为空时回退源文件名。
Returns:
ShippingInventoryFile: 已持久化的库存快照对象。
Raises:
FileNotFoundError: 源文件不存在时抛出。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
inventory_file_no = generate_inventory_file_no()
path = inventory_file_upload_path(inventory_file_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, path)
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(source_file_name or source.name or path.name).strip() or path.name
inv_file = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
batch_id=task.batch_id,
user_id=task.user_id,
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
storage_path=str(path),
schema_preview_json=preview,
share_mode="task_only",
line_count=0,
)
db.session.add(inv_file)
db.session.flush()
replace_task_inventory_link(task, inv_file, role="owner")
return inv_file
def replace_task_inventory_link(
task: ShippingTask,
inv_file: ShippingInventoryFile,
@@ -16,6 +16,8 @@ from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_INVENTORY_SOURCE_REVIEW, CP_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_file_store import save_task_inventory_file_from_local_path
from app.services.shipping_notice.inventory_upload import save_task_inventory_local_file
from app.services.shipping_notice.inventory_source_rules import (
mark_inventory_source_review,
resolve_inventory_source,
@@ -427,14 +429,20 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
# [STEP 2] 成功回调后读取实际库存文件并交给统一的 inventory_loaded_response。
# 这样回调路径与人工上传路径在后续字段对齐/自动串联上保持一致。
# [STEP 2] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。
# 这样 inventory_uploads 会保留任务级正式附件,回调路径也能与人工上传共享同一托管约定。
file_path = str(payload.get("file_path") or "").strip()
path = Path(file_path) if file_path else find_latest_inventory_file()
if not path or not path.is_file():
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
processed = inventory_processed_dir()
managed_path = save_task_inventory_local_file(task.task_no, path)
inv_file = save_task_inventory_file_from_local_path(
task,
managed_path,
source_file_name=path.name,
)
lines, column_meta = ingest_inventory_file(path, move_to=processed)
set_task_step_progress(
task,
@@ -443,7 +451,18 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
status="running",
message="RPA 库存文件已返回,正在读取库存快照",
progress_percent=85,
detail=f"正在读取 {path.name}",
detail=f"正在读取 {managed_path.name}",
)
log_task_event(
task,
"inventory_uploaded",
{
"source": "rpa_callback",
"upload_filename": managed_path.name,
"upload_path": str(managed_path),
"origin_file_path": str(path),
"inventory_file_no": inv_file.inventory_file_no,
},
)
return inventory_loaded_response(
task,
@@ -9,6 +9,7 @@ services/shipping_notice/inventory_upload.py
from __future__ import annotations
import re
import shutil
from pathlib import Path
from typing import Any
@@ -44,6 +45,33 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
return path
def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path:
"""
保存本地已存在的库存文件到任务标准库存目录。
【AI 触发时机】:当 RPA 或其他后台流程已经拿到本地 Excel,需要把它正式纳入系统托管目录时调用。
核心逻辑:校验 source_path 存在后,统一复制到 inventory_uploads/{task_no}/inventory.xlsx,
让 RPA 下载与人工上传共用同一套任务级库存附件路径。
Args:
task_no: 发货任务号,禁止为空。
source_path: 本地现有库存文件路径,必须指向真实文件。
Returns:
Path: 系统托管后的任务库存文件路径。
Raises:
FileNotFoundError: 源文件不存在时抛出。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
path = task_inventory_upload_path(task_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, path)
return path
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
path = task_inventory_upload_path(task_no)
@@ -3,13 +3,14 @@ services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow;批量上传的预检临时文件也在这里统一落盘和清理。
"""
from __future__ import annotations
import base64
import re
import shutil
from email import policy
from email.parser import BytesParser
from pathlib import Path
@@ -30,6 +31,19 @@ def task_notice_upload_path(task_no: str, filename: str) -> Path:
return _storage_root() / "notice_uploads" / safe_task / safe_name
def temp_notice_upload_dir(request_id: str) -> Path:
"""
返回批量上传预检使用的请求级临时目录。
核心逻辑:将同一请求下的临时文件收敛到 `_tmp/{request_id}`,便于 finally 阶段整目录清理。
Args:
request_id: 当前请求唯一 ID。
Returns:
Path: 临时目录路径。
"""
safe_request = re.sub(r"[^\w\-]+", "_", str(request_id or "").strip()) or "unknown"
return _storage_root() / "notice_uploads" / "_tmp" / safe_request
def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
"""保存发货通知附件字节流并返回落盘路径。"""
path = task_notice_upload_path(task_no, filename)
@@ -38,6 +52,42 @@ def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
return path
def save_temp_notice_upload(request_id: str, index: int, filename: str, data: bytes) -> Path:
"""
保存批量上传预检阶段的临时附件。
核心逻辑:以请求 ID 作为一级目录、文件序号作为二级目录,避免同请求内同名文件互相覆盖。
Args:
request_id: 当前请求唯一 ID。
index: 当前文件在请求内的顺序号。
filename: 原始文件名。
data: 文件字节流。
Returns:
Path: 临时落盘路径。
"""
name = str(filename or "").strip() or "notice"
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
safe_index = max(int(index or 0), 1)
path = temp_notice_upload_dir(request_id) / str(safe_index) / safe_name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def cleanup_temp_notice_uploads(request_id: str) -> None:
"""
清理指定请求的临时上传目录。
【AI 触发时机】:仅在批量上传预检完成后调用;正式任务附件目录禁止使用本函数清理。
Args:
request_id: 当前请求唯一 ID。
"""
path = temp_notice_upload_dir(request_id)
if path.exists():
shutil.rmtree(path, ignore_errors=True)
parent = path.parent
if parent.exists() and not any(parent.iterdir()):
parent.rmdir()
def _decode_text(data: bytes) -> str:
if not data:
return ""
@@ -3,7 +3,7 @@ services/shipping_notice/state_machine.py
用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。
依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts。
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;chat_actions 与前端 chat-actions API 读本模块生成按钮与 ui_state;新增人工节点时仅改本文件与测试。
逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;ui_state.py 与历史兼容模块都从本文件读取按钮/状态;新增人工节点时仅改本文件与测试。
扩展说明(开发者):
- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt`
@@ -13,7 +13,6 @@ services/shipping_notice/state_machine.py
from __future__ import annotations
import json
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
@@ -223,19 +222,10 @@ def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
"""checkpoint → action_buttons 的便捷封装(tool_response 与 Dify fallback 用)。"""
"""checkpoint → action_buttons 的便捷封装(状态机 UI payload 用)。"""
return build_action_buttons(human_options_for_checkpoint(checkpoint))
def format_actions_directive(option_ids: list[str] | None) -> str:
"""将 action_buttons 序列化为 HTML 注释指令,嵌入 Agent 回复供前端解析。"""
buttons = build_action_buttons(option_ids)
if not buttons:
return ""
body = json.dumps(buttons, ensure_ascii=False)
return f"<!-- HXOPS_SHIPPING_ACTIONS: {body} -->"
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
"""无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。"""
options = human_options_for_checkpoint(checkpoint)
@@ -271,7 +261,7 @@ def human_options_for_task_or_checkpoint(
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
"""
将 ShippingTask DB 字段映射为 checkpoint + human_options(/chat-actions 核心)。
将 ShippingTask DB 字段映射为 checkpoint + human_options,供统一 UI State 读模型消费。
核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。
"""
@@ -399,29 +389,6 @@ def human_options_for_task(task: ShippingTask) -> list[str] | None:
return resolve_task_ui_state(task).human_options
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
"""
组装 /chat-actions API 响应体,供前端渲染步骤条与动作按钮。
Returns:
dict: 含 task_no、checkpoint、process_status、action_buttons 等字段。
"""
ui = resolve_task_ui_state(task)
action_buttons = (
inventory_source_action_buttons(task)
if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW
else ui.action_buttons
)
return {
"task_no": task.task_no,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": action_buttons,
}
def build_checkpoint_catalog() -> dict[str, Any]:
"""导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。"""
checkpoints = []
@@ -0,0 +1,250 @@
"""
services/shipping_notice/ui_state.py
用途:发货通知任务/批次 UI 状态读模型,作为 Chat 按钮、步骤条与工作台的统一状态来源。
依赖:models.ShippingTask/ShippingBatch、state_machine、query_service。
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/action_buttons,再补充七步流程与用户可读摘要。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_COMPLETED,
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_MAP_INFER,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.query_service import (
compute_batch_process_summary,
list_sorted_batch_tasks,
serialize_batch_summary,
serialize_task_summary,
)
from app.services.shipping_notice.state_machine import (
inventory_source_action_buttons,
resolve_task_ui_state,
)
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
{"id": "shipping-step-4", "code": "align_confirm", "label": "确认字段对齐"},
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
)
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
"step1_notice_submit": 0,
"step2_parse_confirm": 1,
"step3_inventory_prepare": 2,
"step2_inventory_prepare": 2,
"step4_align_confirm": 3,
"step5_match_inventory": 4,
"step3_inventory_match": 4,
"step4_shortage_review": 4,
"step6_generate_file": 5,
"step5_export_excel": 5,
"step7_upload_freight": 6,
"step6_upload_freight": 6,
"step7_finish": 6,
}
_TERMINAL_PROCESS_STATUSES = {"uploaded", "closed"}
_BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_ALIGN_REVIEW,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_FAILED,
}
def _derive_current_step_index(task: ShippingTask) -> int:
"""
根据任务字段推导七步流程当前索引。
核心逻辑:优先使用 current_step 精准定位;缺失时按 process/review/pending 状态兜底,
保持与前端旧 stepper 的语义一致,后续前端可直接消费后端 step。
"""
current_step = str(task.current_step or "").strip()
if current_step in _CURRENT_STEP_INDEX_MAP:
return _CURRENT_STEP_INDEX_MAP[current_step]
process_status = str(task.process_status or "").strip()
review_status = str(task.review_status or "").strip()
pending_reason = str(task.pending_human_reason or "").strip()
match_status = str(task.match_status or "").strip()
has_export = bool(str(task.export_file_name or "").strip() or str(task.export_file_path or "").strip())
if process_status in _TERMINAL_PROCESS_STATUSES:
return 6
if process_status in {"waiting_upload", "upload_failed"} or has_export:
return 5
if process_status == "matched":
return 4
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
return 4
if review_status == RS_ALIGN_REVIEW or pending_reason == CP_ALIGN_REVIEW:
return 3
if process_status == "inventory_ready" or match_status:
return 4
if process_status == "waiting_inventory" or pending_reason in {
PH_MAP_INFER,
PH_RPA_PENDING,
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
}:
return 2
if process_status in {"parsed", "pending_review"} or review_status in {
RS_PARSE_REVIEW,
PH_RSV_REQ,
} or pending_reason in {"low_confidence", PH_RSV_REQ}:
return 1
return 0
def build_shipping_workflow_steps(task: ShippingTask, checkpoint: str | None) -> list[dict[str, str]]:
"""
构造七步流程状态。
Returns:
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
"""
current_index = _derive_current_step_index(task)
process_status = str(task.process_status or "").strip()
checkpoint_value = str(checkpoint or "").strip()
steps: list[dict[str, str]] = []
for index, step in enumerate(WORKFLOW_STEPS):
if process_status in _TERMINAL_PROCESS_STATUSES:
status = "completed"
elif index < current_index:
status = "completed"
elif index == current_index:
status = "current"
else:
status = "pending"
if index == current_index and checkpoint_value in _BLOCKED_CHECKPOINTS:
status = "blocked"
steps.append({**step, "status": status})
return steps
def _action_buttons_for_task(task: ShippingTask) -> list[dict[str, str]]:
"""从状态机解析当前任务可用动作按钮,库存源确认场景补充 source_code。"""
ui = resolve_task_ui_state(task)
if ui.checkpoint == CP_INVENTORY_SOURCE_REVIEW:
return inventory_source_action_buttons(task)
return ui.action_buttons
def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str, str | None]:
"""输出用户可读任务摘要,供 Chat 文案与工作台卡片复用。"""
title = user_facing_task_stage(task)
message_by_checkpoint: dict[str, str] = {
CP_PARSE_REVIEW: "解析结果需要人工确认后才能继续。",
CP_RSV_REQ: "发货通知缺少后续匹配必需字段,请补充或重新上传。",
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
CP_INVENTORY_SOURCE_REVIEW: "库存查询来源不明确,需要先确认。",
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
CP_EXPORT_READY: "发货文件已生成,可以下载或确认上传。",
CP_WAITING_UPLOAD: "系统正在等待货代上传结果。",
CP_UPLOAD_FAILED: "货代上传失败,需要重试或手工确认。",
CP_REJECTED: "任务已驳回,无需继续处理。",
CP_UPLOADED: "任务已完成上传。",
CP_COMPLETED: "任务已关闭。",
}
return {
"title": title,
"message": message_by_checkpoint.get(str(checkpoint or ""), title),
"error_message": task.error_message or task.upload_error_message,
}
def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
"""
构建单票任务 UI State。
核心逻辑:所有 UI 入口只消费这里输出的 checkpoint/action_buttons/step,避免 Chat、顶部步骤条、
右侧工作台分别推导状态导致不一致。
"""
ui = resolve_task_ui_state(task)
action_buttons = _action_buttons_for_task(task)
steps = build_shipping_workflow_steps(task, ui.checkpoint)
current_index = _derive_current_step_index(task)
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
return {
"task_no": task.task_no,
"batch_no": task.batch.batch_no if task.batch is not None else None,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"match_status": task.match_status,
"current_step": current_step,
"steps": steps,
"summary": _build_task_summary(task, ui.checkpoint),
"action_buttons": action_buttons,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
def build_batch_ui_state(batch: ShippingBatch) -> dict[str, Any]:
"""
构建批次级 UI State。
核心逻辑:批次摘要、焦点任务、任务卡片均包含同源 task ui_state,供右侧工作台统一消费。
"""
tasks = list_sorted_batch_tasks(batch)
focus_task_no = str(batch.current_focus_task_no or "").strip()
focus_task = next((task for task in tasks if task.task_no == focus_task_no), None)
if focus_task is None and tasks:
focus_task = tasks[0]
task_states = [
{
**serialize_task_summary(task),
"ui_state": build_task_ui_state(task),
}
for task in tasks
]
return {
**serialize_batch_summary(batch),
"process_summary": batch.process_summary_json or compute_batch_process_summary(tasks),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
"focus_task_ui_state": build_task_ui_state(focus_task) if focus_task else None,
"tasks": task_states,
}