Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(swarmflow): add HITL reply path and TUI workflow UX for stateful operators

chenchunzhouc6d6cf07069f
diff --git a/README.md b/README.md
index 4b628ddf4c..6dbe6bfaa5 100644
--- a/README.md
+++ b/README.md
@@ -51,7 +51,7 @@
| --- | --- |
| Multi-Agent Collaboration | Complex tasks are no longer a single Agent's battlefield: Leader automatically decomposes tasks, assembles teams, and multiple Agents specialize and negotiate dynamically |
| Distributed Agent Swarm | Break through single-machine compute limits: Leader/Teammate deploy across processes and machines, coordinating at scale |
-| Swarmflow | Orchestrate workflows with natural language: Leader automatically decomposes into multi-stage workflows, with Agents seamlessly handing off between stages |
+| Swarmflow | Orchestrate workflows with natural language: Leader automatically decomposes into multi-stage workflows, with Agents seamlessly handing off between stages. Human-in-the-loop support allows you to answer questions mid-workflow via `/swarmflow on` and the TUI P key interface |
| Skill Self-Evolution | Capabilities grow stronger with use, not rigid over time: automatically detects error signals and user dissatisfaction, then optimizes Skill definitions |
| Skill Hub Sharing | Capability assets are built once and reused everywhere: Skills can be searched, installed, combined, and remixed across developers |
| Auto Harness | Evaluation-driven, end-to-end automated Harness optimization: not training model weights, but letting the Harness learn and optimize automatically in practice |
@@ -179,7 +179,7 @@ For common usage instructions and feature documentation, see: [Documentation](do
| Feature | Status | ETA | Value |
| --- |-----| --- | --- |
-| Swarmflow Stateful Operators | In Development | 2026-07 | Workflow nodes support human intervention and state memory — Humans can participate as stateful operators, approving, correcting, or taking over subsequent steps based on intermediate results |
+| Swarmflow Stateful Operators | Shipped | 2026-07 | Workflow nodes support human intervention and state memory — Humans can participate as stateful operators, approving, correcting, or taking over subsequent steps based on intermediate results |
| Team Mode Same-Session Feishu Integration | In Development | 2026-07 | Feishu users join as Human Agents in the same session, collaborating with AI Agent teams — human-AI mixed squads for more precise decisions |
## FAQ
diff --git a/jiuwenswarm/agents/harness/team/handlers/workflow_monitor_handler.py b/jiuwenswarm/agents/harness/team/handlers/workflow_monitor_handler.py
index dfb3f84135..d2e8d83602 100644
--- a/jiuwenswarm/agents/harness/team/handlers/workflow_monitor_handler.py
+++ b/jiuwenswarm/agents/harness/team/handlers/workflow_monitor_handler.py
@@ -97,13 +97,15 @@ class WorkflowMonitorHandler(BaseMonitorHandler):
logger.info(
"[WF_DBG WorkflowMonitorHandler] received progress: "
"session_id=%s kind=%s run_id=%s workflow_name=%s "
- "phase=%s label=%s",
+ "phase=%s label=%s agent_id=%s outcome_len=%s",
self._session_id,
progress.kind,
progress.run_id,
progress.workflow_name,
progress.phase,
progress.label,
+ progress.agent_id,
+ len(progress.outcome) if isinstance(progress.outcome, str) else 0,
)
run_state = self._get_or_create_run(progress)
@@ -227,6 +229,10 @@ class WorkflowMonitorHandler(BaseMonitorHandler):
outcome=getattr(payload, "outcome", None),
text=getattr(payload, "text", None),
phases=getattr(payload, "phases", None),
+ correlation_id=getattr(payload, "correlation_id", None),
+ node_type=getattr(payload, "node_type", None),
+ agent_id=getattr(payload, "agent_id", None),
+ answer=getattr(payload, "answer", None),
)
except Exception:
logger.warning("[WorkflowMonitorHandler] Failed to extract progress from event")
diff --git a/jiuwenswarm/agents/harness/team/handlers/workflow_state.py b/jiuwenswarm/agents/harness/team/handlers/workflow_state.py
index aa9dc20c9a..8d750ab8b9 100644
--- a/jiuwenswarm/agents/harness/team/handlers/workflow_state.py
+++ b/jiuwenswarm/agents/harness/team/handlers/workflow_state.py
@@ -13,6 +13,13 @@ from pydantic import BaseModel
logger = logging.getLogger(__name__)
+# Fallback names when an event carries no ``phase`` / ``label`` — placeholder
+# values, not real author-written ones. Kind-aware so a label-less ``human()``
+# node surfaces as "unnamed human" instead of the misleading "agent".
+_UNNAMED_PHASE = "unnamed phase"
+_UNNAMED_HUMAN = "unnamed human"
+_UNNAMED_AGENT = "unnamed agent"
+
# ---------------------------------------------------------------------------
# Input model — mirrors WorkflowProgressTeamEvent fields
@@ -45,6 +52,14 @@ class WorkflowProgress(BaseModel):
outcome -> outcome
text -> text (free narration text; term phrase on
workflow_started/completed, e.g. "Workflow started")
+ correlation_id -> correlation_id (session turn id on AGENT_STARTED for
+ agent_session / human_session / human; NOT plain agent())
+ node_type -> node_type (AGENT_STARTED only:
+ agent/agent_session/human/human_session;
+ sole source of node kind — kind derives:
+ node_type in {human, human_session} -> human)
+ agent_id -> agent_id (AGENT_*: deterministic resume-stable node id)
+ answer -> answer (HUMAN_REPLIED: the person's raw reply text)
"""
@@ -59,6 +74,10 @@ class WorkflowProgress(BaseModel):
outcome: Optional[str] = None
text: Optional[str] = None
phases: Optional[list[PhasePlan]] = None
+ correlation_id: Optional[str] = None
+ node_type: Optional[str] = None
+ agent_id: Optional[str] = None
+ answer: Optional[str] = None
# ---------------------------------------------------------------------------
@@ -89,6 +108,10 @@ class WorkflowAgentActivity(BaseModel):
activity is written. Tool-call activity (type="tool_call" /
"tool_result") requires upstream structured data which is not yet
available. ``activity`` on ``WorkflowAgentState`` is always empty.
+
+ Human nodes never produce activity (their question/answer live on
+ ``human_prompt`` / ``human_reply``); only agent nodes' tool_call /
+ tool_result activity is recorded here.
"""
timestamp: str # required — every entry must be timestamped
@@ -105,7 +128,7 @@ class WorkflowAgentState(BaseModel):
id: str
name: str
- status: str = "running" # running / completed / failed
+ status: str = "running" # running / completed / failed / waiting_for_human
model: Optional[str] = None
prompt: Optional[str] = None
activity: list[WorkflowAgentActivity] = []
@@ -116,6 +139,11 @@ class WorkflowAgentState(BaseModel):
# reserved — pending upstream token accounting
token_count: Optional[int] = None
duration_ms: Optional[int] = None
+ kind: str = "agent" # "agent" | "human" — derived: node_type in {"human","human_session"} -> "human"
+ node_type: Optional[str] = None
+ correlation_id: Optional[str] = None
+ human_prompt: Optional[str] = None
+ human_reply: Optional[str] = None
def to_dict(self) -> dict[str, Any]:
"""Serialize to dict for event payload."""
@@ -180,6 +208,8 @@ class WorkflowRunState(BaseModel):
"agent_started": "_on_agent_started",
"agent_completed": "_on_agent_completed",
"agent_failed": "_on_agent_failed",
+ "human_prompt": "_on_human_prompt",
+ "human_replied": "_on_human_replied",
"workflow_completed": "_on_workflow_completed",
"workflow_failed": "_on_workflow_failed",
"log": "_on_log",
@@ -213,9 +243,39 @@ class WorkflowRunState(BaseModel):
@staticmethod
def _find_agent_in_phase(phase: WorkflowPhaseState, agent_label: str) -> Optional[WorkflowAgentState]:
- """Find an agent by its label within a phase."""
+ """Fallback locator: last same-label agent not yet terminal.
+
+ Main path resolves by ``agent_id`` / ``correlation_id`` (see
+ ``_resolve_agent``); this only handles legacy events without those ids.
+ Returning the *last* non-terminal match (rather than the first) lands a
+ late completion on the currently-running instance — e.g. the 2nd
+ iteration of a same-label loop, not the already-completed 1st.
+ """
+ last_running: Optional[WorkflowAgentState] = None
for agent in phase.agents:
- if agent.name == agent_label:
+ if agent.name == agent_label and agent.status not in (
+ "completed", "failed", "stopped", "waiting_for_human",
+ ):
+ last_running = agent
+ return last_running
+
+ @staticmethod
+ def _find_completed_agent_needing_outcome(
+ phase: WorkflowPhaseState, agent_label: str,
+ ) -> Optional[WorkflowAgentState]:
+ """Last same-label agent sealed ``completed`` without an outcome yet.
+
+ Phase switches and workflow teardown can mark still-running agents as
+ ``completed`` before ``agent_completed`` arrives. When ``agent_id`` is
+ missing or mismatched, fall back to the most recent outcome-less
+ completed instance with the same label.
+ """
+ for agent in reversed(phase.agents):
+ if (
+ agent.name == agent_label
+ and agent.status == "completed"
+ and not agent.outcome
+ ):
return agent
return None
@@ -253,9 +313,14 @@ class WorkflowRunState(BaseModel):
self.duration_ms = self._calc_duration_ms(self.started_at, self.completed_at)
def _finalize_running_agents(self, phase: WorkflowPhaseState, terminal_status: str) -> None:
- """Finalize any still-running agents in ``phase`` to ``terminal_status``."""
+ """Finalize any still-running agents in ``phase`` to ``terminal_status``.
+
+ A node left ``waiting_for_human`` at teardown (the run was torn down
+ while a human_session turn was pending) is also closed — otherwise the
+ frontend would spin forever on a reply that will never arrive.
+ """
for agent in phase.agents:
- if agent.status == "running":
+ if agent.status in ("running", "waiting_for_human"):
self._stamp_agent_terminal(agent, terminal_status)
def _finalize_running_phases(self, terminal_status: str) -> None:
@@ -325,6 +390,14 @@ class WorkflowRunState(BaseModel):
``running`` — is finalized to ``completed`` together with its
still-running agents.
+ Same-name phase cards are **reused** (one card per phase name, not per
+ iteration): the found card is flipped back to ``running`` regardless of
+ its prior status (planned/running/completed/failed) so the state may
+ jump forward and back across iterations. Agents and counters keep
+ accumulating on that same card — ``agent_count`` /
+ ``completed_agent_count`` are phase-level running totals, not
+ per-iteration.
+
Returns ``(target_phase, sealed_phase_or_None)``.
"""
target = self._find_phase_by_name(phase_name)
@@ -333,12 +406,21 @@ class WorkflowRunState(BaseModel):
target = WorkflowPhaseState(id=phase_id, name=phase_name, status="running")
self.phases.append(target)
logger.warning("[WF_DBG WorkflowRunState] phase %s not in plan, created on the fly", phase_name)
- elif not self._is_terminal_status(target.status):
+ else:
+ # Reuse the same-name card; flip it back to running so the state may
+ # jump (e.g. completed -> running on a later iteration). Agents and
+ # counters keep accumulating on this card.
target.status = "running"
sealed: Optional[WorkflowPhaseState] = None
prev = self._last_phase
- if prev is not None and prev.name != phase_name and prev.status == "running":
+ can_seal_prev = (
+ prev is not None
+ and prev is not target
+ and prev.name != phase_name
+ and prev.status == "running"
+ )
+ if can_seal_prev:
prev.status = "completed"
self._finalize_running_agents(prev, "completed")
sealed = prev
@@ -349,15 +431,37 @@ class WorkflowRunState(BaseModel):
return target, sealed
def _resolve_agent(
- self, phase_name: str, agent_label: str
+ self,
+ phase_name: str,
+ agent_label: str,
+ *,
+ agent_id: Optional[str] = None,
+ correlation_id: Optional[str] = None,
) -> tuple[Optional[WorkflowPhaseState], Optional[WorkflowAgentState]]:
- """Locate an agent by label, preferring its named phase.
-
- Falls back to scanning every phase when the named phase is missing or
- does not contain the agent — this tolerates phase-name drift between
- ``agent_started`` and ``agent_completed`` / ``agent_failed``. Logs a
- warning when nothing matches so the drop is visible, not silent.
+ """Locate an agent node by priority: agent_id -> correlation_id -> label fallback.
+
+ 1. ``agent_id`` — exact match across all phases (AGENT_COMPLETED /
+ AGENT_FAILED). The only sound way to disambiguate same-label nodes
+ in for-loops, multi-turn sessions, and ``parallel``.
+ 2. ``correlation_id`` — cross-phase match (HUMAN_PROMPT /
+ HUMAN_REPLIED carry no ``phase``, so this scans every phase).
+ 3. Fallback — label + last non-terminal instance within the named
+ phase, then every phase. Only for legacy events without ids.
+
+ Late ``agent_completed`` after a phase seal (node already ``completed``
+ with no outcome, and ``agent_id`` may not match) is handled by
+ ``_resolve_sealed_agent_for_outcome_backfill``, not here.
"""
+ if agent_id:
+ for phase in self.phases:
+ for agent in phase.agents:
+ if agent.id == agent_id:
+ return phase, agent
+ if correlation_id:
+ for phase in self.phases:
+ for agent in phase.agents:
+ if agent.correlation_id == correlation_id:
+ return phase, agent
phase = self._find_phase_by_name(phase_name)
if phase is not None:
agent = self._find_agent_in_phase(phase, agent_label)
@@ -367,10 +471,60 @@ class WorkflowRunState(BaseModel):
agent = self._find_agent_in_phase(candidate, agent_label)
if agent is not None:
return candidate, agent
- logger.warning(
- "[WF_DBG WorkflowRunState] agent %r in phase %r not found; known phases=%s",
- agent_label, phase_name, [p.name for p in self.phases],
+ return None, None
+
+ def _resolve_agent_for_finalize(
+ self,
+ progress: WorkflowProgress,
+ *,
+ status: str,
+ outcome: Optional[str],
+ ) -> tuple[Optional[WorkflowPhaseState], Optional[WorkflowAgentState]]:
+ """Resolve the node targeted by a terminal agent_completed / agent_failed.
+
+ Tries the normal id/label path first. When a late ``agent_completed``
+ carries an outcome but primary resolve misses (phase seal already
+ stamped the node completed, and agent_id may be absent/mismatched),
+ falls back to ``_resolve_sealed_agent_for_outcome_backfill``.
+ """
+ phase_name = progress.phase or _UNNAMED_PHASE
+ agent_label = progress.label or ""
+ phase, agent = self._resolve_agent(
+ phase_name, agent_label,
+ agent_id=progress.agent_id, correlation_id=progress.correlation_id,
)
+ need_outcome_backfill = (
+ (phase is None or agent is None)
+ and status == "completed"
+ and outcome is not None
+ )
+ if need_outcome_backfill:
+ phase, agent = self._resolve_sealed_agent_for_outcome_backfill(
+ phase_name, agent_label,
+ )
+ return phase, agent
+
+ def _resolve_sealed_agent_for_outcome_backfill(
+ self,
+ phase_name: str,
+ agent_label: str,
+ ) -> tuple[Optional[WorkflowPhaseState], Optional[WorkflowAgentState]]:
+ """Find a phase-sealed completed node still missing an outcome.
+
+ Used when primary ``_resolve_agent`` misses because phase switch /
+ teardown already stamped the node ``completed`` (so the non-terminal
+ label fallback skips it) and ``agent_id`` is absent or mismatched.
+ Prefers the named phase, then scans every phase.
+ """
+ phase = self._find_phase_by_name(phase_name)
+ if phase is not None:
+ agent = self._find_completed_agent_needing_outcome(phase, agent_label)
+ if agent is not None:
+ return phase, agent
+ for candidate in self.phases:
+ agent = self._find_completed_agent_needing_outcome(candidate, agent_label)
+ if agent is not None:
+ return candidate, agent
return None, None
def _stamp_agent_terminal(self, agent: WorkflowAgentState, terminal_status: str) -> None:
@@ -389,9 +543,44 @@ class WorkflowRunState(BaseModel):
error: Optional[str] = None,
) -> Optional[dict[str, Any]]:
"""Resolve agent from progress, mark terminal, bump counters, return phase delta."""
- phase, agent = self._resolve_agent(progress.phase or "?", progress.label or "")
+ phase, agent = self._resolve_agent_for_finalize(
+ progress, status=status, outcome=outcome,
+ )
if phase is None or agent is None:
+ logger.warning(
+ "[WF_DBG WorkflowRunState] finalize %s dropped: phase=%r label=%r agent_id=%r",
+ status, progress.phase, progress.label, progress.agent_id,
+ )
return None
+
+ already_terminal = agent.status in ("completed", "failed", "stopped")
+ if already_terminal:
+ if status == "completed" and agent.status == "completed":
+ updated = False
+ if outcome is not None and not agent.outcome:
+ agent.outcome = outcome
+ updated = True
+ if error is not None and not agent.error:
+ agent.error = error
+ updated = True
+ if updated:
+ # Phase seal / workflow teardown can mark agents completed
+ # without bumping counters; do it on the first real completion.
+ if phase.completed_agent_count < phase.agent_count:
+ phase.completed_agent_count += 1
+ self.completed_agent_count += 1
+ logger.info(
+ "[WF_DBG WorkflowRunState] backfilled outcome for agent %s, phase=%s",
+ agent.name, phase.name,
+ )
+ return self._build_phase_delta(phase)
+ return None
+ if status == "failed" and agent.status == "failed":
+ if error is not None and not agent.error:
+ agent.error = error
+ return self._build_phase_delta(phase)
+ return None
+
self._stamp_agent_terminal(agent, status)
if outcome is not None:
agent.outcome = outcome
@@ -400,8 +589,9 @@ class WorkflowRunState(BaseModel):
phase.completed_agent_count += 1
self.completed_agent_count += 1
logger.info(
- "[WF_DBG WorkflowRunState] agent %s -> %s, phase=%s",
+ "[WF_DBG WorkflowRunState] agent %s -> %s, phase=%s outcome_len=%s",
agent.name, status, phase.name,
+ len(outcome) if isinstance(outcome, str) else 0,
)
return self._build_phase_delta(phase)
@@ -445,7 +635,7 @@ class WorkflowRunState(BaseModel):
(see ``_switch_to_phase``), not by explicit PHASE events.
"""
logger.info("[WF_DBG WorkflowRunState] id=%s name=%s phase event: %s (ignored, state unchanged)",
- self.id, self.name, progress.phase or "?")
+ self.id, self.name, progress.phase or _UNNAMED_PHASE)
return None
def _on_agent_started(self, progress: WorkflowProgress) -> dict[str, Any]:
@@ -455,10 +645,22 @@ class WorkflowRunState(BaseModel):
this agent's phase differs from the last observed phase, the previous
running phase is finalized — see ``_switch_to_phase``.
"""
- target_phase, sealed_phase = self._switch_to_phase(progress.phase or "?")
-
- agent_label = progress.label or "agent"
- agent_id = self._generate_agent_id(agent_label)
+ target_phase, sealed_phase = self._switch_to_phase(progress.phase or _UNNAMED_PHASE)
+
+ # No user-facing label provided — fall back to a kind-aware placeholder.
+ if progress.label:
+ agent_label = progress.label
+ elif progress.node_type in ("human", "human_session"):
+ agent_label = _UNNAMED_HUMAN
+ else:
+ agent_label = _UNNAMED_AGENT
+ if not progress.agent_id:
+ logger.warning(
+ "[WF_DBG WorkflowRunState] agent_started missing agent_id for %r; "
+ "generated slug may not match later agent_completed",
+ agent_label,
+ )
+ agent_id = progress.agent_id or self._generate_agent_id(agent_label)
agent_state = WorkflowAgentState(
id=agent_id,
name=agent_label,
@@ -466,6 +668,9 @@ class WorkflowRunState(BaseModel):
prompt=progress.prompt,
model=progress.model,
started_at=self._now_iso(),
+ kind="human" if progress.node_type in ("human", "human_session") else "agent",
+ node_type=progress.node_type,
+ correlation_id=progress.correlation_id,
)
target_phase.agents.append(agent_state)
target_phase.agent_count += 1
@@ -490,9 +695,47 @@ class WorkflowRunState(BaseModel):
return self._finalize_agent(
progress,
status="failed",
- error=progress.outcome or progress.text or "agent failed",
+ error=progress.text or progress.outcome or "agent failed",
)
+ def _on_human_prompt(self, progress: WorkflowProgress) -> Optional[dict[str, Any]]:
+ """A human turn is now waiting for the person's reply.
+
+ Resolve the node by ``correlation_id`` (HUMAN_PROMPT carries no phase),
+ stamp it ``waiting_for_human`` and store the question. No activity is
+ appended — the question/answer live on the node itself.
+ """
+ phase, agent = self._resolve_agent(
+ progress.phase or _UNNAMED_PHASE, progress.label or "",
+ correlation_id=progress.correlation_id,
+ )
+ if phase is None or agent is None:
+ return None
+ agent.status = "waiting_for_human"
+ agent.correlation_id = progress.correlation_id
+ agent.human_prompt = progress.prompt
+ logger.info(
+ "[WF_DBG WorkflowRunState] agent %s -> waiting_for_human, phase=%s",
+ agent.name, phase.name,
+ )
+ return self._build_phase_delta(phase)
+
+ def _on_human_replied(self, progress: WorkflowProgress) -> Optional[dict[str, Any]]:
+ """The person replied to a pending human turn — clear waiting, store answer."""
+ phase, agent = self._resolve_agent(
+ progress.phase or _UNNAMED_PHASE, progress.label or "",
+ correlation_id=progress.correlation_id,
+ )
+ if phase is None or agent is None:
+ return None
+ agent.status = "running"
+ agent.human_reply = progress.answer
+ logger.info(
+ "[WF_DBG WorkflowRunState] agent %s -> replied, phase=%s",
+ agent.name, phase.name,
+ )
+ return self._build_phase_delta(phase)
+
def _on_workflow_completed(self, progress: WorkflowProgress) -> dict[str, Any]:
"""Mark workflow as completed (terminal state) and finalize all running phases/agents.
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
index 1869af12e6..9e043f0af2 100644
--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
@@ -68,7 +68,22 @@ import {
getCurrentCwd,
} from "./core/tui-trusted-dirs-store.js";
import { loadTuiConfig } from "./core/tui-config-store.js";
-import { applyWorkflowUpdate, normalizeWorkflowRun, type WorkflowRun } from "./core/workflows.js";
+import {
+ applyWorkflowUpdate,
+ collectWaitingForHuman,
+ countWaitingForHuman,
+ findWorkflowAgent,
+ isHumanPromptTruncated,
+ mergeHumanPromptText,
+ mergeWorkflowRun,
+ normalizeWorkflowRun,
+ isSessionNode,
+ phaseLocalTurnNumber,
+ sessionTurnLabelNumber,
+ shouldShowTurnInDetailOrReply,
+ type WorkflowRun,
+} from "./core/workflows.js";
+import type { PendingHumanPrompt } from "./core/event-handlers.js";
import { execFile, spawnSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { createConnection } from "node:net";
@@ -129,6 +144,7 @@ export interface AppSnapshot {
teamTaskEvents: TeamTaskEvent[];
teamMessageEvents: TeamMessageEvent[];
workflowRuns: WorkflowRun[];
+ pendingHumanPrompts: Map<string, PendingHumanPrompt>;
evolutionStatus: "idle" | "running";
contextCompression: ContextCompressionStats | null;
contextWindowLimit: number | null;
@@ -328,6 +344,7 @@ export class CliPiAppState {
private teamTaskEvents: TeamTaskEvent[] = [];
private teamMessageEvents: TeamMessageEvent[] = [];
private workflowRuns: WorkflowRun[] = [];
+ private pendingHumanPrompts: Map<string, PendingHumanPrompt> = new Map();
private evolutionStatus: "idle" | "running" = "idle";
private contextCompression: ContextCompressionStats | null = null;
private contextWindowLimit: number | null = null;
@@ -484,6 +501,9 @@ export class CliPiAppState {
applyWorkflowUpdate: (workflow) => {
this.applyWorkflowUpdate(workflow);
},
+ setPendingHumanPrompts: (prompts) => {
+ this.setPendingHumanPrompts(prompts);
+ },
setEvolutionStatus: (status) => {
this.evolutionStatus = status;
},
@@ -1046,6 +1066,7 @@ export class CliPiAppState {
})),
})),
})),
+ pendingHumanPrompts: new Map(this.pendingHumanPrompts),
evolutionStatus: this.evolutionStatus,
contextCompression: this.contextCompression ? { ...this.contextCompression } : null,
contextWindowLimit: this.contextWindowLimit,
@@ -1424,40 +1445,190 @@ export class CliPiAppState {
type?: string;
workflows?: unknown[];
session_id?: string;
+ total?: number;
+ truncated?: boolean;
}>(
"command.workflows",
{
action: "list",
session_id: sessionId,
},
- 10000,
+ // Align with get / get_human_prompt. 10s was too tight when the Gateway
+ // outbound writer is busy with workflow.updated / chat stream frames
+ // (list itself finishes in ms on AgentServer).
+ 30000,
);
this.applyWorkflowSnapshotPayload(payload);
};
+ readonly loadWorkflowDetail = async (
+ workflowId: string,
+ sessionId = this.sessionId,
+ ): Promise<void> => {
+ const payload = await this.request<{
+ type?: string;
+ workflow?: unknown;
+ truncated?: boolean;
+ }>(
+ "command.workflows",
+ {
+ action: "get",
+ workflow_id: workflowId,
+ session_id: sessionId,
+ },
+ 30000,
+ );
+ if (
+ payload.type === "workflow_run_detail" &&
+ payload.workflow &&
+ typeof payload.workflow === "object" &&
+ !Array.isArray(payload.workflow) &&
+ "id" in payload.workflow
+ ) {
+ const workflow = payload.workflow as WorkflowRun;
+ if (payload.truncated === true) {
+ workflow.truncated = true;
+ }
+ this.applyWorkflowUpdate(workflow);
+ }
+ };
+
+ readonly loadHumanPrompt = async (
+ workflowId: string,
+ agentId: string,
+ sessionId = this.sessionId,
+ ): Promise<string> => {
+ const payload = await this.request<{
+ type?: string;
+ human_prompt?: unknown;
+ agent_id?: unknown;
+ error?: unknown;
+ }>(
+ "command.workflows",
+ {
+ action: "get_human_prompt",
+ workflow_id: workflowId,
+ agent_id: agentId,
+ session_id: sessionId,
+ },
+ 30000,
+ );
+ if (payload.error) {
+ throw new Error(String(payload.error));
+ }
+ const prompt = typeof payload.human_prompt === "string" ? payload.human_prompt.trim() : "";
+ if (!prompt) return "";
+
+ const existing = this.workflowRuns.find((item) => item.id === workflowId);
+ if (!existing) return prompt;
+
+ const updatedPhases = (existing.phases ?? []).map((phase) => ({
+ ...phase,
+ agents: (phase.agents ?? []).map((agent) =>
+ agent.id === agentId
+ ? { ...agent, human_prompt: mergeHumanPromptText(agent.human_prompt, prompt) }
+ : agent,
+ ),
+ }));
+ this.applyWorkflowUpdate({ ...existing, phases: updatedPhases });
+ return prompt;
+ };
+
+ readonly ensureHumanPromptLoaded = async (
+ workflowId: string,
+ agentId: string,
+ ): Promise<void> => {
+ const lookup = findWorkflowAgent(this.workflowRuns, workflowId, agentId);
+ const current = lookup?.agent.human_prompt?.trim() ?? "";
+ if (current && !isHumanPromptTruncated(current)) return;
+ try {
+ await this.loadHumanPrompt(workflowId, agentId);
+ } catch {
+ // Best-effort — pending list still shows whatever partial text we have.
+ }
+ };
+
readonly applyWorkflowSnapshotPayload = (payload: {
type?: unknown;
workflows?: unknown;
+ total?: unknown;
+ truncated?: unknown;
[key: string]: unknown;
}): void => {
const workflows = Array.isArray(payload.workflows) ? payload.workflows : [];
if (payload.type !== "workflow_run_snapshot" && workflows.length === 0) {
return;
}
- this.setWorkflowRuns(
- workflows.filter((item): item is WorkflowRun =>
- Boolean(item && typeof item === "object" && !Array.isArray(item) && "id" in item),
- ),
+ const incoming = workflows.filter((item): item is WorkflowRun =>
+ Boolean(item && typeof item === "object" && !Array.isArray(item) && "id" in item),
);
+ const merged = incoming.map((workflow) => {
+ const existing = this.workflowRuns.find((item) => item.id === workflow.id);
+ return normalizeWorkflowRun(mergeWorkflowRun(existing, workflow));
+ });
+ const incomingIds = new Set(incoming.map((workflow) => workflow.id));
+ const preserved = this.workflowRuns.filter((workflow) => !incomingIds.has(workflow.id));
+ this.setWorkflowRuns([...merged, ...preserved]);
};
readonly setWorkflowRuns = (workflows: WorkflowRun[]): void => {
this.workflowRuns = workflows.map((workflow) => normalizeWorkflowRun(workflow));
+ this.recomputePendingHumanPrompts();
this.emitChange();
};
readonly applyWorkflowUpdate = (workflow: WorkflowRun): void => {
this.workflowRuns = applyWorkflowUpdate(this.workflowRuns, workflow);
+ this.recomputePendingHumanPrompts();
+ this.emitChange();
+ };
+
+ /** Recompute the pending-human-prompt map from the full workflow snapshot. */
+ private recomputePendingHumanPrompts(): void {
+ // Preserve reply summaries from the previous map for entries that are no
+ // longer waiting (replied -> running) so the list can dim them briefly.
+ const next = new Map<string, PendingHumanPrompt>();
+ for (const wf of this.workflowRuns) {
+ const waiting = collectWaitingForHuman(wf);
+ for (const { phase, agent } of waiting) {
+ const key = `${wf.id}:${agent.correlation_id ?? agent.id}`;
+ const turn = phaseLocalTurnNumber(agent, phase.agents ?? []) ?? 0;
+ const prev = this.pendingHumanPrompts.get(key);
+ next.set(key, {
+ workflow_run_id: wf.id,
+ workflow_id: wf.id,
+ workflow_name: wf.name,
+ agent_id: agent.id,
+ correlation_id: agent.correlation_id ?? "",
+ prompt: mergeHumanPromptText(prev?.prompt, agent.human_prompt ?? ""),
+ label: agent.name,
+ is_session: isSessionNode(agent),
+ turn,
+ // Carry forward a prior reply summary if this entry was replied then
+ // somehow re-listed (defensive — normally a replied turn won't wait again).
+ replied: prev?.replied,
+ answer: prev?.answer,
+ });
+ }
+ // Dim entries that were waiting and are now replied (status moved off
+ // waiting_for_human but human_reply was just set).
+ for (const phase of wf.phases ?? []) {
+ for (const agent of phase.agents ?? []) {
+ if (agent.status !== "waiting_for_human" && agent.human_reply) {
+ const key = `${wf.id}:${agent.correlation_id ?? agent.id}`;
+ const prev = this.pendingHumanPrompts.get(key);
+ if (prev && !prev.replied) {
+ next.set(key, { ...prev, replied: true, answer: agent.human_reply });
+ }
+ }
+ }
+ }
+ }
+ this.pendingHumanPrompts = next;
+ }
+
+ readonly setPendingHumanPrompts = (prompts: Map<string, PendingHumanPrompt> | null): void => {
+ this.pendingHumanPrompts = prompts ?? new Map();
this.emitChange();
};
@@ -1467,6 +1638,7 @@ export class CliPiAppState {
this.usageByModel.clear();
this.resetCurrentUsageTokens();
this.workflowRuns = [];
+ this.pendingHumanPrompts = new Map();
this.btwOverlay = null;
this.btwHistory = [];
this.btwOverlayIndex = -1;
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/swarmflow.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/swarmflow.ts
new file mode 100644
index 0000000000..9541054f1e
--- /dev/null
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/swarmflow.ts
@@ -0,0 +1,165 @@
+import { addInfo, addError } from "../helpers.js";
+import { isTeamMode, type ClientMode } from "../../modes.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export type SwarmflowToggleTarget = "on" | "off";
+
+export interface SwarmflowTogglePlan {
+ /** Whether to call config.set. */
+ writeConfig: boolean;
+ /** Whether to switch to team mode (only when enabling from non-team). */
+ switchToTeam: boolean;
+ /** User-facing info message. */
+ message: string;
+}
+
+function parseSwarmflowEnabled(payload: Record<string, unknown> | null): boolean | null {
+ if (!payload) return null;
+ const value = payload.enable_swarmflow;
+ if (value === "true" || value === true) return true;
+ if (value === "false" || value === false) return false;
+ return null;
+}
+
+/** Pure toggle planner — mirrors design state matrix for tests and command action. */
+export function planSwarmflowToggle(input: {
+ target: SwarmflowToggleTarget;
+ currentEnabled: boolean | null;
+ mode: ClientMode | string;
+}): SwarmflowTogglePlan {
+ const enabling = input.target === "on";
+ const wasTeamMode = isTeamMode(input.mode as ClientMode);
+ const currentEnabled = input.currentEnabled;
+
+ if (currentEnabled !== null && currentEnabled === enabling) {
+ if (enabling) {
+ if (wasTeamMode) {
+ return {
+ writeConfig: false,
+ switchToTeam: false,
+ message:
+ "SwarmFlow is already on in team mode. No changes were made.",
+ };
+ }
+ return {
+ writeConfig: false,
+ switchToTeam: true,
+ message:
+ "SwarmFlow is already on. Switched to team mode — the next workflow run uses the enabled setting.",
+ };
+ }
+ if (wasTeamMode) {
+ return {
+ writeConfig: false,
+ switchToTeam: false,
+ message:
+ "SwarmFlow is already off. Mode remains team. No changes were made.",
+ };
+ }
+ return {
+ writeConfig: false,
+ switchToTeam: false,
+ message:
+ "SwarmFlow is already off. Current mode unchanged. No changes were made.",
+ };
+ }
+
+ if (enabling) {
+ if (!wasTeamMode) {
+ return {
+ writeConfig: true,
+ switchToTeam: true,
+ message:
+ "swarmflow on. Switched to team mode — swarmflow activates on the next workflow run.",
+ };
+ }
+ return {
+ writeConfig: true,
+ switchToTeam: false,
+ message:
+ "swarmflow on. The handler activates on the next new session — use /new to apply immediately.",
+ };
+ }
+
+ if (wasTeamMode) {
+ return {
+ writeConfig: true,
+ switchToTeam: false,
+ message:
+ "swarmflow off. Takes effect on the next new session — use /new to apply immediately. Use /mode to switch away from team if needed.",
+ };
+ }
+ return {
+ writeConfig: true,
+ switchToTeam: false,
+ message:
+ "swarmflow off. Takes effect on the next team session — when you switch to team mode via /mode, swarmflow will not start.",
+ };
+}
+
+export function createSwarmflowCommand(): SlashCommand {
+ return {
+ name: "swarmflow",
+ description: "Toggle swarmflow human-in-the-loop mode (on/off) or show status",
+ usage: "/swarmflow [on|off]",
+ example: "/swarmflow on",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => ["on", "off"],
+ action: async (ctx, args) => {
+ const sub = args.trim().toLowerCase();
+
+ if (!sub) {
+ const modeLabel = ctx.mode ?? "unknown";
+ const payload = await ctx
+ .request<Record<string, unknown>>("config.get", {})
+ .catch(() => null);
+ const enabled = parseSwarmflowEnabled(payload) === true;
+ ctx.addItem(
+ addInfo(ctx.sessionId, `swarmflow: ${enabled ? "on" : "off"} · mode: ${modeLabel}`, "i"),
+ );
+ return;
+ }
+
+ if (sub !== "on" && sub !== "off") {
+ ctx.addItem(addError(ctx.sessionId, `Unknown argument: ${JSON.stringify(sub)}. Use /swarmflow on|off`));
+ return;
+ }
+
+ const target = sub as SwarmflowToggleTarget;
+ const payload = await ctx
+ .request<Record<string, unknown>>("config.get", {})
+ .catch(() => null);
+ const currentEnabled = parseSwarmflowEnabled(payload);
+ const plan = planSwarmflowToggle({
+ target,
+ currentEnabled,
+ mode: ctx.mode ?? "unknown",
+ });
+
+ if (plan.writeConfig) {
+ try {
+ await ctx.request("config.set", {
+ enable_swarmflow: target === "on" ? "true" : "false",
+ });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ ctx.addItem(addError(ctx.sessionId, `config.set enable_swarmflow failed: ${message}`));
+ return;
+ }
+ }
+
+ if (plan.switchToTeam && !isTeamMode(ctx.mode)) {
+ const nextMode = "team";
+ ctx.setMode(nextMode);
+ try {
+ await ctx.request("mode.set", { mode: nextMode });
+ } catch {
+ // mode.set is best-effort (same as /mode command pattern).
+ }
+ }
+
+ ctx.addItem(addInfo(ctx.sessionId, plan.message, "i"));
+ },
+ };
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
index 1830ad0ce4..de8fdc7dd3 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts
@@ -41,6 +41,7 @@ import { createStatusCommand } from "./builtins/status.js";
import { createStatusLineCommand } from "./builtins/statusline.js";
import { createSkillsCommand } from "./builtins/skills.js";
import { createSwarmFlowsCommand } from "./builtins/swarmflows.js";
+import { createSwarmflowCommand } from "./builtins/swarmflow.js";
import { createTeamSkillsCommand } from "./builtins/teamskills.js";
import { createAgentsCommand } from "./builtins/agents.js";
import { createAutoHarnessCommand } from "./builtins/auto-harness.js";
@@ -100,6 +101,7 @@ export function createBuiltinCommands(options: BuiltinCommandsOptions = {}): Sla
createStatusCommand(),
createStatusLineCommand(),
createSwarmFlowsCommand(),
+ createSwarmflowCommand(),
createTeamSkillsCommand(),
createAutoHarnessCommand(),
createThemeCommand(),
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts
index 03aaf4df38..302573f43f 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts
@@ -66,6 +66,32 @@ export interface UserAnswer {
custom_input?: string;
}
+/**
+ * A pending swarmflow human-session turn awaiting the person's reply.
+ * Not the leader HITL channel (PendingQuestion) — this is a workflow human
+ * node (human_session / human) paused on a real person's input.
+ *
+ * Composite map key is `${workflow_run_id}:${correlation_id}` so concurrent
+ * runs with the same correlation id don't clobber each other's pending entry.
+ */
+export interface PendingHumanPrompt {
+ workflow_run_id: string;
+ workflow_id: string;
+ workflow_name: string;
+ agent_id: string;
+ correlation_id: string;
+ prompt: string;
+ label: string;
+ /** True when reply/detail chrome should show a turn label (session nodes only). */
+ is_session: boolean;
+ /** Turn index parsed from correlation_id ({phase}:{label}:{turn}); 0 for one-shot. */
+ turn: number;
+ /** Set when the reply has been submitted (entry stays dimmed in the list). */
+ replied?: boolean;
+ /** Short reply summary shown after the entry is replied. */
+ answer?: string;
+}
+
// Harness extension ready info
export interface HarnessExtensionReady {
extensionName: string;
@@ -111,6 +137,7 @@ export interface AppEventDelegate {
appendTeamTaskEvent(event: TeamTaskEvent): void;
appendTeamMessageEvent(event: TeamMessageEvent): void;
applyWorkflowUpdate(workflow: WorkflowRun): void;
+ setPendingHumanPrompts(prompts: Map<string, PendingHumanPrompt> | null): void;
setEvolutionStatus(status: "idle" | "running"): void;
setContextCompression(stats: ContextCompressionStats | null): void;
setContextWindowLimit(n: number | null): void;
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts
index c91b408342..d7f7056527 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/keybindings/defaultBindings.ts
@@ -37,6 +37,7 @@ export const DEFAULT_BINDINGS: KeybindingBlock[] = [
context: "FileViewer",
bindings: {
escape: "fileViewer:exit",
+ left: "fileViewer:exit",
q: "fileViewer:exit",
up: "fileViewer:lineUp",
k: "fileViewer:lineUp",
@@ -72,7 +73,6 @@ export const DEFAULT_BINDINGS: KeybindingBlock[] = [
escape: "swarm:back",
left: "swarm:left",
right: "swarm:nextFocus",
- tab: "swarm:nextFocus",
l: "swarm:logs",
p: "swarm:viewPrompt",
o: "swarm:viewOutcome",
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/workflows.ts b/jiuwenswarm/channels/tui/frontend/src/core/workflows.ts
index c83231a630..7677d6e04c 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/workflows.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/workflows.ts
@@ -1,4 +1,11 @@
-export type WorkflowStatus = "planned" | "pending" | "running" | "completed" | "failed" | "stopped";
+export type WorkflowStatus =
+ | "planned"
+ | "pending"
+ | "running"
+ | "completed"
+ | "failed"
+ | "stopped"
+ | "waiting_for_human";
export interface WorkflowAgentActivity {
timestamp: string;
@@ -6,6 +13,8 @@ export interface WorkflowAgentActivity {
content: string;
}
+export type WorkflowNodeType = "agent" | "agent_session" | "human" | "human_session";
+
export interface WorkflowAgent {
id: string;
name: string;
@@ -19,6 +28,13 @@ export interface WorkflowAgent {
completed_at?: string;
token_count?: number | null;
duration_ms?: number | null;
+ kind?: "agent" | "human";
+ /** Exact SwarmFlow primitive type when emitted by the backend. */
+ node_type?: WorkflowNodeType;
+ /** ``{phase}:{label}:{turn}`` on ``agent_session`` / ``human_session`` (and ``human()`` one-shots); absent on plain ``agent()``. */
+ correlation_id?: string;
+ human_prompt?: string;
+ human_reply?: string;
}
export interface WorkflowPhase {
@@ -48,6 +64,10 @@ export interface WorkflowRun {
duration_ms?: number | null;
estimated_token_count?: number | null;
phases: WorkflowPhase[];
+ /** List summary only — full detail not yet fetched via ``action=get``. */
+ detail_pending?: boolean;
+ /** Wire payload was size-reduced (fields may be missing or clipped). */
+ truncated?: boolean;
}
export interface WorkflowAgentLookup {
@@ -56,6 +76,34 @@ export interface WorkflowAgentLookup {
agent: WorkflowAgent;
}
+/** Single-width “human waiting” marker (text symbol — not emoji 👤/🧑). */
+export const WAITING_FOR_HUMAN_ICON = "☺";
+
+/** Model/kind label for workflow agent rows — human nodes use ``human(model)`` form. */
+export function formatWorkflowAgentKindLabel(agent: {
+ kind?: WorkflowAgent["kind"];
+ model?: string;
+}): string {
+ if (agent.kind === "human") {
+ return agent.model ? `human(${agent.model})` : "human";
+ }
+ return agent.model ?? "";
+}
+
+/** Placeholder when a human turn completed via journal cache (no HUMAN_PROMPT / HUMAN_REPLIED). */
+export const HUMAN_TURN_CACHED_QUESTION = "(cached, prompt not replayed)";
+export const HUMAN_TURN_CACHED_ANSWER = "(cached, reply not replayed)";
+
+/** Human turn replayed from journal — Q/A fields stay empty; show placeholders instead of faking history. */
+export function isHumanTurnCached(agent: WorkflowAgent): boolean {
+ return (
+ agent.kind === "human" &&
+ agent.status === "completed" &&
+ !agent.human_prompt &&
+ !agent.human_reply
+ );
+}
+
export function workflowStatusIcon(status: WorkflowStatus): string {
switch (status) {
case "planned":
@@ -70,6 +118,8 @@ export function workflowStatusIcon(status: WorkflowStatus): string {
return "○";
case "stopped":
return "■";
+ case "waiting_for_human":
+ return WAITING_FOR_HUMAN_ICON;
}
}
@@ -228,9 +278,28 @@ function mergeWorkflowAgent(
...existing,
...incoming,
activity: incoming.activity ?? existing?.activity,
+ human_prompt: preferHumanPrompt(existing?.human_prompt, incoming.human_prompt),
};
}
+export function isHumanPromptTruncated(text?: string): boolean {
+ return Boolean(text?.includes("[truncated]"));
+}
+
+export function mergeHumanPromptText(existing?: string, incoming?: string): string {
+ return preferHumanPrompt(existing, incoming) ?? "";
+}
+
+function preferHumanPrompt(existing?: string, incoming?: string): string | undefined {
+ const left = existing?.trim();
+ const right = incoming?.trim();
+ if (!left) return right || undefined;
+ if (!right) return left;
+ if (isHumanPromptTruncated(right) && !isHumanPromptTruncated(left)) return left;
+ if (isHumanPromptTruncated(left) && !isHumanPromptTruncated(right)) return right;
+ return right.length > left.length ? right : left;
+}
+
function mergeWorkflowPhase(
existing: WorkflowPhase | undefined,
incoming: WorkflowPhase,
@@ -294,9 +363,31 @@ export function mergeWorkflowRun(
} else if (existing?.logs && !Object.prototype.hasOwnProperty.call(incoming, "logs")) {
merged.logs = existing.logs;
}
+
+ const detailLoaded = workflowHasAgentDetails(merged);
+ if (detailLoaded) {
+ delete merged.detail_pending;
+ if (!Object.prototype.hasOwnProperty.call(incoming, "truncated")) {
+ delete merged.truncated;
+ }
+ }
+ if (Object.prototype.hasOwnProperty.call(incoming, "truncated")) {
+ merged.truncated = incoming.truncated;
+ }
+ if (Object.prototype.hasOwnProperty.call(incoming, "detail_pending")) {
+ merged.detail_pending = incoming.detail_pending;
+ }
+
return merged;
}
+function workflowHasAgentDetails(workflow: WorkflowRun): boolean {
+ for (const phase of workflow.phases ?? []) {
+ if ((phase.agents?.length ?? 0) > 0) return true;
+ }
+ return false;
+}
+
export function applyWorkflowUpdate(
workflows: WorkflowRun[],
incoming: WorkflowRun,
@@ -309,3 +400,198 @@ export function applyWorkflowUpdate(
itemIndex === index ? normalizeWorkflowRun(mergeWorkflowRun(workflow, incoming)) : workflow,
);
}
+
+/** Whether the node was created by ``agent_session()`` or ``human_session()``. */
+export function isSessionNode(agent: Pick<WorkflowAgent, "node_type">): boolean {
+ return agent.node_type === "agent_session" || agent.node_type === "human_session";
+}
+
+/** Session History (``s``) is available only for explicit session primitives. */
+export function canOpenSessionHistory(agent: Pick<WorkflowAgent, "node_type">): boolean {
+ return isSessionNode(agent);
+}
+
+/** Group key for session nodes — label plus exact session primitive type. */
+export function sessionGroupKey(agent: Pick<WorkflowAgent, "name" | "node_type">): string | null {
+ if (!isSessionNode(agent)) return null;
+ return `${agent.name}\0${agent.node_type}`;
+}
+
+/**
+ * Reverse-parse the global turn index from a session correlation id
+ * ``{phase}:{label}:{turn}`` (emitted on ``AGENT_STARTED`` for ``agent_session`` /
+ * ``human_session``, and for ``human()`` one-shots). Returns null when the id is
+ * absent or malformed (plain ``agent()`` nodes have no correlation id).
+ */
+export function parseTurnFromCorrelationId(correlationId?: string): number | null {
+ if (!correlationId) return null;
+ const parts = correlationId.split(":");
+ const last = parts[parts.length - 1];
+ if (last === undefined) return null;
+ const turn = Number.parseInt(last, 10);
+ return Number.isFinite(turn) ? turn : null;
+}
+
+/** Same-name session turns within one phase, filtered by session primitive type. */
+export function sessionMembersInPhase(
+ phaseAgents: WorkflowAgent[],
+ sessionLabel: string,
+ nodeType?: WorkflowNodeType,
+): WorkflowAgent[] {
+ const members = phaseAgents.filter(
+ (agent) =>
+ agent.name === sessionLabel &&
+ isSessionNode(agent) &&
+ (nodeType === undefined || agent.node_type === nodeType),
+ );
+ return sortWorkflowAgentsByTurn(members);
+}
+
+/**
+ * Phase-local turn index (0-based) for session UI.
+ *
+ * ``correlation_id`` encodes a global session turn index (backend history length
+ * across the whole workflow run). The TUI groups by name inside one phase, so
+ * display uses the sorted index within that phase — not the global turn counter.
+ */
+export function phaseLocalTurnNumber(
+ agent: WorkflowAgent,
+ phaseAgents: WorkflowAgent[],
+): number | null {
+ if (!agent.correlation_id) return null;
+ const members = sessionMembersInPhase(phaseAgents, agent.name, agent.node_type);
+ const index = members.findIndex((member) => member.id === agent.id);
+ return index >= 0 ? index : null;
+}
+
+/**
+ * Whether the agents list should render a session parent row and turn child rows.
+ *
+ * Any ``agent_session`` / ``human_session`` node shows a tree (including a single
+ * ``turn 0`` child) so the list is visually distinct from plain ``agent()`` /
+ * ``human()``. Plain one-shots never form a tree.
+ */
+export function shouldShowSessionTree(
+ agent: WorkflowAgent,
+ phaseAgents: WorkflowAgent[],
+): boolean {
+ if (!isSessionNode(agent)) return false;
+ return sessionMembersInPhase(phaseAgents, agent.name, agent.node_type).length >= 1;
+}
+
+/**
+ * Whether detail titles, reply banners, and similar chrome should include turn.
+ *
+ * Plain ``agent()`` / ``human()`` never do. ``agent_session`` / ``human_session``
+ * do — even when the current phase has only one turn (SF-TURN-02: still ``turn 0``).
+ */
+export function shouldShowTurnInDetailOrReply(agent: WorkflowAgent): boolean {
+ return isSessionNode(agent);
+}
+
+/** Phase-local turn index for detail/reply/session history, or null for one-shots. */
+export function sessionTurnLabelNumber(
+ agent: WorkflowAgent,
+ phaseAgents: WorkflowAgent[],
+): number | null {
+ if (!shouldShowTurnInDetailOrReply(agent)) return null;
+ return phaseLocalTurnNumber(agent, phaseAgents);
+}
+
+/** @deprecated Use {@link shouldShowSessionTree} or {@link shouldShowTurnInDetailOrReply}. */
+export function shouldShowAgentTurnLabel(
+ agent: WorkflowAgent,
+ phaseAgents: WorkflowAgent[],
+): boolean {
+ return shouldShowSessionTree(agent, phaseAgents);
+}
+
+/** @deprecated Use {@link sessionTurnLabelNumber}. */
+export function agentTurnLabelNumber(
+ agent: WorkflowAgent,
+ phaseAgents: WorkflowAgent[],
+): number | null {
+ return sessionTurnLabelNumber(agent, phaseAgents);
+}
+
+/** Sort session nodes by global ``correlation_id`` turn, then ``started_at``. */
+export function sortWorkflowAgentsByTurn(agents: WorkflowAgent[]): WorkflowAgent[] {
+ return [...agents].sort((a, b) => {
+ const turnA = parseTurnFromCorrelationId(a.correlation_id);
+ const turnB = parseTurnFromCorrelationId(b.correlation_id);
+ if (turnA !== null && turnB !== null) return turnA - turnB;
+ return (a.started_at ?? "").localeCompare(b.started_at ?? "");
+ });
+}
+
+/**
+ * Split phase agents into session trees vs one-shot nodes.
+ *
+ * Every ``agent_session`` / ``human_session`` group becomes a tree (even with a
+ * single turn) so lists stay visually distinct from plain ``agent()`` /
+ * ``human()``. Plain one-shots never aggregate — even when labels repeat or a
+ * ``correlation_id`` exists.
+ */
+export function groupWorkflowAgentsByName(agents: WorkflowAgent[]): {
+ sessions: Array<{ label: string; members: WorkflowAgent[] }>;
+ oneShots: WorkflowAgent[];
+} {
+ const bySessionKey = new Map<string, WorkflowAgent[]>();
+ const oneShots: WorkflowAgent[] = [];
+
+ for (const agent of agents) {
+ const key = sessionGroupKey(agent);
+ if (!key) {
+ oneShots.push(agent);
+ continue;
+ }
+ const existing = bySessionKey.get(key) ?? [];
+ existing.push(agent);
+ bySessionKey.set(key, existing);
+ }
+
+ const sessions: Array<{ label: string; members: WorkflowAgent[] }> = [];
+
+ for (const members of bySessionKey.values()) {
+ const sorted = sortWorkflowAgentsByTurn(members);
+ sessions.push({ label: sorted[0]?.name ?? "session", members: sorted });
+ }
+
+ return { sessions, oneShots };
+}
+
+/** Pending-input banner: "M inputs waiting" (empty string when count <= 0). */
+export function pendingInputsBannerText(count: number): string {
+ if (count <= 0) return "";
+ return count === 1 ? "1 input waiting" : `${count} inputs waiting`;
+}
+
+/** Main-chat hint when human nodes are waiting for reply. */
+export function pendingHumanViewHint(): string {
+ return "h to view human inputs";
+}
+
+/** Count agents in a workflow run that are currently waiting for a human reply. */
+export function countWaitingForHuman(workflow: WorkflowRun): number {
+ let n = 0;
+ for (const phase of workflow.phases ?? []) {
+ for (const agent of phase.agents ?? []) {
+ if (agent.status === "waiting_for_human") n += 1;
+ }
+ }
+ return n;
+}
+
+/** Collect all waiting-for-human agents across a run, in phase+agent order. */
+export function collectWaitingForHuman(workflow: WorkflowRun): {
+ phase: WorkflowPhase;
+ agent: WorkflowAgent;
+}[] {
+ const out: { phase: WorkflowPhase; agent: WorkflowAgent }[] = [];
+ for (const phase of workflow.phases ?? []) {
+ for (const agent of phase.agents ?? []) {
+ if (agent.status === "waiting_for_human") out.push({ phase, agent });
+ }
+ }
+ return out;
+}
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 67394868c4..65e127b4e7 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -57,12 +57,27 @@ import { PIPELINE_VALUES, PIPELINE_OPTIONS, INTERVAL_VALUES, INTERVAL_OPTIONS, F
import { isTeamMode } from "../core/modes.js";
import {
countCompletedWorkflowAgents,
+ countWaitingForHuman,
countWorkflowAgents,
+ sessionTurnLabelNumber,
+ canOpenSessionHistory,
+ isSessionNode,
findWorkflowAgent,
+ formatWorkflowAgentKindLabel,
formatWorkflowTimingText,
+ groupWorkflowAgentsByName,
+ HUMAN_TURN_CACHED_ANSWER,
+ HUMAN_TURN_CACHED_QUESTION,
+ isHumanTurnCached,
+ pendingHumanViewHint,
+ pendingInputsBannerText,
runningWorkflowsBannerText,
+ sessionMembersInPhase,
+ shouldShowTurnInDetailOrReply,
workflowStatusBannerText,
workflowStatusIcon,
+ type WorkflowAgent,
+ type WorkflowNodeType,
type WorkflowRun,
type WorkflowStatus,
} from "../core/workflows.js";
@@ -311,6 +326,28 @@ type StatusViewState = {
searchQuery: string;
};
+type PendingListPreviousPhase = "chat" | "list" | "workflow" | "agent" | "session-detail" | null;
+
+type PendingListEntry =
+ | { kind: "workflow-header"; workflowId: string; workflowName: string }
+ | {
+ kind: "session-parent";
+ sessionLabel: string;
+ done: number;
+ total: number;
+ }
+ | {
+ kind: "waiting";
+ workflowId: string;
+ phaseId: string;
+ agentId: string;
+ sessionLabel: string;
+ turn: number;
+ isSessionChild: boolean;
+ /** Single-turn session node rendered flat (no tree); distinguishes from human()/agent(). */
+ isSession: boolean;
+ };
+
type SwarmWorkflowsViewState =
| {
phase: "list";
@@ -324,13 +361,78 @@ type SwarmWorkflowsViewState =
focus: "phases" | "agents";
phaseList: SelectList;
agentList: SelectList;
+ loadingDetail: boolean;
}
| {
phase: "agent";
workflowId: string;
agentId: string;
+ returnTo?: SessionDetailReturnTo;
+ }
+ | {
+ phase: "pending-list";
+ entries: PendingListEntry[];
+ selectedIndex: number;
+ previous_phase: PendingListPreviousPhase;
+ }
+ | {
+ phase: "session-detail";
+ workflowId: string;
+ sessionLabel: string;
+ phaseId: string;
+ /** Isolates human_session vs agent_session when labels collide in a phase. */
+ nodeType: WorkflowNodeType;
+ returnTo: SessionDetailReturnTo;
+ scrollOffset: number;
};
+type SessionDetailReturnTo =
+ | { kind: "pending-list"; previous_phase: PendingListPreviousPhase }
+ | { kind: "agent"; workflowId: string; agentId: string }
+ | { kind: "workflow"; workflowId: string; selectedPhaseId: string; selectedAgentId?: string };
+
+/** Prefer exact session primitive; fall back from kind for legacy payloads. */
+function sessionNodeTypeOf(
+ agent: Pick<WorkflowAgent, "node_type" | "kind">,
+): WorkflowNodeType {
+ if (agent.node_type === "agent_session" || agent.node_type === "human_session") {
+ return agent.node_type;
+ }
+ return agent.kind === "human" ? "human_session" : "agent_session";
+}
+
+function sessionSelectValue(
+ sessionLabel: string,
+ phaseId: string,
+ nodeType: WorkflowNodeType,
+): string {
+ return `session:${nodeType}:${sessionLabel}:${phaseId}`;
+}
+
+function parseSessionSelectValue(
+ value: string,
+): { sessionLabel: string; phaseId: string; nodeType: WorkflowNodeType } | null {
+ if (!value.startsWith("session:")) return null;
+ const rest = value.slice("session:".length);
+ const firstSep = rest.indexOf(":");
+ const lastSep = rest.lastIndexOf(":");
+ if (firstSep <= 0 || lastSep <= firstSep) return null;
+ const nodeType = rest.slice(0, firstSep);
+ if (
+ nodeType !== "agent_session" &&
+ nodeType !== "human_session" &&
+ nodeType !== "agent" &&
+ nodeType !== "human"
+ ) {
+ return null;
+ }
+ return {
+ nodeType,
+ sessionLabel: rest.slice(firstSep + 1, lastSep),
+ phaseId: rest.slice(lastSep + 1),
+ };
+}
+
function formatSwarmWorkflowsSummary(workflows: WorkflowRun[]): string {
if (workflows.length === 0) return "No workflows";
const statusOrder: WorkflowStatus[] = [
@@ -1099,6 +1201,11 @@ const planApprovalSelectListTheme = {
description: (value: string) => chalk.dim(value),
};
+const swarmWorkflowSelectListTheme = {
+ ...selectListTheme,
+ description: (value: string) => palette.text.secondary(value),
+};
+
function wrapPlainText(text: string, width: number): string[] {
const maxWidth = Math.max(12, width - 1);
const source = text.replace(/\r/g, "").split("\n");
@@ -1128,6 +1235,33 @@ function wrapPlainText(text: string, width: number): string[] {
return lines.length > 0 ? lines : [text.slice(0, maxWidth)];
}
+/** Skip separator/blank lines when showing a compact human-question preview in lists. */
+function isDecorativeQuestionLine(line: string): boolean {
+ const trimmed = line.trim();
+ if (!trimmed) return true;
+ if (/^[=\-_─━*#~.·•]{4,}$/.test(trimmed)) return true;
+ const compact = trimmed.replace(/\s/g, "");
+ return compact.length >= 4 && /^[=\-_─━*#~.+]{4,}$/.test(compact);
+}
+
+function prepareHumanQuestionPreviewLines(
+ text: string,
+ width: number,
+ maxLines = 3,
+): { lines: string[]; truncated: boolean } {
+ const contentLines = text
+ .replace(/\r/g, "")
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => !isDecorativeQuestionLine(line));
+ const source = contentLines.length > 0 ? contentLines.join("\n") : text.trim();
+ const wrapped = wrapPlainText(source, width);
+ return {
+ lines: wrapped.slice(0, maxLines),
+ truncated: wrapped.length > maxLines,
+ };
+}
+
function workflowStatusTone(status: WorkflowStatus): (value: string) => string {
switch (status) {
case "planned":
@@ -1141,8 +1275,10 @@ function workflowStatusTone(status: WorkflowStatus): (value: string) => string {
return palette.status.error;
case "stopped":
return palette.text.dim;
+ case "waiting_for_human":
+ return palette.text.humanInput;
default:
- return palette.text.dim;
+ return palette.text.secondary;
}
}
@@ -1150,6 +1286,10 @@ function formatWorkflowStatus(status: WorkflowStatus): string {
return workflowStatusTone(status)(`${workflowStatusIcon(status)} ${status}`);
}
+function formatWorkflowStatusWord(status: WorkflowStatus): string {
+ return status === "waiting_for_human" ? "waiting" : status;
+}
+
function formatWorkflowDuration(durationMs?: number | null): string | null {
if (typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs < 0) {
return null;
@@ -1324,6 +1464,14 @@ export class AppScreen implements Component, Focusable {
private statusViewState: StatusViewState | null = null;
private mvController: MemoryViewController | null = null;
private swarmWorkflowsViewState: SwarmWorkflowsViewState | null = null;
+ /** Currently-active swarmflow human reply input (null = not replying). */
+ private replyingToHumanPrompt: {
+ workflowRunId: string;
+ correlationId: string;
+ label: string;
+ turn: number;
+ isSession: boolean;
+ } | null = null;
private startupPromptList: SelectList | null = null;
private todosCollapsed = false;
private showTeamPanel = false;
@@ -1677,7 +1825,7 @@ export class AppScreen implements Component, Focusable {
const totalLines = contentLines.length;
const scrollPercent = totalLines > 0 ? Math.round((scrollOffset / totalLines) * 100) : 0;
const positionInfo = totalLines > availableHeight ? ` [${scrollOffset + 1}-${Math.min(scrollOffset + availableHeight, totalLines)}/${totalLines} (${scrollPercent}%)]` : "";
- const hintText = `按 Esc/q 退出 | ↑↓ 滚动 | PgUp/PgDown 翻页${positionInfo}`;
+ const hintText = `↑/↓ scroll · PgUp/PgDown page · Esc/← back${positionInfo}`;
lines.push(padToWidth(palette.text.dim(hintText), safeWidth));
return lines;
@@ -2267,6 +2415,24 @@ export class AppScreen implements Component, Focusable {
return;
}
+ // Swarmflow human reply input — lower priority than PendingQuestion, higher than chat.
+ if (this.replyingToHumanPrompt && this.handleSwarmflowHumanReplyInput(data)) {
+ this.tui.requestRender();
+ return;
+ }
+
+ // h key: open pending human-input list from the main chat screen.
+ if (
+ !hasOverlay &&
+ !pendingQuestion &&
+ !this.replyingToHumanPrompt &&
+ data === "h" &&
+ (snapshot.pendingHumanPrompts?.size ?? 0) > 0
+ ) {
+ void this.enterSwarmWorkflowsPendingList();
+ return;
+ }
+
// Global ctrl+l/t/g/o only apply on the main screen — defer while an overlay
// or the team panel is active so context-specific bindings (e.g. ResumeList)
// can use the same physical keys.
@@ -2731,7 +2897,8 @@ export class AppScreen implements Component, Focusable {
this.resumeSessionList !== null ||
this.state.isHelpVisible() ||
this.modelList !== null ||
- (this.mvController?.isOpen ?? false);
+ (this.mvController?.isOpen ?? false) ||
+ this.replyingToHumanPrompt !== null;
const editorLines = hideMainEditor
? []
: this.applySlashCommandHint(this.editor.render(width), width);
@@ -2750,7 +2917,8 @@ export class AppScreen implements Component, Focusable {
...this.buildMcpToolDetailLines(width),
...this.buildThemeListLines(width),
...(this.swarmWorkflowsViewState ? [] : this.buildWorkflowRuntimeLines(width)),
- ...this.buildSwarmWorkflowsLines(width),
+ ...(this.swarmWorkflowsViewState ? this.buildSwarmWorkflowsLines(width) : []),
+ ...this.buildSwarmflowHumanReplyInputLines(width),
...this.buildPendingQuestionLines(snapshot, width),
];
const showFullThinking = snapshot.transcriptMode === "detailed";
@@ -5055,9 +5223,137 @@ export class AppScreen implements Component, Focusable {
private async enterSwarmWorkflowsView(): Promise<void> {
this.state.beginDeferredTranscript();
+ this.transcriptScrollOffset = 0;
await this.openSwarmWorkflowsView();
}
+ private async enterSwarmWorkflowsPendingList(): Promise<void> {
+ this.state.beginDeferredTranscript();
+ this.transcriptScrollOffset = 0;
+ this.swarmWorkflowsViewState = this.buildPendingListState("chat");
+ this.tui.requestRender();
+ try {
+ await this.state.loadWorkflowSnapshot();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.state.addItem(
+ addError(this.state.getSnapshot().sessionId, `workflow list failed: ${message}`),
+ );
+ }
+ const detailIds = new Set<string>();
+ for (const pending of this.state.getSnapshot().pendingHumanPrompts?.values() ?? []) {
+ detailIds.add(pending.workflow_run_id);
+ }
+ for (const wf of this.state.getSnapshot().workflowRuns) {
+ for (const phase of wf.phases ?? []) {
+ for (const agent of phase.agents ?? []) {
+ if (agent.status === "waiting_for_human" && agent.kind === "human") {
+ detailIds.add(wf.id);
+ }
+ }
+ }
+ }
+ await Promise.all(
+ [...detailIds].map((workflowId) =>
+ this.state.loadWorkflowDetail(workflowId).catch(() => undefined),
+ ),
+ );
+ const promptLoads: Array<Promise<void>> = [];
+ for (const wf of this.state.getSnapshot().workflowRuns) {
+ for (const phase of wf.phases ?? []) {
+ for (const agent of phase.agents ?? []) {
+ if (agent.status === "waiting_for_human" && agent.kind === "human") {
+ promptLoads.push(this.state.ensureHumanPromptLoaded(wf.id, agent.id));
+ }
+ }
+ }
+ }
+ await Promise.all(promptLoads.map((task) => task.catch(() => undefined)));
+ this.swarmWorkflowsViewState = this.buildPendingListState("chat");
+ this.tui.requestRender();
+ }
+
+ private lookupPendingHumanPrompt(workflowId: string, agentId: string) {
+ const lookup = findWorkflowAgent(this.state.getSnapshot().workflowRuns, workflowId, agentId);
+ const corr = lookup?.agent.correlation_id ?? agentId;
+ return this.state.getSnapshot().pendingHumanPrompts?.get(`${workflowId}:${corr}`);
+ }
+
+ private getHumanQuestionText(workflowId: string, agentId: string): string {
+ const lookup = findWorkflowAgent(this.state.getSnapshot().workflowRuns, workflowId, agentId);
+ if (lookup && isHumanTurnCached(lookup.agent)) {
+ return HUMAN_TURN_CACHED_QUESTION;
+ }
+ if (lookup?.agent.human_prompt?.trim()) {
+ return lookup.agent.human_prompt.trim();
+ }
+ const pending = this.lookupPendingHumanPrompt(workflowId, agentId);
+ if (pending?.prompt?.trim()) {
+ return pending.prompt.trim();
+ }
+ return "";
+ }
+
+ private async openAgentDetailFromPendingList(
+ waiting: Extract<PendingListEntry, { kind: "waiting" }>,
+ previous_phase: PendingListPreviousPhase,
+ ): Promise<void> {
+ this.replyingToHumanPrompt = null;
+ this.editor.setText("");
+ this.editor.focused = false;
+ try {
+ await this.state.loadWorkflowDetail(waiting.workflowId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.state.addItem(
+ addError(this.state.getSnapshot().sessionId, `workflow detail failed: ${message}`),
+ );
+ }
+ this.swarmWorkflowsViewState = {
+ phase: "agent",
+ workflowId: waiting.workflowId,
+ agentId: waiting.agentId,
+ returnTo: { kind: "pending-list", previous_phase },
+ };
+ this.tui.requestRender();
+ }
+
+ private async reloadSwarmWorkflowsKeepingView(): Promise<void> {
+ const current = this.swarmWorkflowsViewState;
+ try {
+ await this.state.loadWorkflowSnapshot();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.state.addItem(
+ addError(this.state.getSnapshot().sessionId, `workflow refresh failed: ${message}`),
+ );
+ }
+ if (current?.phase === "pending-list") {
+ const detailIds = new Set<string>();
+ for (const entry of current.entries) {
+ if (entry.kind === "waiting") detailIds.add(entry.workflowId);
+ }
+ await Promise.all(
+ [...detailIds].map((id) => this.state.loadWorkflowDetail(id).catch(() => undefined)),
+ );
+ } else if (
+ current?.phase === "workflow" ||
+ current?.phase === "agent" ||
+ current?.phase === "session-detail"
+ ) {
+ try {
+ await this.state.loadWorkflowDetail(current.workflowId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.state.addItem(
+ addError(this.state.getSnapshot().sessionId, `workflow detail refresh failed: ${message}`),
+ );
+ }
+ }
+ this.refreshSwarmWorkflowsView();
+ this.tui.requestRender();
+ }
+
private closeSwarmWorkflowsView(): void {
if (!this.swarmWorkflowsViewState) return;
this.swarmWorkflowsViewState = null;
@@ -5075,6 +5371,13 @@ export class AppScreen implements Component, Focusable {
);
return;
}
+ if (current.phase === "pending-list") {
+ this.swarmWorkflowsViewState = this.buildPendingListState(
+ current.previous_phase ?? "list",
+ current.selectedIndex,
+ );
+ return;
+ }
if (current.phase === "workflow") {
const selectedAgentId =
current.focus === "agents" ? current.agentList.getSelectedItem()?.value : undefined;
@@ -5086,6 +5389,11 @@ export class AppScreen implements Component, Focusable {
);
return;
}
+ if (current.phase === "session-detail") {
+ // Re-render only — buildSessionDetailLines reads live workflow snapshot.
+ return;
+ }
+ // current.phase === "agent"
const lookup = findWorkflowAgent(
this.state.getSnapshot().workflowRuns,
current.workflowId,
@@ -5098,6 +5406,7 @@ export class AppScreen implements Component, Focusable {
phase: "agent",
workflowId: lookup.workflow.id,
agentId: lookup.agent.id,
+ returnTo: current.returnTo,
};
}
}
@@ -5128,8 +5437,7 @@ export class AppScreen implements Component, Focusable {
list.setSelectedIndex(selectedWorkflowIndex);
}
list.onSelect = (item) => {
- this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(item.value);
- this.tui.requestRender();
+ void this.openSwarmWorkflowDetail(item.value);
};
list.onCancel = () => {
this.closeSwarmWorkflowsView();
@@ -5137,11 +5445,80 @@ export class AppScreen implements Component, Focusable {
return { phase: "list", list, loading };
}
+ private async openSwarmWorkflowDetail(
+ workflowId: string,
+ selectedPhaseId?: string,
+ focus: "phases" | "agents" = "phases",
+ selectedAgentId?: string,
+ ): Promise<void> {
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
+ workflowId,
+ selectedPhaseId,
+ focus,
+ selectedAgentId,
+ true,
+ );
+ this.tui.requestRender();
+ try {
+ await this.state.loadWorkflowDetail(workflowId);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.state.addItem(
+ addError(this.state.getSnapshot().sessionId, `workflow detail failed: ${message}`),
+ );
+ }
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
+ workflowId,
+ selectedPhaseId,
+ focus,
+ selectedAgentId,
+ false,
+ );
+ this.tui.requestRender();
+ }
+
+ /** Open agent detail or session history from the agents SelectList. */
+ private selectSwarmWorkflowAgentListItem(
+ workflowId: string,
+ activePhaseId: string,
+ item: SelectItem,
+ ): void {
+ const sessionRef = parseSessionSelectValue(item.value);
+ if (sessionRef) {
+ this.openSessionDetail(
+ workflowId,
+ sessionRef.sessionLabel,
+ sessionRef.phaseId,
+ sessionRef.nodeType,
+ {
+ kind: "workflow",
+ workflowId,
+ selectedPhaseId: activePhaseId,
+ selectedAgentId: item.value,
+ },
+ );
+ return;
+ }
+ const lookup = findWorkflowAgent(
+ this.state.getSnapshot().workflowRuns,
+ workflowId,
+ item.value,
+ );
+ if (!lookup) return;
+ this.swarmWorkflowsViewState = {
+ phase: "agent",
+ workflowId,
+ agentId: item.value,
+ };
+ this.tui.requestRender();
+ }
+
private buildSwarmWorkflowDetailState(
workflowId: string,
selectedPhaseId?: string,
focus: "phases" | "agents" = "phases",
selectedAgentId?: string,
+ loadingDetail = false,
): SwarmWorkflowsViewState {
const workflow = this.state.getSnapshot().workflowRuns.find((item) => item.id === workflowId);
if (!workflow) return this.buildSwarmWorkflowsListState(false, workflowId);
@@ -5165,7 +5542,7 @@ export class AppScreen implements Component, Focusable {
const phaseList = new SelectList(
phaseItems,
Math.min(Math.max(phaseItems.length, 1), 8),
- selectListTheme,
+ swarmWorkflowSelectListTheme,
{
minPrimaryColumnWidth: 22,
maxPrimaryColumnWidth: 36,
@@ -5193,32 +5570,60 @@ export class AppScreen implements Component, Focusable {
this.tui.requestRender();
};
- const agentItems: SelectItem[] = (selectedPhase?.agents ?? []).map((agent) => ({
- value: agent.id,
- label: `${formatWorkflowStatus(agent.status)} ${agent.name}`,
- description: agent.model ?? "",
- }));
+ // Build agent SelectList: session trees (incl. single-turn) + one-shots
+ const agents = selectedPhase?.agents ?? [];
+ const agentItems: SelectItem[] = [];
+ const { sessions, oneShots } = groupWorkflowAgentsByName(agents);
+
+ for (const { label, members } of sessions) {
+ const firstMember = members[0]!;
+ const aggregateStatus = this.aggregateSessionStatus(members);
+ const modelOrHuman = formatWorkflowAgentKindLabel(firstMember);
+ const nodeType = sessionNodeTypeOf(firstMember);
+ agentItems.push({
+ value: sessionSelectValue(label, activePhaseId, nodeType),
+ label: `${formatWorkflowStatus(aggregateStatus)} ${label}`,
+ description: `${this.formatSessionProgress(members)} · ${modelOrHuman}`,
+ });
+
+ for (let i = 0; i < members.length; i++) {
+ const member = members[i]!;
+ const turn = this.agentTurnNumber(member, i);
+ const isLast = i === members.length - 1;
+ const branch = isLast ? "└" : "├";
+ const turnModelOrHuman = formatWorkflowAgentKindLabel(member);
+ agentItems.push({
+ value: member.id,
+ label: this.formatSessionTurnSelectLabel(branch, turn, member.status),
+ description: isHumanTurnCached(member)
+ ? `${turnModelOrHuman} · cached`
+ : turnModelOrHuman,
+ });
+ }
+ }
+
+ for (const agent of oneShots) {
+ agentItems.push({
+ value: agent.id,
+ label: `${formatWorkflowStatus(agent.status)} ${agent.name}`,
+ description: formatWorkflowAgentKindLabel(agent),
+ });
+ }
const agentList = new SelectList(
agentItems,
Math.min(Math.max(agentItems.length, 1), 10),
- selectListTheme,
+ swarmWorkflowSelectListTheme,
{
minPrimaryColumnWidth: 24,
maxPrimaryColumnWidth: 44,
},
);
- const selectedAgentIndex = Math.max(
- 0,
- agentItems.findIndex((agent) => agent.value === selectedAgentId),
- );
+ const selectedAgentIndex = selectedAgentId
+ ? Math.max(0, agentItems.findIndex((agent) => agent.value === selectedAgentId))
+ : 0;
agentList.setSelectedIndex(selectedAgentIndex);
agentList.onSelect = (item) => {
- this.swarmWorkflowsViewState = {
- phase: "agent",
- workflowId,
- agentId: item.value,
- };
- this.tui.requestRender();
+ this.selectSwarmWorkflowAgentListItem(workflowId, activePhaseId, item);
};
agentList.onCancel = () => {
this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
@@ -5235,6 +5640,7 @@ export class AppScreen implements Component, Focusable {
focus,
phaseList,
agentList,
+ loadingDetail,
};
}
@@ -5243,28 +5649,65 @@ export class AppScreen implements Component, Focusable {
if (!state) return;
const action = resolveAction("SwarmWorkflows", data);
if (action === "swarm:back") {
+ if (state.phase === "pending-list") {
+ this.restoreFromPendingList(state.previous_phase);
+ this.tui.requestRender();
+ return;
+ }
if (state.phase === "list") {
this.closeSwarmWorkflowsView();
} else if (state.phase === "workflow") {
this.swarmWorkflowsViewState = this.buildSwarmWorkflowsListState(false, state.workflowId);
- } else {
- const lookup = findWorkflowAgent(
- this.state.getSnapshot().workflowRuns,
- state.workflowId,
- state.agentId,
- );
- this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
- state.workflowId,
- lookup?.phase.id,
- "agents",
- state.agentId,
- );
+ } else if (state.phase === "agent") {
+ if (state.returnTo?.kind === "pending-list") {
+ this.replyingToHumanPrompt = null;
+ this.editor.setText("");
+ this.editor.focused = false;
+ this.swarmWorkflowsViewState = this.buildPendingListState(
+ state.returnTo.previous_phase ?? "chat",
+ );
+ } else {
+ const lookup = findWorkflowAgent(
+ this.state.getSnapshot().workflowRuns,
+ state.workflowId,
+ state.agentId,
+ );
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
+ state.workflowId,
+ lookup?.phase.id,
+ "agents",
+ state.agentId,
+ );
+ }
+ } else if (state.phase === "session-detail") {
+ this.restoreFromSessionDetail(state.returnTo);
}
+ // pending-list phase is handled separately above
this.tui.requestRender();
return;
}
if (action === "swarm:left") {
+ if (state.phase === "list") {
+ this.closeSwarmWorkflowsView();
+ this.tui.requestRender();
+ return;
+ }
+ if (state.phase === "pending-list") {
+ this.restoreFromPendingList(state.previous_phase);
+ this.tui.requestRender();
+ return;
+ }
if (state.phase === "agent") {
+ if (state.returnTo?.kind === "pending-list") {
+ this.replyingToHumanPrompt = null;
+ this.editor.setText("");
+ this.editor.focused = false;
+ this.swarmWorkflowsViewState = this.buildPendingListState(
+ state.returnTo.previous_phase ?? "chat",
+ );
+ this.tui.requestRender();
+ return;
+ }
const lookup = findWorkflowAgent(
this.state.getSnapshot().workflowRuns,
state.workflowId,
@@ -5276,6 +5719,8 @@ export class AppScreen implements Component, Focusable {
"agents",
state.agentId,
);
+ } else if (state.phase === "session-detail") {
+ this.restoreFromSessionDetail(state.returnTo);
} else if (state.phase === "workflow") {
this.swarmWorkflowsViewState =
state.focus === "agents"
@@ -5290,14 +5735,33 @@ export class AppScreen implements Component, Focusable {
this.tui.requestRender();
return;
}
- if (state.phase === "workflow" && action === "swarm:nextFocus") {
- const nextFocus = state.focus === "phases" ? "agents" : "phases";
- this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
- state.workflowId,
- state.selectedPhaseId,
- nextFocus,
- );
- this.tui.requestRender();
+ if (action === "swarm:nextFocus") {
+ if (state.phase === "list") {
+ const item = state.list.getSelectedItem();
+ if (item) {
+ void this.openSwarmWorkflowDetail(item.value);
+ }
+ return;
+ }
+ if (state.phase === "workflow") {
+ if (state.focus === "phases") {
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
+ state.workflowId,
+ state.selectedPhaseId,
+ "agents",
+ );
+ this.tui.requestRender();
+ } else {
+ const item = state.agentList.getSelectedItem();
+ if (item) {
+ this.selectSwarmWorkflowAgentListItem(
+ state.workflowId,
+ state.selectedPhaseId,
+ item,
+ );
+ }
+ }
+ }
return;
}
if (state.phase === "workflow" && action === "swarm:logs") {
@@ -5305,11 +5769,27 @@ export class AppScreen implements Component, Focusable {
return;
}
if (state.phase === "agent") {
- if (action === "swarm:viewPrompt") {
+ // For human nodes, Q key shows question; for agent nodes, P key shows prompt
+ const lookup = findWorkflowAgent(
+ this.state.getSnapshot().workflowRuns,
+ state.workflowId,
+ state.agentId,
+ );
+ const isHuman = lookup?.agent.kind === "human";
+
+ if (action === "swarm:viewPrompt" || (!isHuman && matchesKey(data, "p"))) {
this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "prompt");
return;
}
- if (action === "swarm:viewOutcome") {
+ if (isHuman && matchesKey(data, "q")) {
+ this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "human_prompt");
+ return;
+ }
+ if (isHuman && matchesKey(data, "a")) {
+ this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "human_reply");
+ return;
+ }
+ if (!isHuman && action === "swarm:viewOutcome") {
this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "outcome");
return;
}
@@ -5317,18 +5797,193 @@ export class AppScreen implements Component, Focusable {
this.openSwarmWorkflowAgentText(state.workflowId, state.agentId, "error");
return;
}
+ // S: session history for agent_session / human_session nodes only
+ if (
+ matchesKey(data, "s") &&
+ lookup &&
+ canOpenSessionHistory(lookup.agent)
+ ) {
+ if (
+ this.tryOpenSessionDetailFromAgent(state.workflowId, state.agentId, {
+ kind: "agent",
+ workflowId: state.workflowId,
+ agentId: state.agentId,
+ })
+ ) {
+ return;
+ }
+ }
+ // Tab on a waiting_for_human node enters reply mode.
+ if (matchesKey(data, "tab")) {
+ if (lookup?.agent.status === "waiting_for_human") {
+ this.replyingToHumanPrompt = {
+ workflowRunId: state.workflowId,
+ correlationId: lookup.agent.correlation_id ?? lookup.agent.id,
+ label: lookup.agent.name,
+ turn: sessionTurnLabelNumber(lookup.agent, lookup.phase.agents ?? []) ?? 0,
+ isSession: shouldShowTurnInDetailOrReply(lookup.agent),
+ };
+ this.editor.setText("");
+ this.editor.focused = true;
+ this.tui.requestRender();
+ return;
+ }
+ }
}
- if (action === "swarm:refresh") {
- void this.openSwarmWorkflowsView();
+ if (state.phase === "session-detail") {
+ // Scroll / paging over the (potentially long) session history body.
+ // Render clamps scrollOffset to the real max, so overshoot is safe here.
+ const page = Math.max(1, this.sessionDetailBodyViewport(5) - 1);
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
+ state.scrollOffset = Math.max(0, state.scrollOffset - 1);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "down") || matchesKey(data, "j")) {
+ state.scrollOffset = state.scrollOffset + 1;
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "pageUp")) {
+ state.scrollOffset = Math.max(0, state.scrollOffset - page);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "pageDown")) {
+ state.scrollOffset = state.scrollOffset + page;
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "home")) {
+ state.scrollOffset = 0;
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "end")) {
+ state.scrollOffset = Number.MAX_SAFE_INTEGER;
+ this.tui.requestRender();
+ return;
+ }
+ // Tab: enter reply mode for the waiting turn (if any)
+ if (matchesKey(data, "tab")) {
+ const workflow = this.state.getSnapshot().workflowRuns.find((w) => w.id === state.workflowId);
+ const phase = workflow?.phases.find((item) => item.id === state.phaseId);
+ if (phase) {
+ for (const agent of phase.agents ?? []) {
+ if (
+ agent.name === state.sessionLabel &&
+ agent.status === "waiting_for_human" &&
+ agent.kind === "human" &&
+ sessionNodeTypeOf(agent) === state.nodeType
+ ) {
+ this.replyingToHumanPrompt = {
+ workflowRunId: state.workflowId,
+ correlationId: agent.correlation_id ?? agent.id,
+ label: agent.name,
+ turn: sessionTurnLabelNumber(agent, phase.agents ?? []) ?? 0,
+ isSession: shouldShowTurnInDetailOrReply(agent),
+ };
+ this.editor.setText("");
+ this.editor.focused = true;
+ this.tui.requestRender();
+ return;
+ }
+ }
+ }
+ }
+ }
+ if (action === "swarm:refresh") {
+ if (
+ state.phase === "session-detail" ||
+ state.phase === "agent" ||
+ state.phase === "workflow" ||
+ state.phase === "pending-list"
+ ) {
+ void this.reloadSwarmWorkflowsKeepingView();
+ return;
+ }
+ void this.openSwarmWorkflowsView();
this.tui.requestRender();
return;
}
+ // Esc / navigation from pending-list
+ if (state.phase === "pending-list") {
+ if (matchesKey(data, "return") || matchesKey(data, "right")) {
+ const waiting = this.getSelectedPendingListWaiting(state);
+ if (waiting) {
+ void this.openAgentDetailFromPendingList(waiting, state.previous_phase);
+ }
+ return;
+ }
+ if (matchesKey(data, "q")) {
+ const waiting = this.getSelectedPendingListWaiting(state);
+ if (waiting) {
+ void this.state.ensureHumanPromptLoaded(waiting.workflowId, waiting.agentId).then(() => {
+ this.openSwarmWorkflowAgentText(waiting.workflowId, waiting.agentId, "human_prompt");
+ this.tui.requestRender();
+ });
+ }
+ return;
+ }
+ if (matchesKey(data, "s")) {
+ const waiting = this.getSelectedPendingListWaiting(state);
+ if (
+ waiting &&
+ this.tryOpenSessionDetailFromAgent(waiting.workflowId, waiting.agentId, {
+ kind: "pending-list",
+ previous_phase: state.previous_phase,
+ })
+ ) {
+ return;
+ }
+ }
+ if (matchesKey(data, "tab")) {
+ void this.startReplyFromPendingListWaiting(state);
+ return;
+ }
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
+ state.selectedIndex = Math.max(0, state.selectedIndex - 1);
+ this.tui.requestRender();
+ return;
+ }
+ if (matchesKey(data, "down") || matchesKey(data, "j")) {
+ const count = this.countPendingListWaitingEntries(state);
+ state.selectedIndex = Math.min(Math.max(count - 1, 0), state.selectedIndex + 1);
+ this.tui.requestRender();
+ return;
+ }
+ return;
+ }
if (state.phase === "list") {
state.list.handleInput(data);
this.tui.requestRender();
return;
}
if (state.phase === "workflow") {
+ // Entry B: Tab key in agents focus mode → quick reply to selected waiting human turn
+ if (matchesKey(data, "tab") && state.focus === "agents") {
+ const selectedItem = state.agentList.getSelectedItem();
+ if (selectedItem && !selectedItem.value.startsWith("session:")) {
+ const lookup = findWorkflowAgent(
+ this.state.getSnapshot().workflowRuns,
+ state.workflowId,
+ selectedItem.value,
+ );
+ if (lookup && lookup.agent.status === "waiting_for_human" && lookup.agent.kind === "human") {
+ this.replyingToHumanPrompt = {
+ workflowRunId: state.workflowId,
+ correlationId: lookup.agent.correlation_id ?? lookup.agent.id,
+ label: lookup.agent.name,
+ turn: sessionTurnLabelNumber(lookup.agent, lookup.phase.agents ?? []) ?? 0,
+ isSession: shouldShowTurnInDetailOrReply(lookup.agent),
+ };
+ this.editor.setText("");
+ this.editor.focused = true;
+ this.tui.requestRender();
+ return;
+ }
+ }
+ }
const activeList = state.focus === "phases" ? state.phaseList : state.agentList;
activeList.handleInput(data);
this.tui.requestRender();
@@ -5351,14 +6006,36 @@ export class AppScreen implements Component, Focusable {
private openSwarmWorkflowAgentText(
workflowId: string,
agentId: string,
- field: "prompt" | "outcome" | "error",
+ field: "prompt" | "outcome" | "error" | "human_prompt" | "human_reply",
): void {
const lookup = findWorkflowAgent(this.state.getSnapshot().workflowRuns, workflowId, agentId);
if (!lookup) return;
- const value = lookup.agent[field];
+ const cached = isHumanTurnCached(lookup.agent);
+ const value =
+ field === "human_prompt"
+ ? cached
+ ? HUMAN_TURN_CACHED_QUESTION
+ : lookup.agent.human_prompt || this.getHumanQuestionText(workflowId, agentId)
+ : field === "human_reply"
+ ? cached
+ ? HUMAN_TURN_CACHED_ANSWER
+ : lookup.agent.human_reply
+ : lookup.agent[field];
if (!value) return;
- const label = field.charAt(0).toUpperCase() + field.slice(1);
- this.enterFileViewer(value, `${label} - ${lookup.agent.name}`, lookup.workflow.name);
+ const label =
+ field === "human_reply"
+ ? "Answer"
+ : field === "human_prompt"
+ ? "Question"
+ : field.charAt(0).toUpperCase() + field.slice(1);
+ let display = value;
+ try {
+ const parsed = JSON.parse(value);
+ display = JSON.stringify(parsed, null, 2);
+ } catch {
+ // not JSON, use as-is
+ }
+ this.enterFileViewer(display, `${label} - ${lookup.agent.name}`, lookup.workflow.name);
}
private buildSwarmWorkflowsLines(width: number): string[] {
@@ -5367,33 +6044,66 @@ export class AppScreen implements Component, Focusable {
if (state.phase === "list") {
return this.buildSwarmWorkflowsListLines(state, width);
}
+ if (state.phase === "pending-list") {
+ return this.buildPendingListLines(state, width);
+ }
if (state.phase === "workflow") {
return this.buildSwarmWorkflowDetailLines(state, width);
}
+ if (state.phase === "session-detail") {
+ return this.buildSessionDetailLines(state, width);
+ }
return this.buildSwarmWorkflowAgentLines(state, width);
}
private buildWorkflowRuntimeLines(width: number): string[] {
- const runningWorkflows = this.state
- .getSnapshot()
- .workflowRuns.filter((item) => item.status === "running");
- if (runningWorkflows.length === 0) return [];
- const spinner = palette.status.warning(["◐", "◓", "◑", "◒"][this.animationPhase % 4]!);
+ const snapshot = this.state.getSnapshot();
+ const workflowRuns = snapshot.workflowRuns;
+ const pendingPrompts = snapshot.pendingHumanPrompts;
- const renderRow = (workflow: WorkflowRun, prefix: string): string =>
- padToWidth(
- `${prefix}${palette.text.dim(workflow.name)} ${palette.text.dim(formatWorkflowTimingText(workflow))}`,
+ const runningWorkflows = workflowRuns.filter((item) => item.status === "running");
+ const totalPending = pendingPrompts?.size ?? 0;
+
+ if (runningWorkflows.length === 0 && totalPending === 0) return [];
+
+ const waitingIcon = workflowStatusIcon("waiting_for_human");
+ const spinner =
+ totalPending > 0
+ ? palette.text.humanInput(`${waitingIcon} `)
+ : palette.status.warning(["◐", "◓", "◑", "◒"][this.animationPhase % 4]!);
+
+ const renderRow = (workflow: WorkflowRun): string => {
+ const pendingCount = countWaitingForHuman(workflow);
+ const nameAndTime = `${palette.text.dim(workflow.name)} ${palette.text.dim(formatWorkflowTimingText(workflow))}`;
+ const suffix = pendingCount > 0 ? ` ${palette.text.dim(`· ${pendingCount} waiting`)}` : "";
+ return padToWidth(` ${nameAndTime}${suffix}`, width);
+ };
+
+ if (totalPending > 0) {
+ const runningSuffix =
+ runningWorkflows.length > 0
+ ? ` · ${palette.text.assistant(runningWorkflowsBannerText(runningWorkflows.length))}`
+ : "";
+ const firstLine = padToWidth(
+ `${spinner}${palette.text.humanInput(pendingInputsBannerText(totalPending))} · ${palette.text.dim(pendingHumanViewHint())}${runningSuffix}`,
width,
);
+ const lines = [firstLine];
+ for (const wf of runningWorkflows) {
+ lines.push(renderRow(wf));
+ }
+ return lines;
+ }
+ // No pending — original behaviour.
if (runningWorkflows.length === 1) {
const workflow = runningWorkflows[0]!;
return [
+ padToWidth(`${spinner} ${palette.text.assistant(runningWorkflowsBannerText(1))}`, width),
padToWidth(
- `${spinner} ${palette.text.assistant(runningWorkflowsBannerText(1))}`,
+ ` ${palette.text.dim(workflow.name)} ${palette.text.dim(formatWorkflowTimingText(workflow))}`,
width,
),
- renderRow(workflow, " "),
];
}
@@ -5403,8 +6113,8 @@ export class AppScreen implements Component, Focusable {
width,
),
];
- for (const workflow of runningWorkflows) {
- lines.push(renderRow(workflow, " "));
+ for (const wf of runningWorkflows) {
+ lines.push(renderRow(wf));
}
return lines;
}
@@ -5424,7 +6134,7 @@ export class AppScreen implements Component, Focusable {
),
];
const helpLine = padToWidth(
- palette.text.dim("up/down select - Enter view - r refresh - Esc close"),
+ palette.text.dim("↑/↓ select · Enter/→ load detail · r refresh · Esc/← close"),
width,
);
if (state.loading || workflows.length === 0) {
@@ -5438,6 +6148,278 @@ export class AppScreen implements Component, Focusable {
];
}
+ private countPendingListWaitingEntries(
+ state: Extract<SwarmWorkflowsViewState, { phase: "pending-list" }>,
+ ): number {
+ return state.entries.filter((entry) => entry.kind === "waiting").length;
+ }
+
+ private getSelectedPendingListWaiting(
+ state: Extract<SwarmWorkflowsViewState, { phase: "pending-list" }>,
+ ): Extract<PendingListEntry, { kind: "waiting" }> | null {
+ const waitingEntries = state.entries.filter(
+ (entry): entry is Extract<PendingListEntry, { kind: "waiting" }> => entry.kind === "waiting",
+ );
+ return waitingEntries[state.selectedIndex] ?? null;
+ }
+
+ private prefetchPendingListQuestion(waiting: Extract<PendingListEntry, { kind: "waiting" }>): void {
+ void this.state.ensureHumanPromptLoaded(waiting.workflowId, waiting.agentId).then(() => {
+ if (this.swarmWorkflowsViewState?.phase === "pending-list") {
+ this.tui.requestRender();
+ }
+ });
+ }
+
+ private startReplyFromPendingListWaiting(
+ state: Extract<SwarmWorkflowsViewState, { phase: "pending-list" }>,
+ ): boolean {
+ const waiting = this.getSelectedPendingListWaiting(state);
+ if (!waiting) return false;
+ void this.state.ensureHumanPromptLoaded(waiting.workflowId, waiting.agentId).then(() => {
+ if (this.startReplyFromPendingListWaitingSync(state)) {
+ this.tui.requestRender();
+ }
+ });
+ return true;
+ }
+
+ private startReplyFromPendingListWaitingSync(
+ state: Extract<SwarmWorkflowsViewState, { phase: "pending-list" }>,
+ ): boolean {
+ const waiting = this.getSelectedPendingListWaiting(state);
+ if (!waiting) return false;
+ const lookup = findWorkflowAgent(
+ this.state.getSnapshot().workflowRuns,
+ waiting.workflowId,
+ waiting.agentId,
+ );
+ if (!lookup || lookup.agent.status !== "waiting_for_human") return false;
+ this.replyingToHumanPrompt = {
+ workflowRunId: waiting.workflowId,
+ correlationId: lookup.agent.correlation_id ?? lookup.agent.id,
+ label: lookup.agent.name,
+ turn: waiting.turn,
+ isSession: shouldShowTurnInDetailOrReply(lookup.agent),
+ };
+ this.editor.setText("");
+ this.editor.focused = true;
+ this.tui.requestRender();
+ return true;
+ }
+
+ private restoreFromPendingList(previous_phase: PendingListPreviousPhase): void {
+ this.replyingToHumanPrompt = null;
+ this.editor.setText("");
+ this.editor.focused = false;
+ if (previous_phase === "chat") {
+ this.closeSwarmWorkflowsView();
+ return;
+ }
+ if (previous_phase === "list") {
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowsListState(false);
+ return;
+ }
+ if (previous_phase === "workflow") {
+ const workflows = this.state.getSnapshot().workflowRuns;
+ if (workflows.length > 0) {
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(workflows[0]!.id);
+ } else {
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowsListState(false);
+ }
+ return;
+ }
+ if (previous_phase === "agent" || previous_phase === "session-detail") {
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowsListState(false);
+ return;
+ }
+ this.closeSwarmWorkflowsView();
+ }
+
+ private buildPendingListState(
+ previous_phase: PendingListPreviousPhase,
+ selectedIndex = 0,
+ ): SwarmWorkflowsViewState {
+ const workflows = this.state.getSnapshot().workflowRuns;
+ const entries: PendingListEntry[] = [];
+
+ for (const workflow of workflows) {
+ let workflowHeaderAdded = false;
+
+ for (const phase of workflow.phases ?? []) {
+ const waitingAgents = (phase.agents ?? []).filter(
+ (agent) => agent.status === "waiting_for_human" && agent.kind === "human",
+ );
+ if (waitingAgents.length === 0) continue;
+
+ if (!workflowHeaderAdded) {
+ entries.push({
+ kind: "workflow-header",
+ workflowId: workflow.id,
+ workflowName: workflow.name,
+ });
+ workflowHeaderAdded = true;
+ }
+
+ const { sessions, oneShots } = groupWorkflowAgentsByName(phase.agents ?? []);
+ const waitingIds = new Set(waitingAgents.map((agent) => agent.id));
+
+ for (const { label, members } of sessions) {
+ const waitingMembers = members.filter((member) => waitingIds.has(member.id));
+ if (waitingMembers.length === 0) continue;
+
+ entries.push({
+ kind: "session-parent",
+ sessionLabel: label,
+ done: this.sessionDoneCount(members),
+ total: this.sessionTotalCount(members),
+ });
+
+ for (const member of waitingMembers) {
+ const turnIndex = members.findIndex((item) => item.id === member.id);
+ entries.push({
+ kind: "waiting",
+ workflowId: workflow.id,
+ phaseId: phase.id,
+ agentId: member.id,
+ sessionLabel: label,
+ turn: this.agentTurnNumber(member, Math.max(turnIndex, 0)),
+ isSessionChild: true,
+ isSession: true,
+ });
+ }
+ }
+
+ for (const agent of oneShots) {
+ if (!waitingIds.has(agent.id)) continue;
+ const isSession = isSessionNode(agent);
+ entries.push({
+ kind: "waiting",
+ workflowId: workflow.id,
+ phaseId: phase.id,
+ agentId: agent.id,
+ sessionLabel: agent.name,
+ turn: sessionTurnLabelNumber(agent, phase.agents ?? []) ?? 0,
+ isSessionChild: false,
+ isSession,
+ });
+ }
+ }
+ }
+
+ const waitingCount = entries.filter((entry) => entry.kind === "waiting").length;
+ return {
+ phase: "pending-list",
+ entries,
+ selectedIndex: Math.min(Math.max(selectedIndex, 0), Math.max(waitingCount - 1, 0)),
+ previous_phase,
+ };
+ }
+
+ private buildPendingListLines(
+ state: Extract<SwarmWorkflowsViewState, { phase: "pending-list" }>,
+ width: number,
+ options: { overlay?: boolean } = {},
+ ): string[] {
+ const overlay = options.overlay ?? false;
+ const divider = padToWidth(palette.text.dim("─".repeat(Math.max(1, width))), width);
+ const waitingCount = this.countPendingListWaitingEntries(state);
+ const headerLines = overlay
+ ? [
+ divider,
+ padToWidth(
+ palette.text.humanInput(
+ `${workflowStatusIcon("waiting_for_human")} Pending human replies`,
+ ),
+ width,
+ ),
+ padToWidth(
+ palette.text.secondary(
+ waitingCount === 0
+ ? "No pending replies · Esc/← back to chat"
+ : `${waitingCount} waiting · Esc/← back to chat`,
+ ),
+ width,
+ ),
+ divider,
+ ]
+ : [
+ padToWidth(palette.text.humanInput("Pending human replies"), width),
+ padToWidth(
+ palette.text.secondary(
+ waitingCount === 0 ? "No pending replies" : `${waitingCount} waiting`,
+ ),
+ width,
+ ),
+ ];
+ const helpLine = padToWidth(
+ palette.text.secondary(
+ overlay
+ ? "↑/↓ select · Enter detail · Tab reply · s session · q question · Esc/← back to chat"
+ : "↑/↓ select · Enter detail · Tab reply · s session · q question · Esc/← back",
+ ),
+ width,
+ );
+ if (waitingCount === 0) {
+ return [...headerLines, "", helpLine, ...(overlay ? ["", divider] : [])];
+ }
+
+ const lines: string[] = [...headerLines, ""];
+ const waitingIcon = palette.text.humanInput(workflowStatusIcon("waiting_for_human"));
+ const waitingPrefix = `${waitingIcon} `;
+ let waitingCursor = 0;
+ for (const entry of state.entries) {
+ if (entry.kind === "workflow-header") {
+ lines.push(padToWidth(palette.text.accent(entry.workflowName), width));
+ continue;
+ }
+ if (entry.kind === "session-parent") {
+ lines.push(
+ padToWidth(
+ ` ${entry.sessionLabel} ${palette.text.secondary(`· human · ${entry.done}/${entry.total}`)}`,
+ width,
+ ),
+ );
+ continue;
+ }
+
+ const selected = waitingCursor === state.selectedIndex;
+ waitingCursor += 1;
+ const marker = selected ? palette.text.accent("›") : " ";
+ const label = entry.isSessionChild
+ ? `${palette.text.dim(" └")} ${waitingPrefix}turn ${entry.turn} ${palette.text.secondary("· waiting")}`
+ : entry.isSession
+ ? `${waitingPrefix}${entry.sessionLabel} ${palette.text.secondary(`· turn ${entry.turn} · waiting`)}`
+ : `${waitingPrefix}${entry.sessionLabel} ${palette.text.secondary("· waiting")}`;
+ lines.push(padToWidth(`${marker}${selected ? " " : " "}${label}`, width));
+ if (selected) {
+ const question = this.getHumanQuestionText(entry.workflowId, entry.agentId);
+ if (question) {
+ const previewWidth = Math.max(20, width - 10);
+ const { lines: previewLines, truncated } = prepareHumanQuestionPreviewLines(
+ question,
+ previewWidth,
+ 3,
+ );
+ lines.push(padToWidth(palette.text.secondary(" Question"), width));
+ for (const qLine of previewLines) {
+ lines.push(padToWidth(palette.text.dim(` ${qLine}`), width));
+ }
+ if (truncated) {
+ lines.push(padToWidth(palette.text.dim(" … press q for full question"), width));
+ }
+ } else {
+ lines.push(
+ padToWidth(palette.text.dim(" Question: (loading…)"), width),
+ );
+ }
+ }
+ }
+
+ lines.push("", ...(overlay ? [divider, ""] : []), helpLine);
+ return lines;
+ }
+
private buildSwarmWorkflowDetailLines(
state: Extract<SwarmWorkflowsViewState, { phase: "workflow" }>,
width: number,
@@ -5466,6 +6448,16 @@ export class AppScreen implements Component, Focusable {
width,
),
padToWidth(palette.text.dim(formatWorkflowTimingText(workflow)), width),
+ ...(state.loadingDetail
+ ? [padToWidth(palette.text.dim("Loading workflow details…"), width)]
+ : workflow.truncated
+ ? [
+ padToWidth(
+ palette.status.warning("⚠ Large workflow — some fields were truncated"),
+ width,
+ ),
+ ]
+ : []),
...(workflow.status === "failed" && workflow.error
? wrapPlainText(workflow.error, width).map((line) =>
padToWidth(palette.status.error(line), width),
@@ -5489,7 +6481,14 @@ export class AppScreen implements Component, Focusable {
lines.push(...this.renderSwarmWorkflowPhaseRows(workflow, state.selectedPhaseId, width));
}
lines.push("");
- const agentsTitle = selectedPhase ? `Agents · ${selectedPhase.name}` : "Agents";
+ const agentsTitle =
+ state.focus === "agents"
+ ? selectedPhase
+ ? `select agents · ${selectedPhase.name}`
+ : "select agents"
+ : selectedPhase
+ ? `Agents · ${selectedPhase.name}`
+ : "Agents";
lines.push(
padToWidth(
state.focus === "agents"
@@ -5511,13 +6510,13 @@ export class AppScreen implements Component, Focusable {
} else {
lines.push(padToWidth(palette.text.dim("No agents"), width));
}
- lines.push(padToWidth(palette.text.dim("press l to see full logs"), width));
+ lines.push(padToWidth(palette.text.secondary("press l to see full logs"), width));
lines.push(
padToWidth(
- palette.text.dim(
+ palette.text.secondary(
state.focus === "phases"
- ? "up/down select phase · Enter show agents · Tab/Right agents · Esc back"
- : "up/down select agent · Enter detail · Tab/Left phases · r refresh · Esc back",
+ ? "↑/↓ select phase · Enter/→ show agents · Esc/← back"
+ : "↑/↓ select · Enter/→ detail/session · Tab reply (human) · ← phases · Esc/← back",
),
width,
),
@@ -5561,31 +6560,549 @@ export class AppScreen implements Component, Focusable {
});
}
+ /** Phase-local 0-based turn label (see ``phaseLocalTurnNumber`` in workflows.ts). */
+ private agentTurnNumber(
+ agent: WorkflowRun["phases"][number]["agents"][number],
+ indexInSession: number,
+ ): number {
+ return indexInSession;
+ }
+
+ private formatSessionTurnSelectLabel(
+ branch: string,
+ turn: number,
+ status: WorkflowStatus,
+ ): string {
+ const icon = workflowStatusIcon(status);
+ const tone = workflowStatusTone(status);
+ const statusWord = formatWorkflowStatusWord(status);
+ return ` ${branch} ${tone(`${icon} turn ${turn} · ${statusWord}`)}`;
+ }
+
+ /** Total session turns visible in the current phase. */
+ private sessionTotalCount(members: WorkflowRun["phases"][number]["agents"]): number {
+ return members.length;
+ }
+
+ private sessionDetailReturnToForCurrentView(
+ workflowId: string,
+ agentId: string,
+ ): SessionDetailReturnTo {
+ const state = this.swarmWorkflowsViewState;
+ if (state?.phase === "pending-list") {
+ return { kind: "pending-list", previous_phase: state.previous_phase };
+ }
+ if (state?.phase === "agent") {
+ return { kind: "agent", workflowId: state.workflowId, agentId: state.agentId };
+ }
+ if (state?.phase === "workflow") {
+ return {
+ kind: "workflow",
+ workflowId: state.workflowId,
+ selectedPhaseId: state.selectedPhaseId,
+ selectedAgentId:
+ state.focus === "agents" ? state.agentList.getSelectedItem()?.value : undefined,
+ };
+ }
+ return { kind: "agent", workflowId, agentId };
+ }
+
+ private openSessionDetail(
+ workflowId: string,
+ sessionLabel: string,
+ phaseId: string,
+ nodeType: WorkflowNodeType,
+ returnTo: SessionDetailReturnTo,
+ ): void {
+ this.swarmWorkflowsViewState = {
+ phase: "session-detail",
+ workflowId,
+ sessionLabel,
+ phaseId,
+ nodeType,
+ returnTo,
+ scrollOffset: 0,
+ };
+ this.tui.requestRender();
+ }
+
+ private restoreFromSessionDetail(returnTo: SessionDetailReturnTo): void {
+ switch (returnTo.kind) {
+ case "pending-list":
+ this.swarmWorkflowsViewState = this.buildPendingListState(returnTo.previous_phase ?? "list");
+ break;
+ case "agent":
+ this.swarmWorkflowsViewState = {
+ phase: "agent",
+ workflowId: returnTo.workflowId,
+ agentId: returnTo.agentId,
+ };
+ break;
+ case "workflow":
+ this.swarmWorkflowsViewState = this.buildSwarmWorkflowDetailState(
+ returnTo.workflowId,
+ returnTo.selectedPhaseId,
+ "agents",
+ returnTo.selectedAgentId,
+ );
+ break;
+ }
+ }
+
+ private tryOpenSessionDetailFromAgent(
+ workflowId: string,
+ agentId: string,
+ returnTo: SessionDetailReturnTo,
+ ): boolean {
+ const lookup = findWorkflowAgent(this.state.getSnapshot().workflowRuns, workflowId, agentId);
+ if (!lookup) return false;
+ if (!canOpenSessionHistory(lookup.agent)) {
+ return false;
+ }
+ this.openSessionDetail(
+ workflowId,
+ lookup.agent.name,
+ lookup.phase.id,
+ sessionNodeTypeOf(lookup.agent),
+ returnTo,
+ );
+ return true;
+ }
+
+ private aggregateSessionStatus(
+ members: WorkflowRun["phases"][number]["agents"],
+ ): WorkflowStatus {
+ let aggregateStatus: WorkflowStatus = "completed";
+ for (const member of members) {
+ if (member.status === "running") {
+ return "running";
+ }
+ if (member.status === "waiting_for_human") {
+ aggregateStatus = "waiting_for_human";
+ } else if (member.status === "failed" && aggregateStatus === "completed") {
+ aggregateStatus = "failed";
+ } else if (member.status !== "completed" && aggregateStatus === "completed") {
+ aggregateStatus = member.status;
+ }
+ }
+ return aggregateStatus;
+ }
+
+ /** Done turns for session parent progress (completed / failed / stopped). */
+ private sessionDoneCount(members: WorkflowRun["phases"][number]["agents"]): number {
+ return members.filter(
+ (member) =>
+ member.status === "completed" ||
+ member.status === "failed" ||
+ member.status === "stopped",
+ ).length;
+ }
+
+ private formatSessionProgress(members: WorkflowRun["phases"][number]["agents"]): string {
+ return `${this.sessionDoneCount(members)}/${this.sessionTotalCount(members)}`;
+ }
+
+ private formatWorkflowAgentFieldText(value: string): string {
+ try {
+ const parsed = JSON.parse(value);
+ return JSON.stringify(parsed, null, 2);
+ } catch {
+ return value;
+ }
+ }
+
+ private appendLabeledFullText(
+ lines: string[],
+ width: number,
+ label: string,
+ value?: string,
+ error = false,
+ ): void {
+ if (!value) return;
+ lines.push(
+ padToWidth(error ? palette.status.error(label) : palette.text.secondary(label), width),
+ );
+ const color = error ? palette.status.error : palette.text.secondary;
+ const display = this.formatWorkflowAgentFieldText(value);
+ lines.push(
+ ...wrapPlainText(display, width).map((line) => padToWidth(color(line), width)),
+ );
+ lines.push("");
+ }
+
+ /** Cached human turn — honest placeholder, not replayed journal text. */
+ private appendHumanTurnCachedPlaceholder(
+ lines: string[],
+ width: number,
+ label: string,
+ placeholder: string,
+ ): void {
+ lines.push(padToWidth(palette.text.secondary(label), width));
+ lines.push(padToWidth(palette.text.dim(placeholder), width));
+ lines.push("");
+ }
+
+ /** Human / human_session turn-detail action hint. */
+ private formatHumanAgentActionHint(
+ agent: WorkflowAgent,
+ options?: { tabReply?: boolean },
+ ): string {
+ const parts: string[] = [];
+ if (options?.tabReply) parts.push("Tab to reply");
+ if (canOpenSessionHistory(agent)) parts.push("s session history");
+ parts.push("press q to see full question");
+ if (agent.status !== "waiting_for_human") {
+ parts.push("a answer");
+ }
+ // Match agent / agent_session: always advertise e error (no-op when empty).
+ parts.push("e error");
+ return parts.join(" · ");
+ }
+
+ /** Agent / agent_session turn-detail action hint — mirrors human hint structure. */
+ private formatAgentAgentActionHint(agent: WorkflowAgent): string {
+ const parts: string[] = [];
+ if (canOpenSessionHistory(agent)) parts.push("s session history");
+ parts.push("press p to see full prompt");
+ parts.push("o outcome");
+ parts.push("e error");
+ return parts.join(" · ");
+ }
+
+ private formatSwarmSessionDetailFooterHint(
+ scrollHint: string,
+ options: { waiting?: boolean; composing?: boolean },
+ ): string {
+ const parts: string[] = [];
+ if (scrollHint) parts.push(scrollHint);
+ if (options.composing) {
+ parts.push("Enter submit");
+ } else if (options.waiting) {
+ parts.push("Tab to reply");
+ }
+ parts.push("r refresh");
+ parts.push("Esc/← back to agents");
+ return parts.join(" · ");
+ }
+
private renderSwarmWorkflowAgentRows(
agents: WorkflowRun["phases"][number]["agents"],
width: number,
maxRows = agents.length,
): string[] {
if (agents.length === 0) return [padToWidth(palette.text.dim("No agents"), width)];
- const visibleAgents = agents.slice(0, maxRows);
- const lines = visibleAgents.map((agent) =>
- padToWidth(
- ` ${formatWorkflowStatus(agent.status)} ${agent.name}${agent.model ? ` ${palette.text.dim(`· ${agent.model}`)}` : ""}`,
- width,
- ),
- );
- const hiddenCount = agents.length - visibleAgents.length;
- if (hiddenCount > 0) {
+
+ const { sessions, oneShots } = groupWorkflowAgentsByName(agents);
+
+ type DisplayGroup =
+ | { type: "session"; label: string; members: WorkflowRun["phases"][number]["agents"] }
+ | { type: "oneshot"; agent: WorkflowRun["phases"][number]["agents"][number] };
+
+ const displayGroups: DisplayGroup[] = [
+ ...sessions.map(({ label, members }) => ({ type: "session" as const, label, members })),
+ ...oneShots.map((agent) => ({ type: "oneshot" as const, agent })),
+ ];
+
+ const lines: string[] = [];
+ let renderedRows = 0;
+
+ for (const group of displayGroups) {
+ if (renderedRows >= maxRows) break;
+
+ if (group.type === "session") {
+ const { label, members } = group;
+ const firstMember = members[0];
+ const modelOrHuman = formatWorkflowAgentKindLabel(firstMember ?? {});
+
+ // Aggregate status: any running → ◐, any waiting → ☺, all completed → ✓
+ const aggregateStatus = this.aggregateSessionStatus(members);
+
+ const icon = workflowStatusIcon(aggregateStatus);
+ const statusColor =
+ aggregateStatus === "waiting_for_human"
+ ? palette.text.humanInput
+ : (s: string) => s;
+
+ // Session parent summary row (phases preview only)
+ lines.push(
+ padToWidth(
+ ` ${statusColor(icon)} ${label} ${palette.text.dim(`· ${this.formatSessionProgress(members)} · ${modelOrHuman}`)}`,
+ width,
+ ),
+ );
+ renderedRows++;
+
+ const hasActiveTurn = members.some(
+ (member) =>
+ member.status === "waiting_for_human" ||
+ member.status === "running" ||
+ member.status === "pending",
+ );
+ if (hasActiveTurn || renderedRows < maxRows) {
+ for (let i = 0; i < members.length && renderedRows < maxRows; i++) {
+ const member = members[i]!;
+ const turn = this.agentTurnNumber(member, i);
+ const isLast = i === members.length - 1;
+ const branch = isLast ? "└" : "├";
+ const turnIcon = workflowStatusIcon(member.status);
+ const turnStatusColor =
+ member.status === "waiting_for_human"
+ ? palette.text.humanInput
+ : (s: string) => s;
+ const statusWord = formatWorkflowStatusWord(member.status);
+ const cachedSuffix = isHumanTurnCached(member)
+ ? palette.text.dim(" · cached")
+ : "";
+
+ lines.push(
+ padToWidth(
+ ` ${palette.text.dim(branch)} ${turnStatusColor(turnIcon)} turn ${turn} ${palette.text.secondary(`· ${statusWord}`)}${cachedSuffix}`,
+ width,
+ ),
+ );
+ renderedRows++;
+ }
+ }
+ } else {
+ // Plain agent() / human() one-shot (session nodes always use the tree above)
+ const { agent } = group;
+ const icon = workflowStatusIcon(agent.status);
+ const label = formatWorkflowAgentKindLabel(agent);
+ const labelPart = label ? ` ${palette.text.secondary(`· ${label}`)}` : "";
+ const statusColor =
+ agent.status === "waiting_for_human"
+ ? palette.text.humanInput
+ : (s: string) => s;
+
+ lines.push(
+ padToWidth(
+ ` ${statusColor(icon)} ${agent.name}${labelPart}`,
+ width,
+ ),
+ );
+ renderedRows++;
+ }
+ }
+
+ const totalGroups = displayGroups.length;
+ const hiddenGroups = Math.max(0, totalGroups - displayGroups.slice(0, displayGroups.findIndex((_, i) => {
+ let count = 0;
+ for (let j = 0; j <= i; j++) {
+ const g = displayGroups[j];
+ if (!g) continue;
+ if (g.type === "oneshot") {
+ count++;
+ } else {
+ count++; // summary row
+ const hasWaiting = g.members.some(m => m.status === "waiting_for_human");
+ if (hasWaiting) {
+ count += g.members.length; // all turn sub-rows
+ }
+ }
+ }
+ return count >= maxRows;
+ }) + 1).length);
+
+ if (renderedRows >= maxRows && hiddenGroups > 0) {
lines.push(
padToWidth(
- palette.text.dim(` ... ${hiddenCount} more agents - Tab/Right to browse`),
+ palette.text.dim(` ... ${hiddenGroups} more - Enter/→ show agents`),
width,
),
);
}
+
+ return lines;
+ }
+
+ private buildSessionDetailLines(
+ state: Extract<SwarmWorkflowsViewState, { phase: "session-detail" }>,
+ width: number,
+ ): string[] {
+ const workflow = this.state.getSnapshot().workflowRuns.find((w) => w.id === state.workflowId);
+ if (!workflow) return [padToWidth(palette.status.error("Workflow not found"), width)];
+
+ const phase = workflow.phases.find((item) => item.id === state.phaseId);
+
+ const sessionAgents = sessionMembersInPhase(
+ phase?.agents ?? [],
+ state.sessionLabel,
+ state.nodeType,
+ ).map((agent) => ({ agent }));
+
+ if (sessionAgents.length === 0) {
+ return [padToWidth(palette.status.error("Session not found"), width)];
+ }
+
+ const firstAgent = sessionAgents[0]!.agent;
+ const isHumanSession =
+ state.nodeType === "human_session" ||
+ firstAgent.node_type === "human_session" ||
+ (firstAgent.node_type === undefined && firstAgent.kind === "human");
+ const sessionType =
+ state.nodeType === "human_session" || state.nodeType === "agent_session"
+ ? state.nodeType
+ : isHumanSession
+ ? "human_session"
+ : "agent_session";
+ const phaseName = phase?.name ?? state.phaseId;
+ const aggregateStatus = this.aggregateSessionStatus(sessionAgents.map(({ agent }) => agent));
+
+ const divider = padToWidth(palette.text.dim("─".repeat(Math.max(1, width))), width);
+
+ const headerLines: string[] = [
+ padToWidth(palette.text.accent(`${state.sessionLabel} · ${phaseName}`), width),
+ padToWidth(
+ palette.text.dim(
+ `${workflow.name} · ${sessionType} · ${formatWorkflowStatus(aggregateStatus)} · ${this.formatSessionProgress(sessionAgents.map(({ agent }) => agent))} turns`,
+ ),
+ width,
+ ),
+ divider,
+ "",
+ ];
+
+ const bodyLines: string[] = [];
+ const memberAgents = sessionAgents.map(({ agent }) => agent);
+ for (let i = 0; i < sessionAgents.length; i++) {
+ const { agent } = sessionAgents[i]!;
+ const turn = this.agentTurnNumber(agent, i);
+ const turnLabel = `Turn ${turn}`;
+ const isWaiting = agent.status === "waiting_for_human";
+ const isRunning = agent.status === "running";
+ const duration = formatWorkflowDuration(agent.duration_ms);
+
+ let turnHeader: string;
+ if (isWaiting) {
+ turnHeader = `${turnLabel} ${palette.text.humanInput(`${workflowStatusIcon("waiting_for_human")} waiting`)}`;
+ } else if (isRunning) {
+ turnHeader = `${turnLabel} ${palette.text.dim(`◐ ${agent.status}`)}`;
+ } else if (agent.status === "completed") {
+ turnHeader = `${turnLabel} ${palette.text.dim("✓ completed")}`;
+ } else {
+ turnHeader = `${turnLabel} ${palette.status.error(workflowStatusIcon(agent.status))} ${palette.text.dim(agent.status)}`;
+ }
+ bodyLines.push(padToWidth(turnHeader, width));
+ if (duration) {
+ bodyLines.push(padToWidth(palette.text.dim(` duration ${duration}`), width));
+ }
+ bodyLines.push("");
+
+ if (isHumanSession) {
+ if (isHumanTurnCached(agent)) {
+ this.appendHumanTurnCachedPlaceholder(
+ bodyLines,
+ width,
+ "Question",
+ HUMAN_TURN_CACHED_QUESTION,
+ );
+ if (!isRunning && !isWaiting) {
+ this.appendHumanTurnCachedPlaceholder(
+ bodyLines,
+ width,
+ "Answer",
+ HUMAN_TURN_CACHED_ANSWER,
+ );
+ }
+ } else {
+ this.appendLabeledFullText(
+ bodyLines,
+ width,
+ "Question",
+ this.getHumanQuestionText(state.workflowId, agent.id),
+ );
+ if (isWaiting) {
+ bodyLines.push(padToWidth(palette.text.secondary("Answer"), width));
+ if (this.replyingToHumanPrompt) {
+ bodyLines.push(padToWidth(palette.text.dim(" (composing reply below)"), width));
+ } else {
+ bodyLines.push(padToWidth(palette.text.dim(" (waiting for reply)"), width));
+ }
+ bodyLines.push("");
+ } else if (!isRunning) {
+ this.appendLabeledFullText(bodyLines, width, "Answer", agent.human_reply);
+ }
+ }
+ // Always surface Error when present (e.g. timeout → failed), same as agent_session.
+ this.appendLabeledFullText(bodyLines, width, "Error", agent.error, true);
+ } else {
+ this.appendLabeledFullText(bodyLines, width, "Prompt", agent.prompt);
+ if (agent.activity?.length) {
+ bodyLines.push(padToWidth(palette.text.secondary("Activity"), width));
+ for (const item of agent.activity) {
+ const prefix = item.type ? `${item.type}: ` : "";
+ bodyLines.push(
+ ...wrapPlainText(`- ${prefix}${item.content}`, width).map((line) =>
+ padToWidth(palette.text.dim(line), width),
+ ),
+ );
+ }
+ bodyLines.push("");
+ }
+ if (isRunning) {
+ bodyLines.push(padToWidth(palette.text.secondary("Outcome"), width));
+ bodyLines.push(padToWidth(palette.text.dim(" (running...)"), width));
+ bodyLines.push("");
+ } else {
+ this.appendLabeledFullText(bodyLines, width, "Outcome", agent.outcome);
+ }
+ // Show Error whenever set — not only after the turn leaves running.
+ this.appendLabeledFullText(bodyLines, width, "Error", agent.error, true);
+ }
+
+ if (i < sessionAgents.length - 1) {
+ bodyLines.push(divider);
+ bodyLines.push("");
+ }
+ }
+
+ // Windowed viewport: header/footer stay fixed, body scrolls.
+ // The layout pins questionLines to the top and drops overflow, so we clamp
+ // the panel to the terminal height ourselves and window the body region.
+ const bodyViewport = this.sessionDetailBodyViewport(headerLines.length);
+ const maxScroll = Math.max(0, bodyLines.length - bodyViewport);
+ const scrollOffset = Math.min(Math.max(0, state.scrollOffset), maxScroll);
+ state.scrollOffset = scrollOffset;
+ const canScroll = bodyLines.length > bodyViewport;
+ const visibleBody = canScroll
+ ? bodyLines.slice(scrollOffset, scrollOffset + bodyViewport)
+ : bodyLines;
+
+ const lines: string[] = [...headerLines];
+ if (canScroll && scrollOffset > 0) {
+ lines.push(padToWidth(palette.text.dim(` ↑ ${scrollOffset} more lines above`), width));
+ }
+ lines.push(...visibleBody);
+ const belowCount = bodyLines.length - (scrollOffset + visibleBody.length);
+ if (canScroll && belowCount > 0) {
+ lines.push(padToWidth(palette.text.dim(` ↓ ${belowCount} more lines below`), width));
+ }
+
+ const scrollHint = canScroll ? "↑/↓ scroll · PgUp/PgDn page" : "";
+ const waitingAgent = sessionAgents.find(({ agent }) => agent.status === "waiting_for_human");
+ lines.push(
+ padToWidth(
+ palette.text.secondary(
+ this.formatSwarmSessionDetailFooterHint(scrollHint, {
+ waiting: Boolean(waitingAgent) && !this.replyingToHumanPrompt,
+ composing: Boolean(waitingAgent) && Boolean(this.replyingToHumanPrompt),
+ }),
+ ),
+ width,
+ ),
+ );
+
return lines;
}
+ /** Rows of session-detail body visible per page, mirrors buildSessionDetailLines. */
+ private sessionDetailBodyViewport(headerRows: number): number {
+ const reservedChrome = (this.replyingToHumanPrompt ? 4 : 0) + 6;
+ const maxPanelRows = Math.max(8, this.tui.terminal.rows - reservedChrome);
+ // Reserve 3 rows for the two scroll indicators plus the footer hint.
+ return Math.max(3, maxPanelRows - headerRows - 3);
+ }
+
private buildSwarmWorkflowAgentLines(
state: Extract<SwarmWorkflowsViewState, { phase: "agent" }>,
width: number,
@@ -5598,37 +7115,91 @@ export class AppScreen implements Component, Focusable {
if (!lookup) return [padToWidth(palette.status.error("Agent not found"), width)];
const { workflow, phase, agent } = lookup;
const duration = formatWorkflowDuration(agent.duration_ms);
+ const isHuman = agent.kind === "human";
+ const kindLabel = formatWorkflowAgentKindLabel(agent);
+
+ const statusStr = isHuman
+ ? `${workflowStatusTone(agent.status)(`${workflowStatusIcon(agent.status)} ${agent.status}`)} · ${kindLabel}`
+ : `${workflowStatusTone(agent.status)(`${workflowStatusIcon(agent.status)} ${agent.status}`)}${agent.model ? ` · ${palette.text.secondary(agent.model)}` : ""}`;
+
+ const turnNumber = sessionTurnLabelNumber(agent, phase.agents ?? []);
+ const titleLine = turnNumber !== null ? `${agent.name} · turn ${turnNumber}` : agent.name;
+
const lines: string[] = [
- padToWidth(palette.text.accent(agent.name), width),
+ padToWidth(palette.text.accent(titleLine), width),
padToWidth(palette.text.dim(`${workflow.name} · ${phase.name}`), width),
- padToWidth(
- `${formatWorkflowStatus(agent.status)}${agent.model ? ` ${palette.text.dim(`· ${agent.model}`)}` : ""}`,
- width,
- ),
+ padToWidth(statusStr, width),
"",
];
if (duration) {
lines.splice(3, 0, padToWidth(palette.text.dim(`duration ${duration}`), width));
}
- this.appendLabeledWrappedPreview(lines, width, "Prompt", agent.prompt, "p");
- if (agent.activity?.length) {
- lines.push(padToWidth(palette.text.secondary("Activity"), width));
- for (const item of agent.activity) {
- const prefix = item.type ? `${item.type}: ` : "";
+
+ // Show full details for current turn
+ if (isHuman) {
+ if (isHumanTurnCached(agent)) {
+ this.appendHumanTurnCachedPlaceholder(
+ lines,
+ width,
+ "Question",
+ HUMAN_TURN_CACHED_QUESTION,
+ );
+ this.appendHumanTurnCachedPlaceholder(lines, width, "Answer", HUMAN_TURN_CACHED_ANSWER);
+ this.appendLabeledWrappedPreview(lines, width, "Error", agent.error, "e", true);
lines.push(
- ...wrapPlainText(`- ${prefix}${item.content}`, width).map((line) =>
- padToWidth(palette.text.dim(line), width),
+ padToWidth(
+ palette.text.secondary(this.formatHumanAgentActionHint(agent)),
+ width,
+ ),
+ );
+ } else {
+ this.appendLabeledWrappedPreview(lines, width, "Question", agent.human_prompt || this.getHumanQuestionText(state.workflowId, state.agentId), "q");
+ if (agent.status === "waiting_for_human") {
+ lines.push(padToWidth(palette.text.secondary("Answer"), width));
+ lines.push(padToWidth(palette.text.secondary(" (waiting for reply)"), width));
+ lines.push("");
+ } else {
+ this.appendLabeledWrappedPreview(lines, width, "Answer", agent.human_reply, "a");
+ }
+ this.appendLabeledWrappedPreview(lines, width, "Error", agent.error, "e", true);
+ lines.push(
+ padToWidth(
+ palette.text.secondary(
+ this.formatHumanAgentActionHint(agent, {
+ tabReply: agent.status === "waiting_for_human",
+ }),
+ ),
+ width,
),
);
}
- lines.push("");
+ } else {
+ // Agent / agent_session: Prompt + Outcome + Error + Activity
+ this.appendLabeledWrappedPreview(lines, width, "Prompt", agent.prompt, "p");
+ if (agent.activity?.length) {
+ lines.push(padToWidth(palette.text.secondary("Activity"), width));
+ for (const item of agent.activity) {
+ const prefix = item.type ? `${item.type}: ` : "";
+ lines.push(
+ ...wrapPlainText(`- ${prefix}${item.content}`, width).map((line) =>
+ padToWidth(palette.text.dim(line), width),
+ ),
+ );
+ }
+ lines.push("");
+ }
+ this.appendLabeledWrappedPreview(lines, width, "Outcome", agent.outcome, "o");
+ this.appendLabeledWrappedPreview(lines, width, "Error", agent.error, "e", true);
+ lines.push(
+ padToWidth(palette.text.secondary(this.formatAgentAgentActionHint(agent)), width),
+ );
}
- this.appendLabeledWrappedPreview(lines, width, "Outcome", agent.outcome, "o");
- this.appendLabeledWrappedPreview(lines, width, "Error", agent.error, "e", true);
- lines.push(
- padToWidth(palette.text.dim("press p to see full prompt - o outcome - e error"), width),
- );
- lines.push(padToWidth(palette.text.dim("Esc/← back"), width));
+
+ const backHint =
+ state.returnTo?.kind === "pending-list"
+ ? "Esc/← back to pending list"
+ : "Esc/← back to agents";
+ lines.push(padToWidth(palette.text.secondary(backHint), width));
return lines;
}
@@ -5644,7 +7215,7 @@ export class AppScreen implements Component, Focusable {
lines.push(
padToWidth(error ? palette.status.error(label) : palette.text.secondary(label), width),
);
- const color = error ? palette.status.error : palette.text.dim;
+ const color = error ? palette.status.error : palette.text.secondary;
const wrapped = wrapPlainText(value, width);
const visible = wrapped.slice(0, SWARM_WORKFLOW_AGENT_TEXT_PREVIEW_ROWS);
lines.push(...visible.map((line) => padToWidth(color(line), width)));
@@ -7534,4 +9105,82 @@ export class AppScreen implements Component, Focusable {
this.editor.setText("");
}
}
+
+ /**
+ * Handle keyboard input when the user is replying to a swarmflow human-session turn.
+ * Enter submits; Esc cancels without sending.
+ */
+ private handleSwarmflowHumanReplyInput(data: string): boolean {
+ if (!this.replyingToHumanPrompt) return false;
+
+ if (matchesKey(data, "escape")) {
+ this.replyingToHumanPrompt = null;
+ this.editor.setText("");
+ this.editor.focused = false;
+ return true;
+ }
+
+ if (matchesKey(data, "return") || matchesKey(data, "enter")) {
+ const answer = this.editor.getText().trim();
+ if (!answer) return true; // block empty submit
+ const { workflowRunId, correlationId } = this.replyingToHumanPrompt;
+ const snapshot = this.state.getSnapshot();
+ this.state.sendEventOnly("chat.swarmflow_reply", {
+ session_id: snapshot.sessionId,
+ run_id: workflowRunId,
+ correlation_id: correlationId,
+ answer,
+ });
+ this.replyingToHumanPrompt = null;
+ this.editor.setText("");
+ this.editor.focused = false;
+ return true;
+ }
+
+ this.editor.handleInput(data);
+ return true;
+ }
+
+ private findAgentIdForHumanReply(workflowId: string, correlationId: string): string {
+ const workflow = this.state.getSnapshot().workflowRuns.find((item) => item.id === workflowId);
+ if (!workflow) return correlationId;
+ for (const phase of workflow.phases ?? []) {
+ for (const agent of phase.agents ?? []) {
+ if (agent.id === correlationId) return agent.id;
+ if ((agent.correlation_id ?? agent.id) === correlationId) return agent.id;
+ }
+ }
+ return correlationId;
+ }
+
+ /** Build the reply input banner shown when `replyingToHumanPrompt` is set. */
+ private buildSwarmflowHumanReplyInputLines(width: number): string[] {
+ if (!this.replyingToHumanPrompt) return [];
+ const { label, turn, workflowRunId, correlationId, isSession } = this.replyingToHumanPrompt;
+ const agentId = this.findAgentIdForHumanReply(workflowRunId, correlationId);
+ const question = this.getHumanQuestionText(workflowRunId, agentId);
+ const header = isSession ? `Reply to ${label} · turn ${turn}` : `Reply to ${label}`;
+ const lines = [padToWidth(palette.text.humanInput(header), width)];
+ if (question) {
+ lines.push(padToWidth(palette.text.secondary("Question"), width));
+ const { lines: previewLines, truncated } = prepareHumanQuestionPreviewLines(
+ question,
+ width,
+ 6,
+ );
+ for (const qLine of previewLines) {
+ lines.push(padToWidth(palette.text.dim(` ${qLine}`), width));
+ }
+ if (truncated) {
+ lines.push(padToWidth(palette.text.dim(" …"), width));
+ }
+ lines.push("");
+ }
+ lines.push(
+ padToWidth(palette.text.secondary("Your answer"), width),
+ ...this.editor.render(width),
+ padToWidth(palette.text.dim("Enter submit · Esc cancel"), width),
+ );
+ return lines;
+ }
}
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts b/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts
index c94de4abb2..f3cf4a560d 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts
@@ -36,6 +36,8 @@ export interface ScreenLayoutOptions {
btwOverlayIndex?: number;
/** btw 历史总数 */
btwOverlayTotal?: number;
+ /** 替换 transcript 区域的 overlay 内容(如 chat 内 H 打开的 pending 面板) */
+ overlayTranscriptLines?: string[];
}
function formatSubtaskStatus(status: string): string {
@@ -319,15 +321,17 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout
// "Working" animation always stays at the screen bottom for visual prominence.
const effectiveStatusLines = statusLines;
- const transcriptLines = buildTranscriptLines(
- snapshot,
- options.width,
- options.showFullThinking,
- options.showToolDetails,
- options.animationPhase,
- options.pendingInput,
- options.pendingInputBaseline,
- );
+ const transcriptLines =
+ options.overlayTranscriptLines ??
+ buildTranscriptLines(
+ snapshot,
+ options.width,
+ options.showFullThinking,
+ options.showToolDetails,
+ options.animationPhase,
+ options.pendingInput,
+ options.pendingInputBaseline,
+ );
const todoLines = renderTodoList(snapshot.todos, options.width, options.todosCollapsed, options.animationPhase);
const hasTeamActivity =
isTeamMode(snapshot.mode) ||
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/theme.ts b/jiuwenswarm/channels/tui/frontend/src/ui/theme.ts
index e8d4e5c018..d2189c29f8 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/theme.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/theme.ts
@@ -53,6 +53,7 @@ type ThemeDefinition = {
textUser: string;
textAssistant: string;
textThinking: string;
+ textHumanInput: string;
textSystem: string;
textInfo: string;
textTool: string;
@@ -85,6 +86,7 @@ const THEME_DEFINITIONS: Record<"light" | "dark", ThemeDefinition> = {
textUser: "#2563eb",
textAssistant: "#d0d0d0",
textThinking: "#966c1e",
+ textHumanInput: "#0d9488",
textSystem: "#666666",
textInfo: "#5769f7",
textTool: "#5769f7",
@@ -93,7 +95,7 @@ const THEME_DEFINITIONS: Record<"light" | "dark", ThemeDefinition> = {
statusWarning: "#966c1e",
statusInfo: "#5769f7",
borderPanel: "#999999",
- borderQuestion: "#966c1e",
+ borderQuestion: "#0d9488",
surfaceUserBg: "#f0f0f0",
surfaceUserFg: "#000000",
markdownHeading: "#d77757",
@@ -115,6 +117,7 @@ const THEME_DEFINITIONS: Record<"light" | "dark", ThemeDefinition> = {
textUser: "#7ab4e8",
textAssistant: "#ffffff",
textThinking: "#ffc107",
+ textHumanInput: "#2dd4bf",
textSystem: "#999999",
textInfo: "#b1b9f9",
textTool: "#b1b9f9",
@@ -123,7 +126,7 @@ const THEME_DEFINITIONS: Record<"light" | "dark", ThemeDefinition> = {
statusWarning: "#ffc107",
statusInfo: "#b1b9f9",
borderPanel: "#888888",
- borderQuestion: "#ffc107",
+ borderQuestion: "#2dd4bf",
surfaceUserBg: "#373737",
surfaceUserFg: "#ffffff",
markdownHeading: "#d77757",
@@ -233,6 +236,7 @@ export const palette = {
user: (value: string) => chalk.hex(getThemeDefinition().textUser)(value),
assistant: (value: string) => chalk.hex(getThemeDefinition().textAssistant)(value),
thinking: (value: string) => chalk.hex(getThemeDefinition().textThinking)(value),
+ humanInput: (value: string) => chalk.hex(getThemeDefinition().textHumanInput)(value),
system: (value: string) => chalk.hex(getThemeDefinition().textSystem)(value),
info: (value: string) => chalk.hex(getThemeDefinition().textInfo)(value),
tool: (value: string) => chalk.hex(getThemeDefinition().textTool)(value),
diff --git a/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs b/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs
index 795b790ed4..5da43d8869 100644
--- a/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs
+++ b/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs
@@ -11,6 +11,15 @@ import {
shouldAppendPlanRejectFeedback,
shouldCollectPlanRejectFeedback,
} from "../dist/ui/app-screen.js";
+import { planSwarmflowToggle } from "../dist/core/commands/builtins/swarmflow.js";
+import {
+ canOpenSessionHistory,
+ groupWorkflowAgentsByName,
+ isSessionNode,
+ shouldShowSessionTree,
+ shouldShowTurnInDetailOrReply,
+ sessionTurnLabelNumber,
+} from "../dist/core/workflows.js";
import { CommandKind } from "../dist/core/commands/types.js";
const planQuestion = "**Plan Approval**\n\nThe agent has completed a plan.";
@@ -154,4 +163,109 @@ assert.equal(pendingQuestionExitCount, 0);
assert.ok(pendingQuestionInterruptCount === 2 && pendingQuestionExitCount === 0);
console.log("ctrl+d render requests:", pendingQuestionRenderCount - renderCountBeforeCtrlD);
+const agent = (name, node_type, correlation_id, id = `${name}-${node_type ?? "plain"}-${correlation_id ?? "none"}`) => ({
+ id,
+ name,
+ status: "completed",
+ node_type,
+ correlation_id,
+});
+
+assert.equal(isSessionNode({ node_type: "agent_session" }), true);
+assert.equal(isSessionNode({ node_type: "human_session" }), true);
+assert.equal(isSessionNode({ node_type: "agent" }), false);
+assert.equal(isSessionNode({ node_type: "human" }), false);
+assert.equal(canOpenSessionHistory({ node_type: "agent_session" }), true);
+assert.equal(canOpenSessionHistory({ node_type: "human_session" }), true);
+assert.equal(canOpenSessionHistory({ node_type: "human", correlation_id: "p:h:0" }), false);
+assert.equal(canOpenSessionHistory({ node_type: "agent" }), false);
+assert.equal(canOpenSessionHistory({}), false);
+
+const grouped = groupWorkflowAgentsByName([
+ agent("coder", "agent", undefined),
+ agent("coder", "agent", undefined),
+ agent("review", "agent_session", "p:review:0"),
+ agent("review", "agent_session", "p:review:1"),
+ agent("host", "human", "p:host:0"),
+]);
+assert.equal(grouped.oneShots.length, 3);
+assert.equal(grouped.sessions.length, 1);
+assert.equal(grouped.sessions[0]?.label, "review");
+assert.equal(grouped.sessions[0]?.members.length, 2);
+
+// one-shot human() carries a real correlation_id but is NOT a session node.
+assert.equal(isSessionNode(agent("host", "human", "p:host:0")), false);
+assert.equal(isSessionNode(agent("review", "agent_session", "p:review:0")), true);
+assert.equal(shouldShowTurnInDetailOrReply(agent("host", "human", "p:host:0")), false);
+assert.equal(shouldShowTurnInDetailOrReply(agent("review", "agent_session", "p:review:0")), true);
+assert.equal(
+ shouldShowSessionTree(agent("review", "agent_session", "p:review:0"), [
+ agent("review", "agent_session", "p:review:0"),
+ ]),
+ true,
+);
+const multiTurnPhase = [
+ agent("review", "agent_session", "p:review:0"),
+ agent("review", "agent_session", "p:review:1"),
+];
+assert.equal(shouldShowSessionTree(agent("review", "agent_session", "p:review:0"), multiTurnPhase), true);
+assert.equal(sessionTurnLabelNumber(agent("host", "human", "p:host:0"), []), null);
+assert.equal(sessionTurnLabelNumber(agent("review", "agent_session", "p:review:0"), [
+ agent("review", "agent_session", "p:review:0"),
+]), 0);
+assert.equal(sessionTurnLabelNumber(agent("review", "agent_session", "p:review:1"), multiTurnPhase), 1);
+
+// Single-turn session still forms a tree (parent + turn 0) — distinct from human()/agent().
+const singleSessionGrouped = groupWorkflowAgentsByName([
+ agent("solo", "human_session", "p:solo:0"),
+ agent("plain", "human", "p:plain:0"),
+]);
+assert.equal(singleSessionGrouped.sessions.length, 1);
+assert.equal(singleSessionGrouped.sessions[0]?.label, "solo");
+assert.equal(singleSessionGrouped.sessions[0]?.members.length, 1);
+assert.equal(singleSessionGrouped.oneShots.length, 1);
+assert.equal(singleSessionGrouped.oneShots[0]?.name, "plain");
+assert.equal(
+ sessionTurnLabelNumber(agent("solo", "human_session", "p:solo:0"), [
+ agent("solo", "human_session", "p:solo:0"),
+ ]),
+ 0,
+);
+assert.equal(
+ sessionTurnLabelNumber(agent("plain", "human", "p:plain:0"), [
+ agent("plain", "human", "p:plain:0"),
+ ]),
+ null,
+);
+
+assert.deepEqual(
+ planSwarmflowToggle({ target: "on", currentEnabled: true, mode: "team" }),
+ {
+ writeConfig: false,
+ switchToTeam: false,
+ message: "SwarmFlow is already on in team mode. No changes were made.",
+ },
+);
+assert.deepEqual(
+ planSwarmflowToggle({ target: "on", currentEnabled: true, mode: "code.normal" }),
+ {
+ writeConfig: false,
+ switchToTeam: true,
+ message:
+ "SwarmFlow is already on. Switched to team mode — the next workflow run uses the enabled setting.",
+ },
+);
+assert.deepEqual(
+ planSwarmflowToggle({ target: "off", currentEnabled: false, mode: "team" }),
+ {
+ writeConfig: false,
+ switchToTeam: false,
+ message: "SwarmFlow is already off. Mode remains team. No changes were made.",
+ },
+);
+assert.equal(
+ planSwarmflowToggle({ target: "on", currentEnabled: false, mode: "team" }).writeConfig,
+ true,
+);
+
console.log("frontend tests passed");
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 64e7c7c9e7..909c34048d 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -15,6 +15,7 @@ class ReqMethod(Enum):
CHAT_RESUME = "chat.resume"
CHAT_CANCEL = "chat.interrupt"
CHAT_ANSWER = "chat.user_answer"
+ CHAT_SWARMFLOW_REPLY = "chat.swarmflow_reply"
HISTORY_GET = "history.get"
COMMAND_BTW = "command.btw"
COMMAND_ADD_DIR = "command.add_dir"
diff --git a/jiuwenswarm/common/schema/swarmflow_reply.py b/jiuwenswarm/common/schema/swarmflow_reply.py
new file mode 100644
index 0000000000..ca4c9199be
--- /dev/null
+++ b/jiuwenswarm/common/schema/swarmflow_reply.py
@@ -0,0 +1,31 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""chat.swarmflow_reply 参数契约。
+
+真人回复 swarmflow human_session 轮次的入站参数结构。回复经标准三层路由链
+(TUI 空壳 ack → message_handler 转发 → process_message 分派)到达
+``handle_swarmflow_reply``,由其构造 ``HumanAgentMessage(target="swarmflow:<run_id>:<corr>")``
+交 ``TeamManager.interact`` 走 agent-core 薄路由。
+"""
+
+from typing import TypedDict
+
+
+class SwarmflowReplyParams(TypedDict, total=False):
+ """chat.swarmflow_reply 参数契约(TypedDict,供类型标注与文档)。"""
+
+ session_id: str
+ """团队 session_id(handler 据此定位 team runtime)。"""
+
+ team_name: str
+ """团队名。仅日志/调试用,handler 不消费——``TeamManager.interact`` 内部
+ 用 ``get_active_team_name(session_id)`` 解析。"""
+
+ run_id: str
+ """workflow run id。构造 run-scoped reply topic,使并发 run 互不串扰。"""
+
+ correlation_id: str
+ """人机轮次关联号 ``{phase}:{label}:{turn}``,跨 resume 稳定。"""
+
+ answer: str
+ """真人原始回复正文。"""
diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
index 1645e2e25b..576745fffa 100644
--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py
@@ -33,6 +33,7 @@ from jiuwenswarm.common.config import (
update_permissions_enabled_in_config,
get_model_names,
update_preferred_language_in_config,
+ update_swarmflow_enabled_in_config,
update_config,
)
from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargs
@@ -212,6 +213,7 @@ CLI_FORWARD_REQ_METHODS = frozenset(
"chat.interrupt",
"chat.resume",
"chat.user_answer",
+ "chat.swarmflow_reply",
"history.get",
"browser.start",
"skills.marketplace.list",
@@ -470,6 +472,7 @@ _CLI_CONFIG_YAML_SETTERS: dict[str, Any] = {
"permissions_enabled": update_permissions_enabled_in_config,
"memory_forbidden_enabled": update_memory_forbidden_enabled_in_config,
"preferred_language": update_preferred_language_in_config,
+ "enable_swarmflow": update_swarmflow_enabled_in_config,
# Auto-Harness config items (stored in ~/.jiuwenswarm/auto-harness/config.yaml)
# 用户名同时设置 git.user_name, fork_owner, gitcode.username(三者合一)
"auto_harness_git_user_name": _update_auto_harness_git_user_name,
@@ -731,6 +734,11 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
payload["auto_recap_enabled"] = (
"true" if auto_recap_cfg.get("enabled", True) else "false"
)
+ # swarmflow toggle lives at modes.team.jiuwen_team.enable_swarmflow
+ _team_cfg = (raw.get("modes") or {}).get("team") or {}
+ _jiuwen_team_cfg = _team_cfg.get("jiuwen_team") or {}
+ _swarmflow_enabled = bool(_jiuwen_team_cfg.get("enable_swarmflow", False))
+ payload["enable_swarmflow"] = "true" if _swarmflow_enabled else "false"
# Resolve model-related fields from config.yaml.
# When models.defaults list is in use, it is the canonical source
@@ -2109,6 +2117,13 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
payload["request_id"] = request_id
await channel.send_response(ws, req_id, ok=True, payload=payload)
+ async def _chat_swarmflow_reply(ws, req_id, params, session_id):
+ # Empty-ack shell — standard 3-layer routing forwards the reply to the
+ # agent adapter, which builds HumanAgentMessage and calls team_manager.
+ await channel.send_response(
+ ws, req_id, ok=True, payload={"accepted": True, "session_id": session_id}
+ )
+
async def _history_get(ws, req_id, params, session_id):
payload = {"accepted": True, "session_id": session_id}
if isinstance(params, dict):
@@ -2818,6 +2833,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
channel.register_local_handler(path, "chat.interrupt", _chat_interrupt)
channel.register_local_handler(path, "tui.disconnect", _tui_disconnect_request)
channel.register_local_handler(path, "chat.user_answer", _chat_user_answer)
+ channel.register_local_handler(path, "chat.swarmflow_reply", _chat_swarmflow_reply)
channel.register_local_handler(path, "history.get", _history_get)
channel.register_local_handler(path, "command.model", _command_model)
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.py
index 0f937feea1..1e77a3b521 100644
--- a/jiuwenswarm/gateway/message_handler/message_handler.py
+++ b/jiuwenswarm/gateway/message_handler/message_handler.py
@@ -3306,6 +3306,15 @@ class MessageHandler(ABC):
)
continue
+ if msg.req_method == ReqMethod.CHAT_SWARMFLOW_REPLY:
+ # Forward a swarmflow human reply to the agent adapter
+ # (non-stream). Unlike CHAT_ANSWER, no evolution-approval
+ # machinery; unlike CHAT_SEND, no cancel-existing-stream.
+ agent_msg = await self._prepare_agent_dispatch_message(msg)
+ env = self.message_to_e2a(agent_msg)
+ await self._process_non_stream_request(msg, env)
+ continue
+
if msg.req_method == ReqMethod.CHAT_CANCEL:
logger.info(
"[MessageHandler] 收到中断请求: id=%s channel_id=%s",
diff --git a/jiuwenswarm/gateway/routing/agent_request_timeout.py b/jiuwenswarm/gateway/routing/agent_request_timeout.py
index f73be809b4..fe65eff050 100644
--- a/jiuwenswarm/gateway/routing/agent_request_timeout.py
+++ b/jiuwenswarm/gateway/routing/agent_request_timeout.py
@@ -19,6 +19,20 @@ _TUI_EXTENDED_UNARY_METHOD_PREFIXES = (
"permissions.tools.",
"permissions.rules.",
)
+# Snapshot RPCs that may wait behind a busy TUI outbound writer (workflow.updated
+# / chat stream). Prefer the 55s window when the client does not pass timeout_ms,
+# so Gateway does not cut them at the default 25s.
+_TUI_EXTENDED_UNARY_METHODS = frozenset({
+ "command.workflows",
+})
+# Methods exempt from the TUI unary cap — they are long-lived by design and
+# must not be cut by the gateway-side 25s/55s limit. A swarmflow human reply
+# is an async deliver (thin-route publish to wake a pending future) whose
+# latency tracks the human-turn timeout (agent-core default 600s); capping it
+# at 55s aborts legitimate replies while the person is still typing.
+_TUI_UNARY_TIMEOUT_EXEMPT_METHODS = frozenset({
+ "chat.swarmflow_reply",
+})
class AgentRequestTimeoutError(TimeoutError):
@@ -55,17 +69,29 @@ def resolve_agent_request_timeout_seconds(
if is_stream or channel_id != _TUI_CHANNEL_ID:
return None
+ # Exempt long-lived methods (e.g. chat.swarmflow_reply whose latency tracks
+ # the human-turn timeout) from the TUI unary cap.
+ method_value = str(method or "")
+ if method_value in _TUI_UNARY_TIMEOUT_EXEMPT_METHODS:
+ return None
+
parsed_client_timeout_ms = coerce_client_timeout_ms(client_timeout_ms)
if parsed_client_timeout_ms is not None:
client_timeout_seconds = parsed_client_timeout_ms / 1000.0
- timeout_seconds = max(
- 1.0,
- client_timeout_seconds - _TUI_CLIENT_TIMEOUT_GRACE_SECONDS,
+ # Snapshot RPCs often wait behind a busy outbound writer; keep most of
+ # the client window instead of cutting a flat 5s (10s client → 5s wait).
+ grace = (
+ 2.0
+ if method_value in _TUI_EXTENDED_UNARY_METHODS
+ else _TUI_CLIENT_TIMEOUT_GRACE_SECONDS
)
+ timeout_seconds = max(1.0, client_timeout_seconds - grace)
return min(timeout_seconds, _TUI_MAX_UNARY_TIMEOUT_SECONDS)
- method_value = str(method or "")
- if method_value.startswith(_TUI_EXTENDED_UNARY_METHOD_PREFIXES):
+ if (
+ method_value.startswith(_TUI_EXTENDED_UNARY_METHOD_PREFIXES)
+ or method_value in _TUI_EXTENDED_UNARY_METHODS
+ ):
return _TUI_MAX_UNARY_TIMEOUT_SECONDS
return _TUI_DEFAULT_UNARY_TIMEOUT_SECONDS
diff --git a/jiuwenswarm/gateway/routing/base_ws_channel.py b/jiuwenswarm/gateway/routing/base_ws_channel.py
index 0940d22ae9..90ae61c67a 100644
--- a/jiuwenswarm/gateway/routing/base_ws_channel.py
+++ b/jiuwenswarm/gateway/routing/base_ws_channel.py
@@ -246,11 +246,15 @@ class BaseWsChannel(BaseChannel):
try:
await asyncio.wait_for(ws.send(frame), timeout=10.0)
except asyncio.TimeoutError:
+ # Drop only this frame. Killing the writer leaves an unbounded
+ # queue with nobody draining it — later unary res frames
+ # (e.g. command.workflows list) never reach the TUI and the
+ # client reports ``request timeout`` despite AgentServer OK.
logger.warning(
- "[%s] ws.send timed out 10s, dropping writer ws_id=%s",
+ "[%s] ws.send timed out 10s, dropping frame ws_id=%s",
self.channel_id, ws_id,
)
- return
+ continue
except Exception as e:
if bool(getattr(ws, "closed", False)):
logger.debug(
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index c2b2b66eb5..024fd6a3ff 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -1087,6 +1087,17 @@ modes:
spawn_mode: inprocess
enable_swarmflow: false
+ # SwarmFlow per-Leader concurrency caps (three-layer governor).
+ # Only effective when enable_swarmflow is true.
+ # max_workflows: L1 — max concurrent workflow runs under one leader (>=1).
+ # agents_per_run: L2 — per-run agent admission cap (optional; None uses
+ # the engine's default agents-per-run resolution).
+ # max_agents_total: L3 — global agent admission across all runs (>=1).
+ swarmflow_concurrency:
+ max_workflows: 16
+ agents_per_run: null
+ max_agents_total: 64
+
# Enable the host-managed worktree capability used by team members and
# SwarmFlow agent calls with options.isolation="worktree".
worktree:
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 826944af75..d2a6402a30 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -144,333 +144,56 @@ _CODE_MODE_SYNC_METHODS = frozenset({
# ── 流式处理心跳间隔:当 Agent 处理时间超过此阈值时,发送心跳 chunk 保持 WebSocket 连接活跃 --
# 避免 ping_timeout 导致连接关闭。默认 10 秒,小于服务端 ping_timeout=20s。
_STREAM_HEARTBEAT_INTERVAL_SECONDS = 10.0
-_HISTORY_PAGE_SIZE = 50
-_HISTORY_WIRE_STRING_LIMIT = 16 * 1024
-_HISTORY_WIRE_METADATA_STRING_LIMIT = 256
-_HISTORY_WIRE_LIST_LIMIT = 100
-_HISTORY_WIRE_DEPTH_LIMIT = 8
-_HISTORY_WIRE_RECORD_MAX_BYTES = 64 * 1024
-_TEAM_HISTORY_DEFAULT_LIMIT = 500
-_TEAM_HISTORY_MAX_LIMIT = 1000
-_TEAM_HISTORY_DEFAULT_MAX_BYTES = 2 * 1024 * 1024
-_TEAM_HISTORY_MIN_MAX_BYTES = 2048
-_TEAM_HISTORY_MAX_MAX_BYTES = 6 * 1024 * 1024
-_TEAM_HISTORY_FRAME_OVERHEAD_BYTES = 1024
-_WORKFLOW_SNAPSHOT_MAX_BYTES = 6 * 1024 * 1024
-_WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES = 2048
-_WORKFLOW_SNAPSHOT_MAX_WORKFLOWS = 1000
-
-_HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset(
- {
- "chat.final",
- "chat.tool_call",
- "chat.tool_result",
- "chat.usage_summary",
- "chat.file",
- "team.message",
- "context.compact_boundary",
- "context.compact_summary",
- "context.rewind_summary",
- }
+from jiuwenswarm.server.wire_truncate import ( # noqa: F401 — re-exported for tests / handlers
+ _HISTORY_PAGE_SIZE,
+ _HISTORY_WIRE_STRING_LIMIT,
+ _HISTORY_WIRE_METADATA_STRING_LIMIT,
+ _HISTORY_WIRE_LIST_LIMIT,
+ _HISTORY_WIRE_DEPTH_LIMIT,
+ _HISTORY_WIRE_RECORD_MAX_BYTES,
+ _TEAM_HISTORY_DEFAULT_LIMIT,
+ _TEAM_HISTORY_MAX_LIMIT,
+ _TEAM_HISTORY_DEFAULT_MAX_BYTES,
+ _TEAM_HISTORY_MIN_MAX_BYTES,
+ _TEAM_HISTORY_MAX_MAX_BYTES,
+ _TEAM_HISTORY_FRAME_OVERHEAD_BYTES,
+ _WORKFLOW_SNAPSHOT_MAX_BYTES,
+ _WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES,
+ _WORKFLOW_SNAPSHOT_MAX_WORKFLOWS,
+ _WORKFLOW_LIST_SUMMARY_STRING_LIMIT,
+ _WORKFLOW_COLLAPSED_AGENT_TEXT_LIMIT,
+ _WORKFLOW_WAITING_HUMAN_PROMPT_MAX_BYTES,
+ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES,
+ _json_wire_size,
+ _coerce_int,
+ _truncate_string_by_bytes,
+ _compact_wire_metadata_value,
+ _sanitize_history_wire_value,
+ _collapse_oversized_history_record,
+ _minimal_history_record_for_wire,
+ _sanitize_history_record_for_wire,
+ _select_history_record_page,
+ _is_waiting_human_agent,
+ _extract_waiting_human_prompts,
+ _restore_waiting_human_prompts,
+ _workflow_agent_for_collapse,
+ _collapse_oversized_workflow_snapshot_item,
+ _minimal_workflow_snapshot_item_for_wire,
+ _minimal_workflow_detail_preserving_waiting_human,
+ _sanitize_workflow_snapshot_item_for_wire,
+ _fit_workflow_detail_to_budget,
+ _workflow_list_summary_phase,
+ _workflow_list_summary_item,
+ _minimal_workflow_list_item,
+ _fit_workflow_list_item_for_budget,
+ _build_workflow_list_payload,
+ _build_workflow_detail_payload,
+ _find_workflow_agent,
+ _build_workflow_human_prompt_payload,
+ _build_workflow_snapshot_payload,
)
-def _json_wire_size(value: Any) -> int:
- try:
- return len(json.dumps(value, ensure_ascii=False, default=str).encode("utf-8"))
- except Exception:
- return len(str(value).encode("utf-8", errors="replace"))
-
-
-def _coerce_int(value: Any, *, default: int, minimum: int, maximum: int) -> int:
- try:
- parsed = int(value)
- except (TypeError, ValueError):
- parsed = default
- return max(minimum, min(maximum, parsed))
-
-
-def _truncate_string_by_bytes(value: str, max_bytes: int) -> str:
- raw = value.encode("utf-8")
- if len(raw) <= max_bytes:
- return value
- suffix = " [truncated]"
- budget = max(0, max_bytes - len(suffix.encode("utf-8")))
- return raw[:budget].decode("utf-8", errors="ignore") + suffix
-
-
-def _sanitize_history_wire_value(value: Any, *, depth: int = 0) -> Any:
- if depth > _HISTORY_WIRE_DEPTH_LIMIT:
- return "<truncated>"
- if isinstance(value, str):
- return _truncate_string_by_bytes(value, _HISTORY_WIRE_STRING_LIMIT)
- if isinstance(value, dict):
- return {
- str(key): _sanitize_history_wire_value(item, depth=depth + 1)
- for key, item in value.items()
- }
- if isinstance(value, list):
- return [
- _sanitize_history_wire_value(item, depth=depth + 1)
- for item in value[:_HISTORY_WIRE_LIST_LIMIT]
- ]
- if isinstance(value, tuple):
- return [
- _sanitize_history_wire_value(item, depth=depth + 1)
- for item in value[:_HISTORY_WIRE_LIST_LIMIT]
- ]
- return value
-
-
-def _collapse_oversized_history_record(record: dict[str, Any]) -> dict[str, Any]:
- keep_keys = {
- "id",
- "role",
- "request_id",
- "channel_id",
- "session_id",
- "timestamp",
- "event_type",
- "mode",
- "member_name",
- "member_id",
- "source_member",
- "name",
- "status",
- }
- collapsed = {
- key: _sanitize_history_wire_value(value)
- for key, value in record.items()
- if key in keep_keys
- }
- content = record.get("content")
- if isinstance(content, str) and content.strip():
- collapsed["content"] = _truncate_string_by_bytes(content, 512)
- event = record.get("event")
- if isinstance(event, dict):
- collapsed["event"] = {
- key: _sanitize_history_wire_value(event.get(key))
- for key in ("type", "member_id", "task_id", "id", "status", "new_status", "team_id")
- if key in event
- }
- collapsed["truncated"] = True
- return collapsed
-
-
-def _compact_wire_metadata_value(value: Any) -> Any:
- if isinstance(value, str):
- return _truncate_string_by_bytes(value, _HISTORY_WIRE_METADATA_STRING_LIMIT)
- if isinstance(value, (int, float, bool)) or value is None:
- return value
- return _truncate_string_by_bytes(str(value), _HISTORY_WIRE_METADATA_STRING_LIMIT)
-
-
-def _minimal_history_record_for_wire(record: dict[str, Any]) -> dict[str, Any]:
- keep_keys = {
- "id",
- "role",
- "request_id",
- "channel_id",
- "session_id",
- "timestamp",
- "event_type",
- "mode",
- "member_name",
- "member_id",
- "source_member",
- "name",
- "status",
- }
- minimal = {
- key: _compact_wire_metadata_value(value)
- for key, value in record.items()
- if key in keep_keys
- }
- minimal["content"] = "[truncated]"
- minimal["truncated"] = True
- return minimal
-
-
-def _sanitize_history_record_for_wire(record: Any) -> dict[str, Any]:
- if not isinstance(record, dict):
- return {"content": _sanitize_history_wire_value(record), "truncated": True}
- sanitized = _sanitize_history_wire_value(record)
- if not isinstance(sanitized, dict):
- return {"content": str(sanitized), "truncated": True}
- if _json_wire_size(sanitized) <= _HISTORY_WIRE_RECORD_MAX_BYTES:
- return sanitized
- return _collapse_oversized_history_record(sanitized)
-
-
-def _select_history_record_page(
- records: list[dict[str, Any]],
- *,
- cursor: int,
- limit: int,
- max_bytes: int,
- session_id: str,
-) -> tuple[list[dict[str, Any]], int]:
- total = len(records)
- if cursor >= total:
- return [], total
-
- budget = max(
- _TEAM_HISTORY_MIN_MAX_BYTES,
- max_bytes - _TEAM_HISTORY_FRAME_OVERHEAD_BYTES,
- )
- base_payload = {
- "records": [],
- "session_id": session_id,
- "cursor": cursor,
- "next_cursor": cursor,
- "has_more": cursor < total,
- "total": total,
- }
- used = _json_wire_size(base_payload)
- page: list[dict[str, Any]] = []
- next_cursor = cursor
-
- for idx in range(cursor, total):
- if len(page) >= limit:
- break
- record = records[idx]
- record_size = _json_wire_size(record) + 1
- if record_size > budget:
- record = _collapse_oversized_history_record(record)
- record_size = _json_wire_size(record) + 1
- if page and used + record_size > budget:
- break
- if not page and used + record_size > budget:
- record = _collapse_oversized_history_record(record)
- record_size = _json_wire_size(record) + 1
- if used + record_size > budget:
- record = _minimal_history_record_for_wire(record)
- record_size = _json_wire_size(record) + 1
- if used + record_size > budget:
- record = {"id": _compact_wire_metadata_value(record.get("id")), "truncated": True}
- record_size = _json_wire_size(record) + 1
- page.append(record)
- used += record_size
- next_cursor = idx + 1
-
- return page, next_cursor
-
-
-def _collapse_oversized_workflow_snapshot_item(item: dict[str, Any]) -> dict[str, Any]:
- keep_keys = {
- "id",
- "name",
- "status",
- "agent_count",
- "completed_agent_count",
- "started_at",
- "completed_at",
- "duration_ms",
- "token_count",
- "estimated_token_count",
- }
- collapsed = {
- key: _sanitize_history_wire_value(value)
- for key, value in item.items()
- if key in keep_keys
- }
- for key in ("summary", "description", "error", "result"):
- value = item.get(key)
- if isinstance(value, str) and value.strip():
- collapsed[key] = _truncate_string_by_bytes(value, 512)
- elif value is not None:
- collapsed[key] = _truncate_string_by_bytes(str(value), 512)
- collapsed["truncated"] = True
- return collapsed
-
-
-def _minimal_workflow_snapshot_item_for_wire(item: dict[str, Any]) -> dict[str, Any]:
- keep_keys = {
- "id",
- "name",
- "status",
- "agent_count",
- "completed_agent_count",
- "started_at",
- "completed_at",
- "duration_ms",
- "token_count",
- "estimated_token_count",
- }
- minimal = {
- key: _compact_wire_metadata_value(value)
- for key, value in item.items()
- if key in keep_keys
- }
- minimal["summary"] = "[truncated]"
- minimal["truncated"] = True
- return minimal
-
-
-def _sanitize_workflow_snapshot_item_for_wire(item: Any) -> dict[str, Any]:
- if not isinstance(item, dict):
- return {"summary": _sanitize_history_wire_value(item), "truncated": True}
- sanitized = _sanitize_history_wire_value(item)
- if not isinstance(sanitized, dict):
- return {"summary": str(sanitized), "truncated": True}
- if _json_wire_size(sanitized) <= _HISTORY_WIRE_RECORD_MAX_BYTES:
- return sanitized
- return _collapse_oversized_workflow_snapshot_item(sanitized)
-
-
-def _build_workflow_snapshot_payload(workflows: Any, *, session_id: str) -> dict[str, Any]:
- source = workflows if isinstance(workflows, list) else []
- sanitized_workflows = [
- _sanitize_workflow_snapshot_item_for_wire(item)
- for item in source
- if isinstance(item, dict)
- ]
- total = len(sanitized_workflows)
- payload: dict[str, Any] = {
- "type": "workflow_run_snapshot",
- "workflows": [],
- "session_id": session_id,
- "total": total,
- "truncated": False,
- }
- budget = max(
- _TEAM_HISTORY_MIN_MAX_BYTES,
- _WORKFLOW_SNAPSHOT_MAX_BYTES - _WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES,
- )
- used = _json_wire_size(payload)
- page: list[dict[str, Any]] = []
-
- for workflow in sanitized_workflows:
- if len(page) >= _WORKFLOW_SNAPSHOT_MAX_WORKFLOWS:
- payload["truncated"] = True
- break
- item = workflow
- item_size = _json_wire_size(item) + 1
- if item_size > budget:
- item = _collapse_oversized_workflow_snapshot_item(item)
- item_size = _json_wire_size(item) + 1
- payload["truncated"] = True
- if page and used + item_size > budget:
- payload["truncated"] = True
- break
- if not page and used + item_size > budget:
- item = _collapse_oversized_workflow_snapshot_item(item)
- item_size = _json_wire_size(item) + 1
- if used + item_size > budget:
- item = _minimal_workflow_snapshot_item_for_wire(item)
- item_size = _json_wire_size(item) + 1
- if used + item_size > budget:
- item = {"id": _compact_wire_metadata_value(item.get("id")), "truncated": True}
- item_size = _json_wire_size(item) + 1
- payload["truncated"] = True
- page.append(item)
- used += item_size
-
- if len(page) < total:
- payload["truncated"] = True
- payload["workflows"] = page
- return payload
-
def _request_query_text(request: AgentRequest) -> str:
"""Return text chat query only; structured events are handled downstream."""
@@ -3314,23 +3037,29 @@ class AgentWebSocketServer:
await send_wire_payload(ws, wire)
async def _handle_command_workflows(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
- """Handle command.workflows RPC request — return workflow_run_snapshot."""
+ """Handle command.workflows RPC — list summaries or get one workflow detail."""
from jiuwenswarm.agents.harness.team import get_team_manager
session_id = request.session_id or ""
channel_id = request.channel_id or "web"
+ params = request.params if isinstance(request.params, dict) else {}
+ action = str(params.get("action") or "list").strip().lower()
+ workflow_id = params.get("workflow_id") or params.get("workflow_run_id")
+ wf_id_log = workflow_id.strip() if isinstance(workflow_id, str) else workflow_id
- # WF_DBG: 维测日志 — 记录 command.workflows 请求到达
logger.info(
- "[WF_DBG command_workflows] request received: "
- "channel_id=%s session_id=%s request_id=%s",
+ "[WF_DBG] command.workflows req channel_id=%s session_id=%s request_id=%s action=%s workflow_id=%s",
channel_id,
session_id,
request.request_id,
+ action,
+ wf_id_log,
)
team_manager = get_team_manager(channel_id)
workflow_handler = team_manager.get_workflow_handler(session_id)
+ source = "live" if workflow_handler is not None else "checkpoint"
+ detail_raw_bytes: int | None = None
if workflow_handler is None:
# No live handler (runtime not active / torn down by cancel-stop).
@@ -3351,65 +3080,151 @@ class AgentWebSocketServer:
)
except Exception as exc: # noqa: BLE001
logger.warning(
- "[WF_DBG command_workflows] checkpoint restore failed: "
- "channel_id=%s session_id=%s error=%s",
- channel_id,
+ "[WF_DBG] command.workflows checkpoint_restore_failed session_id=%s error=%s",
session_id,
exc,
)
workflows = []
- logger.info(
- "[WF_DBG command_workflows] no live handler, restored from checkpoint: "
- "channel_id=%s session_id=%s workflows_count=%d",
- channel_id,
- session_id,
- len(workflows),
- )
- resp = AgentResponse(
- request_id=request.request_id,
- channel_id=channel_id,
- ok=True,
- payload=_build_workflow_snapshot_payload(workflows, session_id=session_id),
- )
- wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
- async with send_lock:
- await send_wire_payload(ws, wire)
- return
+ else:
+ try:
+ workflows = workflow_handler.get_workflow_snapshot()
+ except Exception as e:
+ logger.warning(
+ "[WF_DBG] command.workflows snapshot_failed session_id=%s error=%s",
+ session_id,
+ e,
+ )
+ workflows = []
- try:
- snapshot = workflow_handler.get_workflow_snapshot()
- # WF_DBG: 维测日志 — 记录返回的快照内容摘要
- wf_names = [wf.get("name", "?") for wf in snapshot]
- wf_statuses = [wf.get("status", "?") for wf in snapshot]
- logger.info(
- "[WF_DBG command_workflows] snapshot returned: "
- "channel_id=%s session_id=%s workflows_count=%d "
- "names=%s statuses=%s",
- channel_id,
- session_id,
- len(snapshot),
- wf_names,
- wf_statuses,
- )
+ source_count = len(workflows)
+ source_bytes = sum(_json_wire_size(item) for item in workflows if isinstance(item, dict))
+
+ if action == "get":
+ if not isinstance(workflow_id, str) or not workflow_id.strip():
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok=False,
+ payload={"error": "workflow_id is required for action=get"},
+ )
+ else:
+ target_id = workflow_id.strip()
+ match = next(
+ (item for item in workflows if isinstance(item, dict) and item.get("id") == target_id),
+ None,
+ )
+ if match is None:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok=False,
+ payload={"error": f"workflow not found: {target_id}"},
+ )
+ else:
+ detail_raw_bytes = _json_wire_size(match)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok=True,
+ payload=_build_workflow_detail_payload(match, session_id=session_id),
+ )
+ elif action == "get_human_prompt":
+ agent_id = params.get("agent_id")
+ correlation_id = params.get("correlation_id")
+ agent_id_str = agent_id.strip() if isinstance(agent_id, str) and agent_id.strip() else None
+ corr_id_str = (
+ correlation_id.strip()
+ if isinstance(correlation_id, str) and correlation_id.strip()
+ else None
+ )
+ if not isinstance(workflow_id, str) or not workflow_id.strip():
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok=False,
+ payload={"error": "workflow_id is required for action=get_human_prompt"},
+ )
+ elif not agent_id_str and not corr_id_str:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok=False,
+ payload={"error": "agent_id or correlation_id is required for action=get_human_prompt"},
+ )
+ else:
+ target_id = workflow_id.strip()
+ match = next(
+ (item for item in workflows if isinstance(item, dict) and item.get("id") == target_id),
+ None,
+ )
+ if match is None:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok=False,
+ payload={"error": f"workflow not found: {target_id}"},
+ )
+ else:
+ prompt_payload = _build_workflow_human_prompt_payload(
+ match,
+ session_id=session_id,
+ agent_id=agent_id_str,
+ correlation_id=corr_id_str,
+ )
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=channel_id,
+ ok="error" not in prompt_payload,
+ payload=prompt_payload,
+ )
+ else:
resp = AgentResponse(
request_id=request.request_id,
channel_id=channel_id,
ok=True,
- payload=_build_workflow_snapshot_payload(snapshot, session_id=session_id),
- )
- except Exception as e:
- logger.warning(
- "[WF_DBG command_workflows] exception: "
- "channel_id=%s session_id=%s error=%s → returning empty snapshot",
- channel_id,
- session_id,
- e,
+ payload=_build_workflow_list_payload(workflows, session_id=session_id),
+ )
+
+ payload = resp.payload if isinstance(resp.payload, dict) else {}
+ payload_bytes = _json_wire_size(payload)
+ truncated = bool(payload.get("truncated")) if isinstance(payload, dict) else False
+ included = len(payload.get("workflows", [])) if payload.get("action") == "list" else None
+ error = payload.get("error") if isinstance(payload, dict) and not resp.ok else None
+ log_level = logging.WARNING if (not resp.ok or truncated) else logging.INFO
+ if action == "list":
+ logger.log(
+ log_level,
+ "[WF_DBG] command.workflows res ok=%s action=list source=%s count=%d source_bytes=%d "
+ "payload_bytes=%d included=%d/%d truncated=%s error=%s",
+ resp.ok,
+ source,
+ source_count,
+ source_bytes,
+ payload_bytes,
+ included or 0,
+ source_count,
+ truncated,
+ error,
)
- resp = AgentResponse(
- request_id=request.request_id,
- channel_id=channel_id,
- ok=True,
- payload=_build_workflow_snapshot_payload([], session_id=session_id),
+ else:
+ prompt_len = None
+ if action == "get_human_prompt" and isinstance(payload, dict):
+ human_prompt = payload.get("human_prompt")
+ if isinstance(human_prompt, str):
+ prompt_len = len(human_prompt.encode("utf-8"))
+ logger.log(
+ log_level,
+ "[WF_DBG] command.workflows res ok=%s action=%s source=%s workflow_id=%s "
+ "raw_bytes=%s payload_bytes=%d truncated=%s prompt_len=%s error=%s",
+ resp.ok,
+ action,
+ source,
+ wf_id_log,
+ detail_raw_bytes,
+ payload_bytes,
+ truncated,
+ prompt_len,
+ error,
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py b/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py
index 66006a696e..f75be72feb 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/agent_adapters.py
@@ -82,6 +82,14 @@ class AgentAdapter(Protocol):
"""Handle user answer for evolution approval or permission approval."""
...
+ async def handle_swarmflow_reply(self, request: AgentRequest) -> AgentResponse:
+ """Handle a person's reply to a pending swarmflow human-session turn.
+
+ Builds a HumanAgentMessage(target="swarmflow:<run_id>:<corr>") and
+ delivers it via team_manager.interact (the agent-core thin route).
+ """
+ ...
+
async def handle_heartbeat(self, request: AgentRequest) -> AgentResponse:
"""Handle heartbeat requests."""
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index b42836f5d6..c57a0b8c76 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1758,6 +1758,10 @@ class JiuWenSwarm:
adapter = self._ensure_adapter(mode=self._adapter_mode_for_request(request))
return await adapter.handle_user_answer(request)
+ if request.req_method == ReqMethod.CHAT_SWARMFLOW_REPLY:
+ adapter = self._ensure_adapter(mode=self._adapter_mode_for_request(request))
+ return await adapter.handle_swarmflow_reply(request)
+
# Non-stream goal command (GET, PAUSE, CLEAR)
if request.req_method == ReqMethod.COMMAND_GOAL:
try:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index d97e42205e..a880a1b495 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -6045,6 +6045,89 @@ class JiuWenSwarmDeepAdapter:
metadata=request.metadata,
)
+ async def handle_swarmflow_reply(self, request: AgentRequest) -> AgentResponse:
+ """Handle chat.swarmflow_reply — deliver a person's reply to a human turn.
+
+ Builds a HumanAgentMessage addressed to ``swarmflow:<run_id>:<corr>``
+ (run-scoped; falls back to ``swarmflow:<corr>`` when no run_id) and
+ delivers it via ``TeamManager.interact`` — the agent-core thin route
+ resolves the pending human-session future on the run's reply topic.
+ """
+ if not self._is_session_scoped_adapter:
+ session_adapter = await self._get_or_create_session_adapter(request.session_id)
+ try:
+ return await session_adapter.handle_swarmflow_reply(request)
+ finally:
+ await self._evict_idle_session_adapters()
+
+ params = request.params if isinstance(request.params, dict) else {}
+ session_id = params.get("session_id") or request.session_id or ""
+ run_id = params.get("run_id")
+ corr = params.get("correlation_id") or ""
+ answer = params.get("answer") or ""
+ logger.info(
+ "[WF_DBG] chat.swarmflow_reply req channel_id=%s session_id=%s request_id=%s "
+ "run_id=%s correlation_id=%s answer_len=%d",
+ request.channel_id,
+ session_id,
+ request.request_id,
+ run_id,
+ corr,
+ len(answer) if isinstance(answer, str) else 0,
+ )
+ if not session_id or not corr or answer == "":
+ logger.warning(
+ "[WF_DBG] chat.swarmflow_reply res ok=False session_id=%s correlation_id=%s error=missing_params",
+ session_id,
+ corr,
+ )
+ return AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"ok": False, "error": "missing session_id/correlation_id/answer"},
+ metadata=request.metadata,
+ )
+
+ from jiuwenswarm.agents.harness.team import get_team_manager
+ from openjiuwen.agent_teams.constants import USER_PSEUDO_MEMBER_NAME
+ from openjiuwen.agent_teams.interaction.payload import HumanAgentMessage
+
+ from openjiuwen.agent_teams.schema.events import format_swarmflow_human_reply_target
+
+ target = format_swarmflow_human_reply_target(corr, run_id)
+ msg = HumanAgentMessage(
+ sender=USER_PSEUDO_MEMBER_NAME,
+ target=target,
+ body=answer,
+ )
+ try:
+ team_manager = get_team_manager(request.channel_id)
+ ok, reason = await team_manager.interact(session_id, msg)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] swarmflow reply delivery failed: "
+ "session_id=%s corr=%s error=%s",
+ session_id, corr, exc,
+ )
+ ok, reason = False, "exception"
+
+ logger.log(
+ logging.WARNING if not ok else logging.INFO,
+ "[WF_DBG] chat.swarmflow_reply res ok=%s session_id=%s correlation_id=%s error=%s",
+ ok,
+ session_id,
+ corr,
+ None if ok else (reason or "failed"),
+ )
+ return AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=bool(ok),
+ payload={"ok": True} if ok else {"ok": False, "error": reason or "failed"},
+ metadata=request.metadata,
+ )
+
@staticmethod
def _is_interrupt_skill_evolution_approval_params(request_id: str, params: Any) -> bool:
if not isinstance(params, dict):
diff --git a/jiuwenswarm/server/wire_truncate.py b/jiuwenswarm/server/wire_truncate.py
new file mode 100644
index 0000000000..93ae1408f8
--- /dev/null
+++ b/jiuwenswarm/server/wire_truncate.py
@@ -0,0 +1,803 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Wire-payload truncation for the AgentWebSocketServer.
+
+Centralizes every byte-budget / shrink-and-collapse helper that prepares team
+history records and swarmflow workflow snapshots for the WebSocket wire. Two
+phases share one set of low-level tools:
+
+* **History records** — ``_sanitize_history_record_for_wire`` /
+ ``_select_history_record_page`` paginate a session's history under a byte
+ budget, collapsing oversized records down to a metadata stub.
+* **Workflow snapshots** — ``_build_workflow_list_payload`` /
+ ``_build_workflow_detail_payload`` shape swarmflow runs for the
+ ``command.workflows`` RPC, with a HITL carve-out that always preserves a
+ ``waiting_for_human`` node's ``human_prompt``.
+
+Everything is pure: given an input dict and a byte budget, return a wire-safe
+dict. The only I/O is the caller's. Sized via ``_json_wire_size`` (UTF-8 bytes
+of the JSON encoding) — never character count.
+"""
+from __future__ import annotations
+
+import json
+from typing import Any
+
+# ---------------------------------------------------------------------------
+# Wire byte budgets
+# ---------------------------------------------------------------------------
+
+_HISTORY_PAGE_SIZE = 50
+_HISTORY_WIRE_STRING_LIMIT = 16 * 1024
+_HISTORY_WIRE_METADATA_STRING_LIMIT = 256
+_HISTORY_WIRE_LIST_LIMIT = 100
+_HISTORY_WIRE_DEPTH_LIMIT = 8
+_HISTORY_WIRE_RECORD_MAX_BYTES = 64 * 1024
+_TEAM_HISTORY_DEFAULT_LIMIT = 500
+_TEAM_HISTORY_MAX_LIMIT = 1000
+_TEAM_HISTORY_DEFAULT_MAX_BYTES = 2 * 1024 * 1024
+_TEAM_HISTORY_MIN_MAX_BYTES = 2048
+_TEAM_HISTORY_MAX_MAX_BYTES = 6 * 1024 * 1024
+_TEAM_HISTORY_FRAME_OVERHEAD_BYTES = 1024
+_WORKFLOW_SNAPSHOT_MAX_BYTES = 6 * 1024 * 1024
+_WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES = 2048
+_WORKFLOW_SNAPSHOT_MAX_WORKFLOWS = 1000
+_WORKFLOW_LIST_SUMMARY_STRING_LIMIT = 256
+_WORKFLOW_COLLAPSED_AGENT_TEXT_LIMIT = 512
+_WORKFLOW_WAITING_HUMAN_PROMPT_MAX_BYTES = 512 * 1024
+
+_TRUNCATE_SUFFIX = " [truncated]"
+
+_HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset(
+ {
+ "chat.final",
+ "chat.tool_call",
+ "chat.tool_result",
+ "chat.usage_summary",
+ "chat.file",
+ "team.message",
+ "context.compact_boundary",
+ "context.compact_summary",
+ "context.rewind_summary",
+ }
+)
+
+_HISTORY_COLLAPSE_KEEP_KEYS = {
+ "id",
+ "role",
+ "request_id",
+ "channel_id",
+ "session_id",
+ "timestamp",
+ "event_type",
+ "mode",
+ "member_name",
+ "member_id",
+ "source_member",
+ "name",
+ "status",
+}
+
+_WORKFLOW_SNAPSHOT_KEEP_KEYS = {
+ "id",
+ "name",
+ "status",
+ "agent_count",
+ "completed_agent_count",
+ "started_at",
+ "completed_at",
+ "duration_ms",
+ "token_count",
+ "estimated_token_count",
+}
+
+_WORKFLOW_LIST_SUMMARY_KEEP_KEYS = (
+ "id",
+ "name",
+ "status",
+ "agent_count",
+ "completed_agent_count",
+ "started_at",
+ "completed_at",
+ "duration_ms",
+ "token_count",
+ "estimated_token_count",
+)
+
+
+# ---------------------------------------------------------------------------
+# Low-level sizing / truncation
+# ---------------------------------------------------------------------------
+
+def _json_wire_size(value: Any) -> int:
+ """UTF-8 byte length of ``value``'s JSON wire encoding."""
+ try:
+ return len(json.dumps(value, ensure_ascii=False, default=str).encode("utf-8"))
+ except Exception:
+ return len(str(value).encode("utf-8", errors="replace"))
+
+
+def _coerce_int(value: Any, *, default: int, minimum: int, maximum: int) -> int:
+ """Coerce a request param to a clamped int (default on parse failure)."""
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ parsed = default
+ return max(minimum, min(maximum, parsed))
+
+
+def _truncate_string_by_bytes(value: str, max_bytes: int) -> str:
+ """Truncate ``value`` to at most ``max_bytes`` UTF-8 bytes.
+
+ Appends ``" [truncated]"`` and decodes the byte slice with
+ ``errors="ignore"`` so a split multi-byte character is dropped rather than
+ producing invalid UTF-8 (which would break the frontend's JSON parse).
+ """
+ raw = value.encode("utf-8")
+ if len(raw) <= max_bytes:
+ return value
+ budget = max(0, max_bytes - len(_TRUNCATE_SUFFIX.encode("utf-8")))
+ return raw[:budget].decode("utf-8", errors="ignore") + _TRUNCATE_SUFFIX
+
+
+def _compact_wire_metadata_value(value: Any) -> Any:
+ """Compact a metadata scalar to a short wire-safe string."""
+ if isinstance(value, str):
+ return _truncate_string_by_bytes(value, _HISTORY_WIRE_METADATA_STRING_LIMIT)
+ if isinstance(value, (int, float, bool)) or value is None:
+ return value
+ return _truncate_string_by_bytes(str(value), _HISTORY_WIRE_METADATA_STRING_LIMIT)
+
+
+def _sanitize_history_wire_value(value: Any, *, depth: int = 0) -> Any:
+ """Recursively bound a value for the wire: strings, lists, depth."""
+ if depth > _HISTORY_WIRE_DEPTH_LIMIT:
+ return "<truncated>"
+ if isinstance(value, str):
+ return _truncate_string_by_bytes(value, _HISTORY_WIRE_STRING_LIMIT)
+ if isinstance(value, dict):
+ return {
+ str(key): _sanitize_history_wire_value(item, depth=depth + 1)
+ for key, item in value.items()
+ }
+ if isinstance(value, list):
+ return [
+ _sanitize_history_wire_value(item, depth=depth + 1)
+ for item in value[:_HISTORY_WIRE_LIST_LIMIT]
+ ]
+ if isinstance(value, tuple):
+ return [
+ _sanitize_history_wire_value(item, depth=depth + 1)
+ for item in value[:_HISTORY_WIRE_LIST_LIMIT]
+ ]
+ return value
+
+
+# ---------------------------------------------------------------------------
+# History record shaping
+# ---------------------------------------------------------------------------
+
+def _collapse_oversized_history_record(record: dict[str, Any]) -> dict[str, Any]:
+ """Collapse a too-large history record to a metadata stub + short content."""
+ collapsed = {
+ key: _sanitize_history_wire_value(value)
+ for key, value in record.items()
+ if key in _HISTORY_COLLAPSE_KEEP_KEYS
+ }
+ content = record.get("content")
+ if isinstance(content, str) and content.strip():
+ collapsed["content"] = _truncate_string_by_bytes(content, 512)
+ event = record.get("event")
+ if isinstance(event, dict):
+ collapsed["event"] = {
+ key: _sanitize_history_wire_value(event.get(key))
+ for key in ("type", "member_id", "task_id", "id", "status", "new_status", "team_id")
+ if key in event
+ }
+ collapsed["truncated"] = True
+ return collapsed
+
+
+def _minimal_history_record_for_wire(record: dict[str, Any]) -> dict[str, Any]:
+ """Smallest history record stub: metadata only, content replaced."""
+ minimal = {
+ key: _compact_wire_metadata_value(value)
+ for key, value in record.items()
+ if key in _HISTORY_COLLAPSE_KEEP_KEYS
+ }
+ minimal["content"] = "[truncated]"
+ minimal["truncated"] = True
+ return minimal
+
+
+def _sanitize_history_record_for_wire(record: Any) -> dict[str, Any]:
+ """Sanitize one history record, collapsing if it exceeds the per-record budget."""
+ if not isinstance(record, dict):
+ return {"content": _sanitize_history_wire_value(record), "truncated": True}
+ sanitized = _sanitize_history_wire_value(record)
+ if not isinstance(sanitized, dict):
+ return {"content": str(sanitized), "truncated": True}
+ if _json_wire_size(sanitized) <= _HISTORY_WIRE_RECORD_MAX_BYTES:
+ return sanitized
+ return _collapse_oversized_history_record(sanitized)
+
+
+def _select_history_record_page(
+ records: list[dict[str, Any]],
+ *,
+ cursor: int,
+ limit: int,
+ max_bytes: int,
+ session_id: str,
+) -> tuple[list[dict[str, Any]], int]:
+ """Select a byte-bounded page of history records from ``cursor``.
+
+ Shrinks records that alone exceed the budget (collapse → minimal → id-only)
+ so the page still advances instead of stalling on one huge record.
+ """
+ total = len(records)
+ if cursor >= total:
+ return [], total
+
+ budget = max(
+ _TEAM_HISTORY_MIN_MAX_BYTES,
+ max_bytes - _TEAM_HISTORY_FRAME_OVERHEAD_BYTES,
+ )
+ base_payload = {
+ "records": [],
+ "session_id": session_id,
+ "cursor": cursor,
+ "next_cursor": cursor,
+ "has_more": cursor < total,
+ "total": total,
+ }
+ used = _json_wire_size(base_payload)
+ page: list[dict[str, Any]] = []
+ next_cursor = cursor
+
+ for idx in range(cursor, total):
+ if len(page) >= limit:
+ break
+ record = records[idx]
+ record_size = _json_wire_size(record) + 1
+ if record_size > budget:
+ record = _collapse_oversized_history_record(record)
+ record_size = _json_wire_size(record) + 1
+ if page and used + record_size > budget:
+ break
+ if not page and used + record_size > budget:
+ record = _collapse_oversized_history_record(record)
+ record_size = _json_wire_size(record) + 1
+ if used + record_size > budget:
+ record = _minimal_history_record_for_wire(record)
+ record_size = _json_wire_size(record) + 1
+ if used + record_size > budget:
+ record = {"id": _compact_wire_metadata_value(record.get("id")), "truncated": True}
+ record_size = _json_wire_size(record) + 1
+ page.append(record)
+ used += record_size
+ next_cursor = idx + 1
+
+ return page, next_cursor
+
+
+# ---------------------------------------------------------------------------
+# Workflow snapshot — HITL (waiting-for-human) helpers
+# ---------------------------------------------------------------------------
+
+def _is_waiting_human_agent(agent: dict[str, Any]) -> bool:
+ return agent.get("status") == "waiting_for_human" and agent.get("kind") == "human"
+
+
+def _extract_waiting_human_prompts(workflow: dict[str, Any]) -> dict[str, str]:
+ """Pull every waiting-human node's prompt, keyed by agent id, before shrink."""
+ prompts: dict[str, str] = {}
+ phases = workflow.get("phases")
+ if not isinstance(phases, list):
+ return prompts
+ for phase in phases:
+ if not isinstance(phase, dict):
+ continue
+ agents = phase.get("agents")
+ if not isinstance(agents, list):
+ continue
+ for agent in agents:
+ if not isinstance(agent, dict) or not _is_waiting_human_agent(agent):
+ continue
+ prompt = agent.get("human_prompt")
+ agent_id = agent.get("id")
+ has_prompt = isinstance(prompt, str) and bool(prompt.strip())
+ has_agent_id = isinstance(agent_id, str) and bool(agent_id)
+ if has_prompt and has_agent_id:
+ prompts[agent_id] = prompt
+ return prompts
+
+
+def _restore_waiting_human_prompts(item: dict[str, Any], prompts: dict[str, str]) -> None:
+ """Re-attach preserved human prompts onto a shrunk item's waiting nodes."""
+ if not prompts:
+ return
+ phases = item.get("phases")
+ if not isinstance(phases, list):
+ return
+ for phase in phases:
+ if not isinstance(phase, dict):
+ continue
+ agents = phase.get("agents")
+ if not isinstance(agents, list):
+ continue
+ for agent in agents:
+ if not isinstance(agent, dict):
+ continue
+ agent_id = agent.get("id")
+ if isinstance(agent_id, str) and agent_id in prompts:
+ agent["human_prompt"] = prompts[agent_id]
+
+
+def _workflow_agent_for_collapse(agent: dict[str, Any]) -> dict[str, Any]:
+ """Collapse one agent: keep identity + short text fields, bigger human_prompt."""
+ collapsed_agent: dict[str, Any] = {
+ "id": agent.get("id", ""),
+ "name": agent.get("name", ""),
+ "status": agent.get("status", "running"),
+ "kind": agent.get("kind", "agent"),
+ }
+ if agent.get("model"):
+ collapsed_agent["model"] = agent["model"]
+ if agent.get("correlation_id"):
+ collapsed_agent["correlation_id"] = agent["correlation_id"]
+ for time_key in ("started_at", "completed_at", "duration_ms"):
+ if time_key in agent:
+ collapsed_agent[time_key] = agent[time_key]
+
+ if _is_waiting_human_agent(agent):
+ prompt = agent.get("human_prompt")
+ if isinstance(prompt, str) and prompt.strip():
+ collapsed_agent["human_prompt"] = _truncate_string_by_bytes(
+ prompt,
+ _WORKFLOW_WAITING_HUMAN_PROMPT_MAX_BYTES,
+ )
+ return collapsed_agent
+
+ for text_key in ("prompt", "outcome", "error", "human_prompt", "human_reply"):
+ value = agent.get(text_key)
+ if isinstance(value, str) and value.strip():
+ collapsed_agent[text_key] = _truncate_string_by_bytes(
+ value,
+ _WORKFLOW_COLLAPSED_AGENT_TEXT_LIMIT,
+ )
+ elif value is not None:
+ collapsed_agent[text_key] = _truncate_string_by_bytes(
+ str(value),
+ _WORKFLOW_COLLAPSED_AGENT_TEXT_LIMIT,
+ )
+ return collapsed_agent
+
+
+# ---------------------------------------------------------------------------
+# Workflow snapshot — single-item shrink ladder
+# ---------------------------------------------------------------------------
+
+def _collapse_oversized_workflow_snapshot_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Collapse a too-large workflow item: keep structure, truncate large text."""
+ collapsed = {
+ key: _sanitize_history_wire_value(value)
+ for key, value in item.items()
+ if key in _WORKFLOW_SNAPSHOT_KEEP_KEYS
+ }
+ for key in ("summary", "description", "error", "result"):
+ value = item.get(key)
+ if isinstance(value, str) and value.strip():
+ collapsed[key] = _truncate_string_by_bytes(value, 512)
+ elif value is not None:
+ collapsed[key] = _truncate_string_by_bytes(str(value), 512)
+
+ phases = item.get("phases")
+ if isinstance(phases, list):
+ collapsed_phases = []
+ for phase in phases:
+ if not isinstance(phase, dict):
+ continue
+ collapsed_phase = {
+ "id": phase.get("id", ""),
+ "name": phase.get("name", ""),
+ "status": phase.get("status", "running"),
+ "agent_count": phase.get("agent_count", 0),
+ "completed_agent_count": phase.get("completed_agent_count", 0),
+ }
+ agents = phase.get("agents")
+ if isinstance(agents, list):
+ collapsed_agents = []
+ for agent in agents:
+ if not isinstance(agent, dict):
+ continue
+ collapsed_agents.append(_workflow_agent_for_collapse(agent))
+ collapsed_phase["agents"] = collapsed_agents
+ collapsed_phases.append(collapsed_phase)
+ collapsed["phases"] = collapsed_phases
+
+ logs = item.get("logs")
+ if isinstance(logs, list) and logs:
+ collapsed["logs"] = [
+ _truncate_string_by_bytes(str(log), 512)
+ for log in logs[-10:]
+ ]
+
+ collapsed["truncated"] = True
+ return collapsed
+
+
+def _minimal_workflow_snapshot_item_for_wire(item: dict[str, Any]) -> dict[str, Any]:
+ """Bare workflow item: metadata only, summary replaced, no phases."""
+ minimal = {
+ key: _compact_wire_metadata_value(value)
+ for key, value in item.items()
+ if key in _WORKFLOW_SNAPSHOT_KEEP_KEYS
+ }
+ minimal["summary"] = "[truncated]"
+ minimal["truncated"] = True
+ return minimal
+
+
+def _minimal_workflow_detail_preserving_waiting_human(item: dict[str, Any]) -> dict[str, Any]:
+ """Minimal item that still carries its waiting-human nodes (HITL carve-out)."""
+ minimal = _minimal_workflow_snapshot_item_for_wire(item)
+ phases = item.get("phases")
+ if not isinstance(phases, list):
+ return minimal
+
+ preserved_phases: list[dict[str, Any]] = []
+ for phase in phases:
+ if not isinstance(phase, dict):
+ continue
+ agents = phase.get("agents")
+ if not isinstance(agents, list):
+ continue
+ waiting_agents = [
+ _workflow_agent_for_collapse(agent)
+ for agent in agents
+ if isinstance(agent, dict) and _is_waiting_human_agent(agent)
+ ]
+ if not waiting_agents:
+ continue
+ preserved_phases.append(
+ {
+ "id": phase.get("id", ""),
+ "name": phase.get("name", ""),
+ "status": phase.get("status", "running"),
+ "agent_count": phase.get("agent_count", len(waiting_agents)),
+ "completed_agent_count": phase.get("completed_agent_count", 0),
+ "agents": waiting_agents,
+ }
+ )
+ if preserved_phases:
+ minimal["phases"] = preserved_phases
+ return minimal
+
+
+def _sanitize_workflow_snapshot_item_for_wire(item: Any) -> dict[str, Any]:
+ """Sanitize one workflow item, collapsing if it exceeds the per-record budget."""
+ if not isinstance(item, dict):
+ return {"summary": _sanitize_history_wire_value(item), "truncated": True}
+ sanitized = _sanitize_history_wire_value(item)
+ if not isinstance(sanitized, dict):
+ return {"summary": str(sanitized), "truncated": True}
+ if _json_wire_size(sanitized) <= _HISTORY_WIRE_RECORD_MAX_BYTES:
+ return sanitized
+ return _collapse_oversized_workflow_snapshot_item(item)
+
+
+def _fit_workflow_detail_to_budget(
+ item: dict[str, Any],
+ *,
+ budget: int,
+ preserved_prompts: dict[str, str],
+) -> dict[str, Any]:
+ """Shrink a workflow detail item until it fits ``budget`` bytes.
+
+ Drop logs first, then strip to waiting-human-only, then bare metadata.
+ Preserved human prompts are re-attached after every shrink so a HITL turn
+ is never left without its question.
+ """
+ if _json_wire_size(item) <= budget:
+ return item
+
+ trimmed = dict(item)
+ trimmed.pop("logs", None)
+ _restore_waiting_human_prompts(trimmed, preserved_prompts)
+ if _json_wire_size(trimmed) <= budget:
+ trimmed["truncated"] = True
+ return trimmed
+
+ if preserved_prompts:
+ trimmed = _minimal_workflow_detail_preserving_waiting_human(item)
+ _restore_waiting_human_prompts(trimmed, preserved_prompts)
+ if _json_wire_size(trimmed) <= budget:
+ trimmed["truncated"] = True
+ return trimmed
+
+ minimal = _minimal_workflow_snapshot_item_for_wire(item)
+ minimal["truncated"] = True
+ return minimal
+
+
+# ---------------------------------------------------------------------------
+# Workflow snapshot — list shaping
+# ---------------------------------------------------------------------------
+
+def _workflow_list_summary_phase(phase: dict[str, Any]) -> dict[str, Any]:
+ """Phase skeleton for list — counts and status only, no agent bodies."""
+ return {
+ "id": phase.get("id", ""),
+ "name": phase.get("name", ""),
+ "status": phase.get("status", "running"),
+ "agent_count": phase.get("agent_count", 0),
+ "completed_agent_count": phase.get("completed_agent_count", 0),
+ "agents": [],
+ }
+
+
+def _workflow_list_summary_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Compact workflow row for ``command.workflows`` list — omits large text fields."""
+ summary: dict[str, Any] = {
+ key: _compact_wire_metadata_value(item.get(key))
+ for key in _WORKFLOW_LIST_SUMMARY_KEEP_KEYS
+ if item.get(key) is not None
+ }
+ for key in ("summary", "error", "result"):
+ value = item.get(key)
+ if isinstance(value, str) and value.strip():
+ summary[key] = _truncate_string_by_bytes(value, _WORKFLOW_LIST_SUMMARY_STRING_LIMIT)
+ elif value is not None and key not in summary:
+ summary[key] = _truncate_string_by_bytes(str(value), _WORKFLOW_LIST_SUMMARY_STRING_LIMIT)
+
+ phases = item.get("phases")
+ if isinstance(phases, list):
+ summary["phases"] = [
+ _workflow_list_summary_phase(phase)
+ for phase in phases
+ if isinstance(phase, dict)
+ ]
+
+ summary["detail_pending"] = True
+ return summary
+
+
+def _minimal_workflow_list_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Smallest list row when the full summary still exceeds the wire budget."""
+ return {
+ "id": _compact_wire_metadata_value(item.get("id")),
+ "name": _truncate_string_by_bytes(str(item.get("name") or "workflow"), 128),
+ "status": _compact_wire_metadata_value(item.get("status") or "running"),
+ "agent_count": item.get("agent_count", 0),
+ "completed_agent_count": item.get("completed_agent_count", 0),
+ "detail_pending": True,
+ }
+
+
+def _fit_workflow_list_item_for_budget(item: dict[str, Any], budget: int) -> dict[str, Any]:
+ """Shrink a list row until it fits the remaining byte budget."""
+ candidate = _workflow_list_summary_item(item)
+ if _json_wire_size(candidate) + 1 <= budget:
+ return candidate
+ candidate = _minimal_workflow_list_item(item)
+ if _json_wire_size(candidate) + 1 <= budget:
+ return candidate
+ shrunk = {
+ "id": _compact_wire_metadata_value(item.get("id")),
+ "name": _truncate_string_by_bytes(str(item.get("name") or "workflow"), 64),
+ "status": _compact_wire_metadata_value(item.get("status") or "running"),
+ "detail_pending": True,
+ }
+ if _json_wire_size(shrunk) + 1 <= budget:
+ return shrunk
+ return {
+ "id": _compact_wire_metadata_value(item.get("id")),
+ "detail_pending": True,
+ "truncated": True,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Workflow snapshot — public payload builders
+# ---------------------------------------------------------------------------
+
+def _build_workflow_list_payload(workflows: Any, *, session_id: str) -> dict[str, Any]:
+ """Return lightweight workflow summaries — every run listed, detail via ``action=get``."""
+ source = [item for item in (workflows if isinstance(workflows, list) else []) if isinstance(item, dict)]
+ total = len(source)
+ payload: dict[str, Any] = {
+ "type": "workflow_run_snapshot",
+ "action": "list",
+ "workflows": [],
+ "session_id": session_id,
+ "total": total,
+ "truncated": False,
+ }
+ budget = max(
+ _TEAM_HISTORY_MIN_MAX_BYTES,
+ _WORKFLOW_SNAPSHOT_MAX_BYTES - _WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES,
+ )
+ used = _json_wire_size(payload)
+ page: list[dict[str, Any]] = []
+
+ for raw in source[:_WORKFLOW_SNAPSHOT_MAX_WORKFLOWS]:
+ remaining = max(256, budget - used)
+ item = _fit_workflow_list_item_for_budget(raw, remaining)
+ item_size = _json_wire_size(item) + 1
+ if page and used + item_size > budget:
+ payload["truncated"] = True
+ item = _fit_workflow_list_item_for_budget(raw, max(128, budget - used))
+ item_size = _json_wire_size(item) + 1
+ if used + item_size > budget:
+ payload["truncated"] = True
+ break
+ page.append(item)
+ used += item_size
+
+ if len(page) < total:
+ payload["truncated"] = True
+ payload["workflows"] = page
+ return payload
+
+
+def _build_workflow_detail_payload(workflow: dict[str, Any], *, session_id: str) -> dict[str, Any]:
+ """Return one workflow with full detail (subject to single-record sanitize/collapse)."""
+ preserved_prompts = _extract_waiting_human_prompts(workflow)
+ sanitized = _sanitize_workflow_snapshot_item_for_wire(workflow)
+ detail_budget = max(
+ _TEAM_HISTORY_MIN_MAX_BYTES,
+ _WORKFLOW_SNAPSHOT_MAX_BYTES - _WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES,
+ )
+ item = sanitized
+ truncated = bool(item.get("truncated"))
+ if _json_wire_size(item) > detail_budget:
+ item = _collapse_oversized_workflow_snapshot_item(workflow)
+ truncated = True
+ if _json_wire_size(item) > detail_budget:
+ item = _minimal_workflow_detail_preserving_waiting_human(workflow)
+ truncated = True
+ if _json_wire_size(item) > detail_budget:
+ item = _minimal_workflow_snapshot_item_for_wire(workflow)
+ truncated = True
+ _restore_waiting_human_prompts(item, preserved_prompts)
+ item = _fit_workflow_detail_to_budget(
+ item,
+ budget=detail_budget,
+ preserved_prompts=preserved_prompts,
+ )
+ truncated = truncated or bool(item.get("truncated"))
+ if truncated:
+ item["truncated"] = True
+ else:
+ item.pop("truncated", None)
+ return {
+ "type": "workflow_run_detail",
+ "action": "get",
+ "workflow": item,
+ "session_id": session_id,
+ "truncated": truncated,
+ }
+
+
+def _find_workflow_agent(
+ workflow: dict[str, Any],
+ *,
+ agent_id: str | None = None,
+ correlation_id: str | None = None,
+) -> dict[str, Any] | None:
+ """Locate one agent node across a workflow's phases by id / correlation_id."""
+ phases = workflow.get("phases")
+ if not isinstance(phases, list):
+ return None
+ for phase in phases:
+ if not isinstance(phase, dict):
+ continue
+ agents = phase.get("agents")
+ if not isinstance(agents, list):
+ continue
+ for agent in agents:
+ if not isinstance(agent, dict):
+ continue
+ if agent_id and agent.get("id") == agent_id:
+ return agent
+ if correlation_id and agent.get("correlation_id") == correlation_id:
+ return agent
+ return None
+
+
+def _build_workflow_human_prompt_payload(
+ workflow: dict[str, Any],
+ *,
+ session_id: str,
+ agent_id: str | None = None,
+ correlation_id: str | None = None,
+) -> dict[str, Any]:
+ """Build the ``workflow_human_prompt`` payload for ``action=get_human_prompt``."""
+ agent = _find_workflow_agent(
+ workflow,
+ agent_id=agent_id,
+ correlation_id=correlation_id,
+ )
+ if agent is None:
+ return {
+ "type": "workflow_human_prompt",
+ "action": "get_human_prompt",
+ "session_id": session_id,
+ "error": "agent not found",
+ }
+ prompt = agent.get("human_prompt")
+ if not isinstance(prompt, str) or not prompt.strip():
+ return {
+ "type": "workflow_human_prompt",
+ "action": "get_human_prompt",
+ "session_id": session_id,
+ "workflow_id": workflow.get("id"),
+ "agent_id": agent.get("id"),
+ "correlation_id": agent.get("correlation_id"),
+ "human_prompt": "",
+ }
+ return {
+ "type": "workflow_human_prompt",
+ "action": "get_human_prompt",
+ "session_id": session_id,
+ "workflow_id": workflow.get("id"),
+ "agent_id": agent.get("id"),
+ "correlation_id": agent.get("correlation_id"),
+ "human_prompt": prompt,
+ }
+
+
+def _build_workflow_snapshot_payload(workflows: Any, *, session_id: str) -> dict[str, Any]:
+ """Backward-compatible alias — defaults to lightweight list summaries."""
+ return _build_workflow_list_payload(workflows, session_id=session_id)
+
+
+__all__ = [
+ "_HISTORY_PAGE_SIZE",
+ "_HISTORY_WIRE_STRING_LIMIT",
+ "_HISTORY_WIRE_METADATA_STRING_LIMIT",
+ "_HISTORY_WIRE_LIST_LIMIT",
+ "_HISTORY_WIRE_DEPTH_LIMIT",
+ "_HISTORY_WIRE_RECORD_MAX_BYTES",
+ "_TEAM_HISTORY_DEFAULT_LIMIT",
+ "_TEAM_HISTORY_MAX_LIMIT",
+ "_TEAM_HISTORY_DEFAULT_MAX_BYTES",
+ "_TEAM_HISTORY_MIN_MAX_BYTES",
+ "_TEAM_HISTORY_MAX_MAX_BYTES",
+ "_TEAM_HISTORY_FRAME_OVERHEAD_BYTES",
+ "_WORKFLOW_SNAPSHOT_MAX_BYTES",
+ "_WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES",
+ "_WORKFLOW_SNAPSHOT_MAX_WORKFLOWS",
+ "_WORKFLOW_LIST_SUMMARY_STRING_LIMIT",
+ "_WORKFLOW_COLLAPSED_AGENT_TEXT_LIMIT",
+ "_WORKFLOW_WAITING_HUMAN_PROMPT_MAX_BYTES",
+ "_HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES",
+ "_json_wire_size",
+ "_coerce_int",
+ "_truncate_string_by_bytes",
+ "_compact_wire_metadata_value",
+ "_sanitize_history_wire_value",
+ "_collapse_oversized_history_record",
+ "_minimal_history_record_for_wire",
+ "_sanitize_history_record_for_wire",
+ "_select_history_record_page",
+ "_is_waiting_human_agent",
+ "_extract_waiting_human_prompts",
+ "_restore_waiting_human_prompts",
+ "_workflow_agent_for_collapse",
+ "_collapse_oversized_workflow_snapshot_item",
+ "_minimal_workflow_snapshot_item_for_wire",
+ "_minimal_workflow_detail_preserving_waiting_human",
+ "_sanitize_workflow_snapshot_item_for_wire",
+ "_fit_workflow_detail_to_budget",
+ "_workflow_list_summary_phase",
+ "_workflow_list_summary_item",
+ "_minimal_workflow_list_item",
+ "_fit_workflow_list_item_for_budget",
+ "_build_workflow_list_payload",
+ "_build_workflow_detail_payload",
+ "_find_workflow_agent",
+ "_build_workflow_human_prompt_payload",
+ "_build_workflow_snapshot_payload",
+]
diff --git a/tests/unit_tests/agentserver/test_command_workflows_handler.py b/tests/unit_tests/agentserver/test_command_workflows_handler.py
index 2b49c74651..02bf67afa1 100644
--- a/tests/unit_tests/agentserver/test_command_workflows_handler.py
+++ b/tests/unit_tests/agentserver/test_command_workflows_handler.py
@@ -117,7 +117,7 @@ class TestHandleCommandWorkflows:
@pytest.mark.anyio
async def test_handler_returns_snapshot(self) -> None:
- """When workflow handler exists, return its snapshot."""
+ """When workflow handler exists, return lightweight list summaries."""
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
server = AgentWebSocketServer.__new__(AgentWebSocketServer)
@@ -142,13 +142,67 @@ class TestHandleCommandWorkflows:
wire = json.loads(ws.sent[0])
payload = self._extract_payload_from_wire(wire)
assert payload["type"] == "workflow_run_snapshot"
- assert payload["workflows"] == snapshot_data
+ assert payload["action"] == "list"
+ assert len(payload["workflows"]) == len(snapshot_data)
+ assert payload["workflows"][0]["id"] == "wf_1"
+ assert payload["workflows"][0]["detail_pending"] is True
+ assert "truncated" not in payload["workflows"][0]
assert payload["session_id"] == "sess-2"
+ @pytest.mark.anyio
+ async def test_handler_get_returns_workflow_detail(self) -> None:
+ """action=get returns one workflow with full detail payload."""
+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ ws = _FakeWS()
+ request = _make_request(session_id="sess-get", channel_id="cli")
+ request.params = {"action": "get", "workflow_id": "wf_1"}
+ send_lock = asyncio.Lock()
+
+ snapshot_data = [
+ {
+ "id": "wf_1",
+ "name": "research-flow",
+ "status": "completed",
+ "phases": [
+ {
+ "id": "phase-1",
+ "name": "main",
+ "status": "completed",
+ "agents": [
+ {
+ "id": "agent-1",
+ "name": "writer",
+ "status": "completed",
+ "prompt": "hello world",
+ "outcome": "done",
+ }
+ ],
+ }
+ ],
+ }
+ ]
+ fake_handler = _FakeWorkflowHandler(snapshot=snapshot_data)
+ fake_tm = _FakeTeamManager(workflow_handler=fake_handler)
+
+ with patch(
+ "jiuwenswarm.agents.harness.team.get_team_manager",
+ return_value=fake_tm,
+ ):
+ await server._handle_command_workflows(ws, request, send_lock)
+
+ payload = self._extract_payload_from_wire(json.loads(ws.sent[0]))
+ assert payload["type"] == "workflow_run_detail"
+ assert payload["action"] == "get"
+ workflow = payload["workflow"]
+ assert workflow["id"] == "wf_1"
+ assert workflow["phases"][0]["agents"][0]["prompt"] == "hello world"
+
@pytest.mark.anyio
async def test_handler_bounds_large_snapshot_response(self, monkeypatch) -> None:
"""Large workflow snapshots should not exceed the configured wire budget."""
- from jiuwenswarm.server import agent_ws_server as agent_ws_server_module
+ from jiuwenswarm.server import wire_truncate as wire_truncate_module
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
server = AgentWebSocketServer.__new__(AgentWebSocketServer)
@@ -170,7 +224,7 @@ class TestHandleCommandWorkflows:
fake_handler = _FakeWorkflowHandler(snapshot=snapshot_data)
fake_tm = _FakeTeamManager(workflow_handler=fake_handler)
- monkeypatch.setattr(agent_ws_server_module, "_WORKFLOW_SNAPSHOT_MAX_BYTES", 8192)
+ monkeypatch.setattr(wire_truncate_module, "_WORKFLOW_SNAPSHOT_MAX_BYTES", 8192)
with patch(
"jiuwenswarm.agents.harness.team.get_team_manager",
@@ -186,14 +240,14 @@ class TestHandleCommandWorkflows:
assert payload["type"] == "workflow_run_snapshot"
assert payload["session_id"] == "sess-large-workflow"
assert payload["workflows"]
- assert len(payload["workflows"]) < len(snapshot_data)
- assert payload["workflows"][0]["description"].endswith("[truncated]")
- assert payload["truncated"] is True
+ assert len(payload["workflows"]) == len(snapshot_data)
+ assert payload["workflows"][0]["detail_pending"] is True
+ assert payload["truncated"] is False
@pytest.mark.anyio
async def test_handler_preserves_too_large_first_snapshot_as_placeholder(self, monkeypatch) -> None:
"""A huge first workflow should be represented instead of dropped."""
- from jiuwenswarm.server import agent_ws_server as agent_ws_server_module
+ from jiuwenswarm.server import wire_truncate as wire_truncate_module
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
server = AgentWebSocketServer.__new__(AgentWebSocketServer)
@@ -213,7 +267,7 @@ class TestHandleCommandWorkflows:
fake_handler = _FakeWorkflowHandler(snapshot=snapshot_data)
fake_tm = _FakeTeamManager(workflow_handler=fake_handler)
- monkeypatch.setattr(agent_ws_server_module, "_WORKFLOW_SNAPSHOT_MAX_BYTES", 2048)
+ monkeypatch.setattr(wire_truncate_module, "_WORKFLOW_SNAPSHOT_MAX_BYTES", 2048)
with patch(
"jiuwenswarm.agents.harness.team.get_team_manager",
@@ -226,17 +280,17 @@ class TestHandleCommandWorkflows:
payload = self._extract_payload_from_wire(json.loads(ws.sent[0]))
assert len(payload["workflows"]) == 1
- assert payload["workflows"][0]["truncated"] is True
+ assert payload["workflows"][0]["detail_pending"] is True
assert payload["workflows"][0]["id"].startswith("wf-too-large-")
assert payload["workflows"][0]["status"] == "running"
- assert payload["truncated"] is True
+ assert payload["workflows"][0]["name"] == "workflow-too-large"
@pytest.mark.anyio
async def test_handler_degrades_to_id_placeholder_when_minimal_exceeds_budget(
self, monkeypatch
) -> None:
"""When even the minimal snapshot exceeds budget, fall back to {id, truncated}."""
- from jiuwenswarm.server import agent_ws_server as agent_ws_server_module
+ from jiuwenswarm.server import wire_truncate as wire_truncate_module
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
server = AgentWebSocketServer.__new__(AgentWebSocketServer)
@@ -264,7 +318,7 @@ class TestHandleCommandWorkflows:
fake_handler = _FakeWorkflowHandler(snapshot=snapshot_data)
fake_tm = _FakeTeamManager(workflow_handler=fake_handler)
- monkeypatch.setattr(agent_ws_server_module, "_WORKFLOW_SNAPSHOT_MAX_BYTES", 2048)
+ monkeypatch.setattr(wire_truncate_module, "_WORKFLOW_SNAPSHOT_MAX_BYTES", 2048)
with patch(
"jiuwenswarm.agents.harness.team.get_team_manager",
@@ -272,18 +326,21 @@ class TestHandleCommandWorkflows:
):
await server._handle_command_workflows(ws, request, send_lock)
- encoded_size = len(ws.sent[0].encode("utf-8"))
- assert encoded_size <= 2048
-
payload = self._extract_payload_from_wire(json.loads(ws.sent[0]))
+ budget = max(
+ wire_truncate_module._TEAM_HISTORY_MIN_MAX_BYTES,
+ wire_truncate_module._WORKFLOW_SNAPSHOT_MAX_BYTES
+ - wire_truncate_module._WORKFLOW_SNAPSHOT_FRAME_OVERHEAD_BYTES,
+ )
+ payload_size = wire_truncate_module._json_wire_size(payload)
+ assert payload_size <= budget
+
assert len(payload["workflows"]) == 1
- assert payload["truncated"] is True
first = payload["workflows"][0]
- assert first["truncated"] is True
+ assert first["detail_pending"] is True
assert first["id"].startswith("wf-min-")
- # Minimal fields are dropped once degraded to the id-only placeholder.
- assert "name" not in first
- assert "status" not in first
+ assert first.get("name")
+ assert first.get("status")
@pytest.mark.anyio
async def test_handler_exception_returns_empty_snapshot(self) -> None:
@@ -429,9 +486,9 @@ class TestHandleCommandWorkflows:
def _find_payload_recursive(data: Any) -> dict[str, Any]:
- """Recursively search for a dict with 'type' == 'workflow_run_snapshot'."""
+ """Recursively search for a workflow list/detail payload dict."""
if isinstance(data, dict):
- if data.get("type") == "workflow_run_snapshot":
+ if data.get("type") in ("workflow_run_snapshot", "workflow_run_detail", "workflow_human_prompt"):
return data
for v in data.values():
result = _find_payload_recursive(v)
@@ -470,3 +527,107 @@ class TestCommandWorkflowsDispatch:
await server._handle_command_workflows(ws, request, send_lock)
server._handle_command_workflows.assert_called_once_with(ws, request, send_lock)
+
+
+class TestWorkflowHumanPromptWireHelpers:
+ def test_collapse_preserves_full_waiting_human_prompt(self) -> None:
+ from jiuwenswarm.server.wire_truncate import (
+ _build_workflow_detail_payload,
+ _collapse_oversized_workflow_snapshot_item,
+ )
+
+ long_question = "Q-" + ("x" * 5000)
+ workflow = {
+ "id": "wf-human",
+ "name": "party-planner",
+ "status": "running",
+ "phases": [
+ {
+ "id": "phase-1",
+ "name": "main",
+ "status": "running",
+ "agents": [
+ {
+ "id": "agent-wait",
+ "name": "human_baby",
+ "status": "waiting_for_human",
+ "kind": "human",
+ "correlation_id": "main:human_baby:1",
+ "human_prompt": long_question,
+ },
+ *[
+ {
+ "id": f"agent-{idx}",
+ "name": f"worker-{idx}",
+ "status": "completed",
+ "kind": "agent",
+ "prompt": "p" * 8000,
+ "outcome": "o" * 8000,
+ }
+ for idx in range(12)
+ ],
+ ],
+ }
+ ],
+ }
+
+ collapsed = _collapse_oversized_workflow_snapshot_item(workflow)
+ waiting = collapsed["phases"][0]["agents"][0]
+ assert waiting["human_prompt"] == long_question
+ assert "[truncated]" not in waiting["human_prompt"]
+
+ detail = _build_workflow_detail_payload(workflow, session_id="sess-human")
+ detail_waiting = detail["workflow"]["phases"][0]["agents"][0]
+ assert detail_waiting["human_prompt"] == long_question
+
+ @pytest.mark.anyio
+ async def test_get_human_prompt_action_returns_full_text(self) -> None:
+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ ws = _FakeWS()
+ request = _make_request(session_id="sess-human", channel_id="web")
+ request.params = {
+ "action": "get_human_prompt",
+ "workflow_id": "wf_human",
+ "agent_id": "agent-wait",
+ }
+ send_lock = asyncio.Lock()
+
+ long_question = "Approve?" + ("!" * 4000)
+ snapshot_data = [
+ {
+ "id": "wf_human",
+ "name": "party-planner",
+ "status": "running",
+ "phases": [
+ {
+ "id": "phase-1",
+ "name": "main",
+ "status": "running",
+ "agents": [
+ {
+ "id": "agent-wait",
+ "name": "human_baby",
+ "status": "waiting_for_human",
+ "kind": "human",
+ "human_prompt": long_question,
+ }
+ ],
+ }
+ ],
+ }
+ ]
+ fake_handler = _FakeWorkflowHandler(snapshot=snapshot_data)
+ fake_tm = _FakeTeamManager(workflow_handler=fake_handler)
+
+ with patch(
+ "jiuwenswarm.agents.harness.team.get_team_manager",
+ return_value=fake_tm,
+ ):
+ await server._handle_command_workflows(ws, request, send_lock)
+
+ assert len(ws.sent) == 1
+ payload = TestHandleCommandWorkflows()._extract_payload_from_wire(json.loads(ws.sent[0]))
+ assert payload["type"] == "workflow_human_prompt"
+ assert payload["human_prompt"] == long_question
diff --git a/tests/unit_tests/agentserver/test_history_payload_limits.py b/tests/unit_tests/agentserver/test_history_payload_limits.py
index 9c2f6171ab..87bf630fab 100644
--- a/tests/unit_tests/agentserver/test_history_payload_limits.py
+++ b/tests/unit_tests/agentserver/test_history_payload_limits.py
@@ -163,9 +163,11 @@ def test_history_get_sanitizes_large_restorable_records(monkeypatch):
message = result["messages"][0]
assert message["content"].endswith("[truncated]")
assert message["tool_result"]["result"].endswith("[truncated]")
+ from jiuwenswarm.server import wire_truncate as wire_truncate_module
+
assert (
len(json.dumps(message, ensure_ascii=False).encode("utf-8"))
- <= getattr(agent_ws_server_module, "_HISTORY_WIRE_RECORD_MAX_BYTES")
+ <= getattr(wire_truncate_module, "_HISTORY_WIRE_RECORD_MAX_BYTES")
)
diff --git a/tests/unit_tests/agentserver/test_swarmflow_reply_rpc.py b/tests/unit_tests/agentserver/test_swarmflow_reply_rpc.py
new file mode 100644
index 0000000000..1b30d0e06a
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_swarmflow_reply_rpc.py
@@ -0,0 +1,68 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for handle_swarmflow_reply — adapter-side early validation.
+
+Happy-path delivery builds a HumanAgentMessage via agent-core helpers
+(``format_swarmflow_human_reply_target`` / ``HumanAgentMessage``); those
+symbols are version-sensitive and are not pinned here. This suite only
+covers the missing-params short-circuit that stays inside jiuwenswarm.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+
+from jiuwenswarm.common.schema.agent import AgentRequest
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+
+
+def _make_handler() -> JiuWenSwarmDeepAdapter:
+ """Bypass the heavy __init__; only the handler needs the session-scoped flag."""
+ adapter = JiuWenSwarmDeepAdapter.__new__(JiuWenSwarmDeepAdapter)
+ adapter._is_session_scoped_adapter = True
+ return adapter
+
+
+class _FakeTeamManager:
+ """Captures the interact() call; returns a configurable (ok, reason)."""
+
+ def __init__(self, ok: bool = True, reason: str | None = None) -> None:
+ self.ok = ok
+ self.reason = reason
+ self.calls: list[tuple[str, object]] = []
+
+ async def interact(self, session_id: str, user_input: object) -> tuple[bool, str | None]:
+ self.calls.append((session_id, user_input))
+ return self.ok, self.reason
+
+
+def _req(**params) -> AgentRequest:
+ return AgentRequest(
+ request_id="req-1",
+ channel_id="tui",
+ session_id=params.get("session_id", "sess-1"),
+ req_method=None,
+ params=params,
+ )
+
+
+async def test_handle_swarmflow_reply_rejects_missing_fields():
+ """Missing session_id / correlation_id / answer short-circuits with an error."""
+ handler = _make_handler()
+ tm = _FakeTeamManager()
+ with patch(
+ "jiuwenswarm.agents.harness.team.get_team_manager", return_value=tm
+ ):
+ # No answer -> no interact call, error payload.
+ resp = await handler.handle_swarmflow_reply(_req(
+ session_id="sess-1",
+ run_id="run-1",
+ correlation_id="review:host:0",
+ answer="",
+ ))
+ assert resp.ok is False
+ assert resp.payload == {"ok": False, "error": "missing session_id/correlation_id/answer"}
+ assert tm.calls == []
diff --git a/tests/unit_tests/agentserver/test_workflow_monitor_handler.py b/tests/unit_tests/agentserver/test_workflow_monitor_handler.py
index e6ea210cd4..44679aff39 100644
--- a/tests/unit_tests/agentserver/test_workflow_monitor_handler.py
+++ b/tests/unit_tests/agentserver/test_workflow_monitor_handler.py
@@ -420,3 +420,35 @@ class TestWorkflowMonitorHandlerRunIdRegistry:
assert len(runs) == 1
assert run_id in runs
assert runs[run_id].id == run_id
+
+
+# ---------------------------------------------------------------------------
+# New-field passthrough (agent_id / node_type / correlation_id / answer)
+# ---------------------------------------------------------------------------
+
+class TestExtractProgressPassthrough:
+ """_extract_progress passes the new fields through the dict payload path.
+
+ Agent-core EventMessage / WorkflowProgressTeamEvent shapes vary by package
+ version; those paths are not pinned here.
+ """
+
+ @staticmethod
+ def test_dict_payload_passes_new_fields() -> None:
+ """dict path: WorkflowProgress(**payload) covers the new fields."""
+ handler = WorkflowMonitorHandler(monitor=_FakeTeamMonitor(), session_id="s")
+ payload = {
+ "kind": "agent_started",
+ "phase": "review",
+ "label": "host",
+ "agent_id": "main/call:1",
+ "node_type": "human_session",
+ "correlation_id": "review:host:0",
+ "answer": "yes, approved",
+ }
+ progress = handler._extract_progress(SimpleNamespace(payload=payload))
+ assert progress is not None
+ assert progress.agent_id == "main/call:1"
+ assert progress.node_type == "human_session"
+ assert progress.correlation_id == "review:host:0"
+ assert progress.answer == "yes, approved"
diff --git a/tests/unit_tests/agentserver/test_workflow_schema.py b/tests/unit_tests/agentserver/test_workflow_schema.py
index 87c565e28d..eb3ddbe2da 100644
--- a/tests/unit_tests/agentserver/test_workflow_schema.py
+++ b/tests/unit_tests/agentserver/test_workflow_schema.py
@@ -12,4 +12,18 @@ def test_req_method_command_workflows():
def test_event_type_workflow_updated():
"""Verify WORKFLOW_UPDATED enum value exists with correct string."""
- assert EventType.WORKFLOW_UPDATED.value == "workflow.updated"
\ No newline at end of file
+ assert EventType.WORKFLOW_UPDATED.value == "workflow.updated"
+
+
+def test_req_method_chat_swarmflow_reply():
+ """Verify CHAT_SWARMFLOW_REPLY enum value exists with correct string."""
+ assert ReqMethod.CHAT_SWARMFLOW_REPLY.value == "chat.swarmflow_reply"
+
+
+def test_swarmflow_reply_params_typeddict_keys():
+ """SwarmflowReplyParams declares the expected keys (total=False => all optional)."""
+ from jiuwenswarm.common.schema.swarmflow_reply import SwarmflowReplyParams
+
+ hints = SwarmflowReplyParams.__annotations__
+ for key in ("session_id", "team_name", "run_id", "correlation_id", "answer"):
+ assert key in hints, f"missing key {key}"
\ No newline at end of file
diff --git a/tests/unit_tests/agentserver/test_workflow_state.py b/tests/unit_tests/agentserver/test_workflow_state.py
index 8a8397ce63..b92e5adac4 100644
--- a/tests/unit_tests/agentserver/test_workflow_state.py
+++ b/tests/unit_tests/agentserver/test_workflow_state.py
@@ -417,4 +417,389 @@ class TestIDGeneration:
state.apply(_make_progress("workflow_started", workflow_name="test"))
progress = _make_progress("unknown_kind")
delta = state.apply(progress)
- assert delta is None
\ No newline at end of file
+ assert delta is None
+
+
+class TestAgentIdResolution:
+ """agent_id / correlation_id exact matching for same-label nodes."""
+
+ @staticmethod
+ def test_for_loop_same_label_completed_lands_on_correct_instance():
+ """A 2nd loop iteration's completion matches its own agent_id, not the 1st."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="loop"))
+ state.apply(_make_progress("agent_started", phase="p", label="x", agent_id="path/call:1"))
+ state.apply(_make_progress("agent_started", phase="p", label="x", agent_id="path/call:2"))
+ # Complete the 2nd node — must land on instance #2, leaving #1 running.
+ state.apply(_make_progress("agent_completed", phase="p", label="x", agent_id="path/call:2", outcome="done2"))
+ a1, a2 = state.phases[0].agents
+ assert a1.status == "running"
+ assert a2.status == "completed"
+ assert a2.outcome == "done2"
+ assert state.phases[0].completed_agent_count == 1
+
+ @staticmethod
+ def test_agent_session_multi_turn_each_unique_agent_id():
+ """agent_session multi-turn: each turn gets a distinct agent_id + kind=agent + correlation_id."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="sess"))
+ for i in (1, 2, 3):
+ state.apply(_make_progress(
+ "agent_started", phase="review", label="chat",
+ agent_id=f"main/call:{i}", node_type="agent_session",
+ correlation_id=f"review:chat:{i - 1}",
+ ))
+ assert len(state.phases[0].agents) == 3
+ ids = [a.id for a in state.phases[0].agents]
+ assert len(set(ids)) == 3
+ assert all(a.kind == "agent" for a in state.phases[0].agents)
+ assert [a.correlation_id for a in state.phases[0].agents] == [
+ "review:chat:0", "review:chat:1", "review:chat:2",
+ ]
+
+ @staticmethod
+ def test_human_session_multi_turn_correlation_id_locates_node():
+ """human_session multi-turn: HUMAN_PROMPT/REPLIED locate the node by correlation_id (no phase)."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="h"))
+ state.apply(_make_progress(
+ "agent_started", phase="review", label="host",
+ agent_id="main/call:5", node_type="human_session", correlation_id="review:host:0",
+ ))
+ state.apply(_make_progress(
+ "agent_started", phase="review", label="host",
+ agent_id="main/call:7", node_type="human_session", correlation_id="review:host:1",
+ ))
+ # HUMAN_PROMPT for turn 1 (no phase field) -> matches turn-1 node by correlation_id.
+ state.apply(_make_progress(
+ "human_prompt", label="host", correlation_id="review:host:1", prompt="ok?",
+ ))
+ a0, a1 = state.phases[0].agents
+ assert a0.status == "running"
+ assert a1.status == "waiting_for_human"
+ assert a1.human_prompt == "ok?"
+ assert a1.kind == "human"
+ # HUMAN_REPLIED clears waiting, stores answer.
+ state.apply(_make_progress(
+ "human_replied", label="host", correlation_id="review:host:1", answer="yes",
+ ))
+ assert a1.status == "running"
+ assert a1.human_reply == "yes"
+
+ @staticmethod
+ def test_human_prompt_and_replied_do_not_append_activity():
+ """Human nodes never produce WorkflowAgentActivity (question/answer live on the node)."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="h"))
+ state.apply(_make_progress(
+ "agent_started", phase="review", label="host",
+ agent_id="main/call:1", node_type="human_session", correlation_id="review:host:0",
+ ))
+ state.apply(_make_progress("human_prompt", label="host", correlation_id="review:host:0", prompt="q"))
+ state.apply(_make_progress("human_replied", label="host", correlation_id="review:host:0", answer="a"))
+ agent = state.phases[0].agents[0]
+ assert agent.activity == []
+
+ @staticmethod
+ def test_legacy_event_without_agent_id_falls_back_to_last_non_terminal():
+ """Old agent-core events (no agent_id) fall back to label + last non-terminal."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="legacy"))
+ # No agent_id on any event (legacy).
+ state.apply(_make_progress("agent_started", phase="p", label="x"))
+ state.apply(_make_progress("agent_started", phase="p", label="x"))
+ # The 1st is still running; completion lands on the last non-terminal (instance #2).
+ state.apply(_make_progress("agent_completed", phase="p", label="x", outcome="done2"))
+ a1, a2 = state.phases[0].agents
+ assert a2.status == "completed"
+ assert a2.outcome == "done2"
+
+ @staticmethod
+ def test_waiting_for_human_finalized_to_stopped_on_teardown():
+ """finalize_if_running closes a waiting_for_human node to stopped (no perpetual spin)."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="h"))
+ state.apply(_make_progress(
+ "agent_started", phase="review", label="host",
+ agent_id="main/call:1", node_type="human_session", correlation_id="review:host:0",
+ ))
+ state.apply(_make_progress("human_prompt", label="host", correlation_id="review:host:0", prompt="q"))
+ agent = state.phases[0].agents[0]
+ assert agent.status == "waiting_for_human"
+ # Teardown without a reply.
+ changed = state.finalize_if_running("stopped")
+ assert changed is True
+ assert agent.status == "stopped"
+ assert state.status == "stopped"
+
+
+class TestPhaseReuseAndJump:
+ """Same-name phase card is reused; status may jump; counters accumulate."""
+
+ @staticmethod
+ def test_same_name_phase_reused_not_duplicated():
+ """Re-entering a same-name phase reuses the one card, not a new one."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="iter"))
+ state.apply(_make_progress("agent_started", phase="数据采集", label="a", agent_id="c:1"))
+ assert len(state.phases) == 1
+ # Round 2: same phase name arrives again -> reuse, not a new card.
+ state.apply(_make_progress("agent_started", phase="数据采集", label="a", agent_id="c:2"))
+ assert len(state.phases) == 1
+ assert state.phases[0].status == "running"
+ # Two agents accumulated on the same card.
+ assert len(state.phases[0].agents) == 2
+
+ @staticmethod
+ def test_phase_status_jumps_completed_back_to_running():
+ """A phase sealed to completed flips back to running when re-entered.
+
+ A phase is sealed only when a *different-name* phase is entered. So the
+ jump test interleaves a different-name phase to seal P, then re-enters P.
+ """
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="iter"))
+ state.apply(_make_progress("agent_started", phase="P", label="a", agent_id="c:1"))
+ agent_a = None
+ for ph in state.phases:
+ for ag in ph.agents:
+ if ag.name == "a":
+ agent_a = ag
+ assert agent_a is not None and agent_a.status == "running"
+ # Enter a different-name phase -> seals P to completed (finalizes running agents).
+ state.apply(_make_progress("agent_started", phase="Q", label="b", agent_id="c:2"))
+ p, q = state.phases
+ assert p.status == "completed"
+ assert q.status == "running"
+ # agent1 (label=a) was running in P; sealing P finalized it to completed.
+ assert agent_a.status == "completed"
+ assert agent_a.completed_at is not None
+ # Re-enter P (same name) -> jumps back to running, same card.
+ state.apply(_make_progress("agent_started", phase="P", label="c", agent_id="c:3"))
+ assert len(state.phases) == 2 # no new card
+ assert p.status == "running" # jumped back from completed
+ # P now holds agent1 (completed) + agent3 (running).
+ assert len(p.agents) == 2
+ assert p.agents[0].status == "completed" # agent1
+ assert p.agents[1].status == "running" # agent3
+ # agent1 (label=a) still completed — the jump does not revive finalized agents.
+ assert agent_a.status == "completed"
+ assert agent_a.name == "a"
+
+ @staticmethod
+ def test_agent_count_accumulates_across_iterations():
+ """agent_count / completed_agent_count keep accumulating on the reused card."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="iter"))
+ # Round 1: 2 agents, both complete.
+ state.apply(_make_progress("agent_started", phase="P", label="a", agent_id="c:1"))
+ state.apply(_make_progress("agent_completed", phase="P", label="a", agent_id="c:1", outcome="o1"))
+ state.apply(_make_progress("agent_started", phase="P", label="b", agent_id="c:2"))
+ state.apply(_make_progress("agent_completed", phase="P", label="b", agent_id="c:2", outcome="o2"))
+ assert state.phases[0].agent_count == 2
+ assert state.phases[0].completed_agent_count == 2
+ # Round 2: 1 more agent on the same card.
+ state.apply(_make_progress("agent_started", phase="P", label="a", agent_id="c:3"))
+ assert state.phases[0].agent_count == 3
+ assert state.phases[0].completed_agent_count == 2 # round-2 agent still running
+ state.apply(_make_progress("agent_completed", phase="P", label="a", agent_id="c:3", outcome="o3"))
+ assert state.phases[0].agent_count == 3
+ assert state.phases[0].completed_agent_count == 3 # accumulated
+
+ @staticmethod
+ def test_different_name_phase_still_seals_previous():
+ """Switching to a different-name phase still seals the running previous one."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="iter"))
+ state.apply(_make_progress("agent_started", phase="采集", label="a", agent_id="c:1"))
+ state.apply(_make_progress("agent_started", phase="计算", label="b", agent_id="c:2"))
+ assert state.phases[0].status == "completed" # 采集 sealed
+ assert state.phases[1].status == "running" # 计算 active
+ assert len(state.phases) == 2
+
+ @staticmethod
+ def test_completed_phase_can_jump_back_to_running_then_re_sealed():
+ """A re-entered completed phase jumps to running; a later switch re-seals it."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="iter"))
+ state.apply(_make_progress("agent_started", phase="P", label="a", agent_id="c:1"))
+ state.apply(_make_progress("agent_started", phase="Q", label="b", agent_id="c:2")) # seal P
+ state.apply(_make_progress("agent_started", phase="P", label="c", agent_id="c:3")) # jump P back
+ p, q = state.phases
+ assert p.status == "running"
+ # Switch to a different name again -> P sealed again (still one card).
+ state.apply(_make_progress("agent_started", phase="R", label="d", agent_id="c:4"))
+ assert p.status == "completed"
+ assert len(state.phases) == 3
+
+
+class TestAgentOutcomeBackfill:
+ """Outcome persistence when phase seal or agent_id mismatch occurs."""
+
+ @staticmethod
+ def test_agent_completed_backfills_outcome_after_phase_seal():
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="seal"))
+ state.apply(_make_progress("agent_started", phase="P1", label="worker", agent_id="engine:1"))
+ state.apply(_make_progress("agent_started", phase="P2", label="next", agent_id="engine:2"))
+ sealed = state.phases[0].agents[0]
+ assert sealed.status == "completed"
+ assert sealed.outcome is None
+ assert state.phases[0].completed_agent_count == 0
+ state.apply(_make_progress(
+ "agent_completed", phase="P1", label="worker", agent_id="engine:1", outcome="done",
+ ))
+ assert sealed.outcome == "done"
+ assert state.phases[0].completed_agent_count == 1
+
+ @staticmethod
+ def test_agent_completed_backfills_when_agent_id_mismatch():
+ """Slug id from agent_started without engine id + late agent_completed by label."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="mismatch"))
+ state.apply(_make_progress("agent_started", phase="P", label="worker"))
+ assert state.phases[0].agents[0].id == "worker-1"
+ state.apply(_make_progress("agent_started", phase="Q", label="other", agent_id="engine:2"))
+ sealed = state.phases[0].agents[0]
+ assert sealed.status == "completed"
+ assert sealed.outcome is None
+ state.apply(_make_progress(
+ "agent_completed", phase="P", label="worker", agent_id='[["call", 0]]', outcome="payload",
+ ))
+ assert sealed.outcome == "payload"
+ assert state.phases[0].completed_agent_count == 1
+
+ @staticmethod
+ def test_duplicate_agent_completed_is_idempotent():
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="dup"))
+ state.apply(_make_progress("agent_started", phase="P", label="a", agent_id="c:1"))
+ first = state.apply(_make_progress(
+ "agent_completed", phase="P", label="a", agent_id="c:1", outcome="once",
+ ))
+ assert first is not None
+ assert state.phases[0].completed_agent_count == 1
+ second = state.apply(_make_progress(
+ "agent_completed", phase="P", label="a", agent_id="c:1", outcome="twice",
+ ))
+ assert second is None
+ assert state.phases[0].agents[0].outcome == "once"
+ assert state.phases[0].completed_agent_count == 1
+
+
+class TestAgentNodeType:
+ """Explicit node_type from AGENT_STARTED is persisted on WorkflowAgentState."""
+
+ @staticmethod
+ def test_agent_started_persists_node_type():
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="types"))
+ state.apply(_make_progress(
+ "agent_started",
+ phase="P1",
+ label="coder",
+ node_type="agent_session",
+ correlation_id="P1:coder:0",
+ ))
+ agent = state.phases[0].agents[0]
+ assert agent.node_type == "agent_session"
+ assert agent.to_dict()["node_type"] == "agent_session"
+
+ @staticmethod
+ def test_agent_started_without_node_type_remains_optional():
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="legacy"))
+ state.apply(_make_progress("agent_started", phase="P1", label="legacy-agent"))
+ agent = state.phases[0].agents[0]
+ assert agent.node_type is None
+ assert "node_type" not in agent.to_dict()
+
+ @staticmethod
+ def test_restored_agent_state_keeps_node_type():
+ raw = WorkflowAgentState(
+ id="sess-1",
+ name="reviewer",
+ node_type="human_session",
+ kind="human",
+ correlation_id="P1:reviewer:0",
+ )
+ assert raw.model_dump(exclude_none=True)["node_type"] == "human_session"
+
+ @staticmethod
+ def test_kind_derived_from_node_type():
+ """kind is derived from node_type (no is_human): human/human_session -> human, else agent."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="kinds"))
+ cases = [
+ ("agent", "agent"),
+ ("agent_session", "agent"),
+ ("human", "human"),
+ ("human_session", "human"),
+ ]
+ for i, (nt, expected_kind) in enumerate(cases):
+ state.apply(_make_progress(
+ "agent_started", phase="P1", label=f"n{i}",
+ agent_id=f"main/call:{i}", node_type=nt,
+ correlation_id=f"P1:n{i}:0",
+ ))
+ agent = state.phases[0].agents[i]
+ assert agent.node_type == nt, f"node_type {nt} not persisted"
+ assert agent.kind == expected_kind, f"node_type={nt} should derive kind={expected_kind}, got {agent.kind}"
+
+ @staticmethod
+ def test_kind_defaults_to_agent_when_node_type_missing():
+ """Legacy AGENT_STARTED with node_type=None derives kind=agent (pre-change default)."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="legacy"))
+ state.apply(_make_progress("agent_started", phase="P1", label="legacy-agent"))
+ agent = state.phases[0].agents[0]
+ assert agent.node_type is None
+ assert agent.kind == "agent"
+
+ @staticmethod
+ def test_label_less_human_node_falls_back_to_human_not_agent():
+ """A ``human()`` / ``human_session()`` node started with no label surfaces
+ as "unnamed human" (not the misleading bare "agent") so the TUI
+ pending-reply list is readable. Plain ``agent()`` falls back to
+ "unnamed agent". The ``unnamed `` prefix marks placeholder values."""
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="nolabel"))
+ state.apply(_make_progress(
+ "agent_started", phase="P1", agent_id="main/call:0",
+ node_type="human", correlation_id="P1::0",
+ ))
+ state.apply(_make_progress(
+ "agent_started", phase="P1", agent_id="main/call:1",
+ node_type="human_session", correlation_id="P1::1",
+ ))
+ state.apply(_make_progress(
+ "agent_started", phase="P1", agent_id="main/call:2",
+ ))
+ agents = state.phases[0].agents
+ assert agents[0].name == "unnamed human"
+ assert agents[0].kind == "human"
+ assert agents[1].name == "unnamed human"
+ assert agents[1].kind == "human"
+ assert agents[2].name == "unnamed agent"
+ assert agents[2].kind == "agent"
+
+ @staticmethod
+ def test_phase_less_node_falls_back_to_unnamed_phase():
+ """A node whose event carries no ``phase`` lands on a placeholder phase
+ card named "unnamed phase" (replacing the cryptic "?"). All phase-less
+ nodes share that one card — same-name phases are reused."""
+ from jiuwenswarm.agents.harness.team.handlers.workflow_state import _UNNAMED_PHASE
+ state = WorkflowRunState()
+ state.apply(_make_progress("workflow_started", workflow_name="nophase"))
+ state.apply(_make_progress(
+ "agent_started", label="coder", agent_id="main/call:0", node_type="agent",
+ ))
+ state.apply(_make_progress(
+ "agent_started", label="reviewer", agent_id="main/call:1", node_type="human",
+ correlation_id="nophase:reviewer:0",
+ ))
+ assert len(state.phases) == 1
+ assert state.phases[0].name == _UNNAMED_PHASE == "unnamed phase"
+ assert state.phases[0].status == "running"
+ assert [a.name for a in state.phases[0].agents] == ["coder", "reviewer"]
+ assert state.phases[0].agent_count == 2
\ No newline at end of file
diff --git a/tests/unit_tests/gateway/test_agent_request_timeout_policy.py b/tests/unit_tests/gateway/test_agent_request_timeout_policy.py
index 27627fb9ff..ea0e9dc4af 100644
--- a/tests/unit_tests/gateway/test_agent_request_timeout_policy.py
+++ b/tests/unit_tests/gateway/test_agent_request_timeout_policy.py
@@ -60,6 +60,48 @@ def test_resolve_timeout_extends_known_permissions_methods_for_older_clients():
) == 55.0
+def test_resolve_timeout_extends_command_workflows_for_older_clients():
+ assert resolve_agent_request_timeout_seconds(
+ channel_id="tui",
+ method="command.workflows",
+ is_stream=False,
+ ) == 55.0
+
+
+def test_resolve_timeout_keeps_most_of_client_window_for_command_workflows():
+ # 30s client → 28s gateway (2s grace); not the flat 5s cut used elsewhere.
+ assert resolve_agent_request_timeout_seconds(
+ channel_id="tui",
+ method="command.workflows",
+ is_stream=False,
+ client_timeout_ms=30_000,
+ ) == 28.0
+ assert resolve_agent_request_timeout_seconds(
+ channel_id="tui",
+ method="command.workflows",
+ is_stream=False,
+ client_timeout_ms=10_000,
+ ) == 8.0
+
+
+def test_resolve_timeout_exempts_swarmflow_reply_from_unary_cap():
+ """A swarmflow human reply tracks the human-turn timeout (600s default),
+ so it must not be capped by the TUI 25s/55s unary limit."""
+ assert resolve_agent_request_timeout_seconds(
+ channel_id="tui",
+ method="chat.swarmflow_reply",
+ is_stream=False,
+ ) is None
+ # Even when a client passes a short client_timeout_ms, the exempt method
+ # stays uncapped (the reply is async and must outlive the cap).
+ assert resolve_agent_request_timeout_seconds(
+ channel_id="tui",
+ method="chat.swarmflow_reply",
+ is_stream=False,
+ client_timeout_ms=1_000,
+ ) is None
+
+
def test_request_timeout_from_envelope_accepts_metadata_fallback():
env = SimpleNamespace(
channel="tui",
diff --git a/tests/unit_tests/gateway/test_swarmflow_reply_forward.py b/tests/unit_tests/gateway/test_swarmflow_reply_forward.py
new file mode 100644
index 0000000000..d158ca2180
--- /dev/null
+++ b/tests/unit_tests/gateway/test_swarmflow_reply_forward.py
@@ -0,0 +1,123 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Forward-layer tests for chat.swarmflow_reply.
+
+The reply rides the standard 3-layer chain: TUI empty ack -> message_handler
+forward -> process_message -> handle_swarmflow_reply. These tests pin the two
+gateway-side invariants:
+
+1. A swarmflow reply must NOT cancel an in-flight leader stream (the cancel gate
+ only fires for CHAT_SEND).
+2. A swarmflow reply is forwarded to the AgentServer as a non-stream request
+ (the agent_ws_server then dispatches it to handle_swarmflow_reply).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields
+from jiuwenswarm.common.schema import Message
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler
+
+
+class _FakeAgentClient:
+ """Captures the forwarded env (proves the reply reached the AgentServer)."""
+
+ def __init__(self) -> None:
+ self.sent: list[object] = []
+
+ async def send_request(self, env: object) -> SimpleNamespace:
+ self.sent.append(env)
+ return SimpleNamespace(
+ request_id="r1",
+ channel_id="tui",
+ ok=True,
+ payload={"ok": True},
+ metadata=None,
+ )
+
+ @staticmethod
+ async def send_request_stream(env: object): # pragma: no cover
+ if False:
+ yield env
+
+
+class _TestMessageHandler(MessageHandler):
+ @classmethod
+ def create(cls) -> "_TestMessageHandler":
+ setattr(MessageHandler, "_instance", None)
+ setattr(cls, "_instance", None)
+ return cls(_FakeAgentClient())
+
+ async def cancel_stream_tasks_for_channel(self, msg: Message) -> int:
+ return await getattr(self, "_cancel_stream_tasks_for_channel")(msg)
+
+
+def _swarmflow_reply_message(*, session_id: str = "sess-1") -> Message:
+ return Message(
+ id="r-sw",
+ type="req",
+ channel_id="tui",
+ session_id=session_id,
+ params={
+ "session_id": session_id,
+ "run_id": "run-1",
+ "correlation_id": "review:host:0",
+ "answer": "ok",
+ },
+ timestamp=0.0,
+ ok=True,
+ req_method=ReqMethod.CHAT_SWARMFLOW_REPLY,
+ is_stream=False,
+ )
+
+
+async def test_swarmflow_reply_does_not_cancel_existing_stream() -> None:
+ """The cancel gate is CHAT_SEND-only; a swarmflow reply leaves streams alive.
+
+ ``_cancel_stream_tasks_for_channel`` is a generic by-channel tool; the real
+ gate is ``_should_cancel_existing_stream_before_chat_send`` (called inside
+ ``_forward_loop`` before cancelling). Pinning the gate here proves a
+ swarmflow reply never triggers cancellation of an in-flight leader stream.
+ """
+ assert MessageHandler._should_cancel_existing_stream_before_chat_send(
+ _swarmflow_reply_message()
+ ) is False
+ # Contrast: a plain chat.send on the same channel WOULD cancel.
+ chat_send = Message(
+ id="r-cs", type="req", channel_id="tui", session_id="sess-1",
+ params={"mode": "agent.plan", "query": "hi"}, timestamp=0.0, ok=True,
+ req_method=ReqMethod.CHAT_SEND, is_stream=True,
+ )
+ assert MessageHandler._should_cancel_existing_stream_before_chat_send(chat_send) is True
+
+
+async def test_swarmflow_reply_forwarded_to_agent_server_non_stream() -> None:
+ """_process_non_stream_request forwards the reply env to the AgentServer client."""
+ handler = _TestMessageHandler.create()
+ msg = _swarmflow_reply_message()
+ env = e2a_from_agent_fields(
+ request_id=msg.id,
+ channel_id=msg.channel_id,
+ session_id=msg.session_id,
+ req_method=ReqMethod.CHAT_SWARMFLOW_REPLY,
+ params=msg.params,
+ is_stream=False,
+ timestamp=0.0,
+ )
+ await handler._process_non_stream_request(msg, env) # pylint: disable=protected-access
+
+ client = handler.agent_client # type: ignore[attr-defined]
+ assert len(client.sent) == 1
+ forwarded = client.sent[0]
+ # The forwarded envelope preserves the swarmflow reply method + params.
+ assert forwarded.method == ReqMethod.CHAT_SWARMFLOW_REPLY.value
+ assert forwarded.params["correlation_id"] == "review:host:0"
+ assert forwarded.params["answer"] == "ok"