Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): make a team's Lead tab the chat with its lead (#594)
Ruben Lütke717665463f14
diff --git a/docs/agent-society/team-leads.md b/docs/agent-society/team-leads.mdindex 6f539ddb4e..c126b303a9 100644--- a/docs/agent-society/team-leads.md+++ b/docs/agent-society/team-leads.md@@ -1,16 +1,18 @@# Team leadsA team (a group of agents in the Agents section) can have a **lead**: one of-its members that manages the team for the person. The person gives the team a-goal. The lead breaks it into tasks, hands each task to the member whose role-fits, checks what comes back, sends rework or re-assigns, and reports when the-goal is done. The person steps in only for what is theirs: answering a-question the lead cannot decide, continuing a paused goal, or stopping one.+its members that manages the team for the person. The person talks to the lead+in an ordinary chat and says what the team should achieve. The lead breaks it+into tasks, hands each task to the member whose role fits, checks what comes+back, sends rework or re-assigns, and reports when the goal is done. The+person steps in only for what is theirs: answering a question the lead cannot+decide, continuing a paused goal, or stopping one.Code: `jarvis/society/team_lead.py` (the engine), `jarvis/society/team_tools.py`(the lead's tools), `/api/society/chat-groups/{id}/…` in-`jarvis/ui/web/society_routes.py`, and the board in-`src/components/society/chat/TeamLeadBoard.tsx`.+`jarvis/ui/web/society_routes.py`, and the lead's view in+`src/components/society/chat/TeamLeadView.tsx` (the chat) with+`TeamLeadPanel.tsx` (the team beside it).## Naming a lead@@ -24,6 +26,32 @@ team lead because it already leads every agent.The team's **mission** is a short standing purpose. The lead reads it on everymanaging turn.+## Talking to the lead++The **Lead** tab of a team is the lead's own chat, the same conversation and+composer every agent has. There is no separate form for goals:++- **Asking for work** is a message. When the lead hands out the first task+ from it, a goal opens in the person's own words (source `chat`).+- **Answering** a question the lead asked, or telling it to go on with a+ paused goal, is a message too. The lead's tools work on that goal again+ inside the person's turn; a turn nobody typed (a check-in, another agent's+ message) can never answer for the person.+- **Reports** appear in the conversation as cards: the result of a goal, an+ interim update, a failure, or the lead's question.+- Above the composer sit the actions only a lead is asked: a status, a+ suggestion for the next goals, a look at the team, and taking the+ initiative. Each sends its sentence as the person's message.++Beside the chat, the team panel follows the work live: the goal in progress+with every task, what waits behind it, the members and what each is on, and+the finished goals. It holds the controls that are not a sentence (stop,+continue, try again) and the setup: mission, initiative, who leads.++After the person's turn the engine follows up exactly as after a managing+turn: results that landed meanwhile are reviewed, and a goal left with+nothing running and no report is asked once for a typed one.+## How a goal runs1. **Plan.** The lead gets a managing turn in its own chat with the goal, the@@ -57,8 +85,8 @@ Offered only in the chats of an agent that currently leads a team.| Tool | What it does ||---|---|-| `society_team_assign` | Hand one task to one member. Returns at once with the task's state. |-| `society_team_board` | Read the mission, the members and every open goal with its tasks. |+| `society_team_assign` | Hand one task to one member. Returns at once with the task's state. With no goal in progress it opens one; `goal` names it. |+| `society_team_board` | Read the mission, the members, every open goal with its tasks, and the goals finished most recently. || `society_team_report` | `progress`, `needs_input` (one question for the person), `done`, `failed`. |None of them starts work by itself. Assigning appends an envelope; the@@ -105,14 +133,24 @@ Both vocabularies are pinned across Python, SQL and TypeScript by`blocked`. The lead is never left waiting forever, and never hands the samework out twice because a start was slow.-## Check-ins+## Initiative++How much a lead does without being asked is the person's choice, made in the+team panel's setup:++| Way | What the lead does |+|---|---|+| Only when asked | Works when the person writes and whenever a result comes in. The default. |+| Keeps watch | Also looks at its team unprompted (every hour, every four hours, or once a day): it follows up on stuck work and starts standing duties the mission names. |+| Takes the initiative | As above, and when no goal is open it sets the team's next goal from the mission and hands out the first tasks (source `lead`). |-Off by default. When the person switches them on (every hour, every four-hours, or once a day), the lead looks at its team unprompted: it follows up on-stuck work and starts standing duties the mission names. A check-in is an-ordinary agent routine tagged `team-checkin:<team id>`, so it appears with the+A look is an ordinary agent routine tagged `team-checkin:<team id>` (and+`team-initiative:<team id>` when it may set goals), so it appears with thelead's other routines and follows the same rules for which seat may run-background work.+background work. A lead that takes the initiative stays inside every bound+below: one goal at a time, the turn budget, the task limit. With a mission+that gives it nothing to derive a goal from, it starts nothing and says what+it needs.## Drillsdiff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex 53812348b6..6da931e0f2 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -540,11 +540,30 @@ class SocietyRuntime:await asyncio.to_thread(self.conversations.ingest, session.session_id, events)await self._complete_message_reply(session, completion, events)terminal = [e for e in events if e.get("kind") == "turn_finished"]- if not terminal or terminal[-1].get("payload", {}).get("status") not in {+ finished = bool(terminal) and terminal[-1].get("payload", {}).get("status") in {"done","ok","completed",- }:+ }+ if completion.turn.direct_user:+ from .surface import agent_id_of++ owner = agent_id_of(session.session_id)+ if owner and self.team_leads.group_led_by(owner) is not None:+ # The person's own turn in a team lead's chat: a goal the lead+ # acted on in it is followed up like a managing turn.+ final = next(+ (+ str(e.get("payload", {}).get("text") or "")+ for e in reversed(events)+ if e.get("kind") == "assistant_text"+ ),+ "",+ )+ self.background(+ self.team_leads.person_turn_ended(owner, ok=finished, final=final)+ )+ if not finished:returnnames = {str(e.get("payload", {}).get("name") or "")diff --git a/jarvis/society/team_lead.py b/jarvis/society/team_lead.pyindex 933b6429aa..0e659cf3a3 100644--- a/jarvis/society/team_lead.py+++ b/jarvis/society/team_lead.py@@ -17,6 +17,10 @@ person gives the TEAM a goal; from there the lead works on its own:next queued goal starts. A goal that came in as a board assignment (fromJarvis by voice, or a quest) answers that assignment with its report.+The person leads the lead in an ordinary chat. What they write there is their+own turn: work the lead hands out from it opens a goal in the person's words,+and their answer or go-ahead continues a goal that waits for them.+Nothing here calls a model. The lead's turns run on the lead's own seat, themembers' on theirs, and every turn belongs to a goal the person started (or acheck-in they switched on, which is an ordinary agent routine). Opening the@@ -57,6 +61,7 @@ log = logging.getLogger(__name__)__all__ = ["CHECKIN_TAG",+ "INITIATIVE_TAG","MAX_LEAD_TURNS","MAX_TASKS_PER_GOAL","TRACE_PREFIX",@@ -93,6 +98,10 @@ SWEEP_S: Final[float] = 60.0STALL_MS: Final[int] = 3 * 60 * 1000CHECKIN_TAG: Final[str] = "team-checkin:"+#: A check-in that may also set the team's next goal carries this tag too.+INITIATIVE_TAG: Final[str] = "team-initiative:"+#: Finished goals a lead reads on its board, so it does not repeat their work.+BOARD_FINISHED: Final[int] = 5CHECKIN_MINUTES: Final[tuple[int, ...]] = (0, 60, 240, 1440)_PROMOTED_KEY: Final[str] = "team_lead_promoted:"@@ -143,8 +152,12 @@ _LEAD_RULES: Final[str] = ("person: what was achieved, where the output is, what remains open. Use ""status=needs_input for a decision only the person can make (ask one precise question), ""status=progress for an interim update on long work, status=failed when the goal cannot "- "be reached and why.\n"- "- society_team_board shows the goal and every task at any time."+ "be reached and why. End a status=done report with the next step you recommend.\n"+ "- society_team_board shows the goal and every task at any time.\n"+ "- The person talks to you in this chat. When they ask for work, start it at once: "+ "society_team_assign opens the goal (name it in `goal`). When they answer a question "+ "you asked or tell you to go on, continue that goal in the same turn: your tools work "+ "on it again. When they only ask something, answer from the board.")CHECKIN_PROMPT: Final[str] = (@@ -155,6 +168,20 @@ CHECKIN_PROMPT: Final[str] = ("work the mission or an open goal does not call for.")+INITIATIVE_PROMPT: Final[str] = (+ "Team check-in. Call society_team_board first. If a goal is stuck, blocked or waiting on "+ "a member, act on it: follow up, re-assign, or report to the person. If no goal is open, "+ "take the initiative: decide what moves the team mission forward most right now, make it "+ "the team's next goal and hand out its first tasks with society_team_assign, naming the "+ "goal in `goal`. Choose one goal the team can finish, and never repeat what a finished "+ "goal already delivered. If the mission gives you nothing to derive a goal from, start "+ "nothing and say in one line what you need from the person. If a goal is in progress and "+ "nothing needs you, say so in one line and stop."+)++#: What a chat composer appends below the person's words (mentions, tool pins).+_CHAT_MARKS: Final[re.Pattern[str]] = re.compile(r"\n\n\[(?:agent mentions|tools:|to jarvis)")+_NAME_UNSAFE: Final[re.Pattern[str]] = re.compile(r"[/\\:@#<>\"'`]")@@ -330,6 +357,8 @@ class TeamLeads:self._resumed: set[str] = set()#: Goals whose lead was asked once for a typed report after a plain answer.self._nudged: set[str] = set()+ #: Goals a lead acted on inside the person's own turn in its chat.+ self._chat_goals: set[str] = set()self._timers: dict[str, asyncio.TimerHandle] = {}self._tasks: set[asyncio.Task[Any]] = set()self._locks: dict[str, asyncio.Lock] = {}@@ -451,12 +480,14 @@ class TeamLeads:lead = await self._rt.roster.get(lead_id) if lead_id else Nonegoals = await self.goals(group_id)rows = [goal.to_dict(await self.tasks(goal.goal_id)) for goal in goals]+ minutes, initiative = await self.checkin(group_id) if lead is not None else (0, False)return {"group_id": group_id,"lead_agent_id": lead_id,"lead_available": lead is not None and lead.state is AgentState.ACTIVE,"mission": group.get("mission") or "",- "checkin_minutes": await self.checkin_minutes(group_id) if lead is not None else 0,+ "checkin_minutes": minutes,+ "initiative": initiative,"goals": rows,"working": any(goal.goal_id in self._turns for goal in goals),"max_lead_turns": MAX_LEAD_TURNS,@@ -506,7 +537,7 @@ class TeamLeads:return groupif current and await self._active_goal(group_id) is not None:raise TeamLeadError("Stop the team's current goal before changing its lead.")- minutes = await self.checkin_minutes(group_id) if current else 0+ minutes, initiative = await self.checkin(group_id) if current else (0, False)if agent_id is None:await self._drop_checkin(group_id)group = await self._rt.store.set_chat_group_lead(group_id, None)@@ -539,7 +570,7 @@ class TeamLeads:await self.refresh()if minutes:try:- await self.set_checkin(group_id, minutes)+ await self.set_checkin(group_id, minutes, initiative=initiative)except TeamLeadError:log.info("society team lead: check-in not moved to the new lead")await self._announce(group_id, reason="lead")@@ -616,18 +647,23 @@ class TeamLeads:if CHECKIN_TAG + group_id in row.get("tags", ()) and row.get("state") not in ended]- async def checkin_minutes(self, group_id: str) -> int:- """How often the lead looks at its team unprompted; ``0`` = never."""+ async def checkin(self, group_id: str) -> tuple[int, bool]:+ """How often the lead looks at its team unprompted (``0`` = never), and+ whether such a look may also set the team's next goal."""try:rows = await self._checkin_rows(group_id)except Exception: # noqa: BLE001 — an unreadable task store reads as "off" on the boardlog.warning("society team lead: check-in state unreadable", exc_info=True)- return 0+ return 0, Falsefor row in rows:seconds = float((row.get("trigger") or {}).get("interval_seconds") or 0)if seconds > 0:- return int(round(seconds / 60))- return 0+ return int(round(seconds / 60)), INITIATIVE_TAG + group_id in row.get("tags", ())+ return 0, False++ async def checkin_minutes(self, group_id: str) -> int:+ """How often the lead looks at its team unprompted; ``0`` = never."""+ return (await self.checkin(group_id))[0]async def _drop_checkin(self, group_id: str) -> None:store, scheduler = self._rt.task_services()@@ -638,8 +674,12 @@ class TeamLeads:await scheduler.cancel_task(task_id)await store.delete(task_id)- async def set_checkin(self, group_id: str, minutes: int) -> int:- """Switch the lead's unprompted check-in on (an agent routine) or off."""+ async def set_checkin(self, group_id: str, minutes: int, *, initiative: bool = False) -> int:+ """Switch the lead's unprompted check-in on (an agent routine) or off.++ With ``initiative`` a check-in that finds no open goal sets the team's+ next one from its mission; without it the lead only follows up.+ """if minutes not in CHECKIN_MINUTES:raise TeamLeadError("Unknown check-in interval.", status=422)group = await self._require_group(group_id)@@ -658,10 +698,13 @@ class TeamLeads:spec = build_task_spec(lead,title=f"Team check-in: {group['name']}",- prompt=CHECKIN_PROMPT,+ prompt=INITIATIVE_PROMPT if initiative else CHECKIN_PROMPT,schedule={"kind": "every", "interval_seconds": minutes * 60},)- spec = spec.model_copy(update={"tags": (*spec.tags, CHECKIN_TAG + group_id)})+ tags = (*spec.tags, CHECKIN_TAG + group_id)+ if initiative:+ tags = (*tags, INITIATIVE_TAG + group_id)+ spec = spec.model_copy(update={"tags": tags})await create_routine(store, scheduler, spec)await self._announce(group_id, reason="checkin")return minutes@@ -888,6 +931,7 @@ class TeamLeads:self._told.pop(goal.goal_id, None)self._resumed.discard(goal.goal_id)self._nudged.discard(goal.goal_id)+ self._chat_goals.discard(goal.goal_id)for task in await self.tasks(goal.goal_id):if task.state not in TASK_OPEN:continue@@ -1045,7 +1089,7 @@ class TeamLeads:"blocked, then lead it to its report.")return self._frame(goal, "team goal resumed", body), goal.title, reported- if not tasks and goal.lead_turns == 0:+ if not tasks and goal.lead_turns == 0 and goal.goal_id not in self._nudged:return self._plan_prompt(goal)news, reported = self._news_body(goal, tasks)if not reported:@@ -1091,6 +1135,9 @@ class TeamLeads:return# Claimed before the first await, so a second caller cannot start a twin.self._turns[goal_id] = ("", "")+ # From here the engine follows this goal itself; a mark left by a+ # person's turn that never reported its end must not outlive that.+ self._chat_goals.discard(goal_id)lead_id = ""started = Falsetry:@@ -1223,10 +1270,12 @@ class TeamLeads:goal = await self.get_goal(goal_id)if goal is None:return+ # The turn is over whatever became of the goal: the view stops showing+ # the lead at work, also for a goal this very turn closed.+ await self._announce(goal.group_id, goal_id=goal_id, state=goal.state, reason="turn")if goal.state in GOAL_TERMINAL:await self._advance(goal.group_id)return- await self._announce(goal.group_id, goal_id=goal_id, state=goal.state, reason="turn")if goal.state is not TeamGoalState.RUNNING:returnif goal_id in self._turns:@@ -1259,9 +1308,29 @@ class TeamLeads:# ----------------------------------------------------- the lead's tools- async def _goal_for_lead(self, lead_id: str, *, create_title: str = "") -> TeamGoal:- """The goal a lead's tool call belongs to; a lead working from its own- chat with no goal open starts one."""+ @staticmethod+ def _person_turn(lead_id: str) -> Any | None:+ """The person's own turn in this lead's chat, when a tool call runs+ inside one. Trusted provenance: the chat service sets it, no model does."""+ from jarvis.core.protocols import current_chat_turn++ from .surface import agent_id_of++ turn = current_chat_turn.get()+ if turn is None or not turn.direct_user or agent_id_of(turn.session_id) != lead_id:+ return None+ return turn++ async def _goal_for_lead(+ self, lead_id: str, *, create_title: str = "", goal_hint: str = ""+ ) -> TeamGoal:+ """The goal a lead's tool call belongs to.++ Inside the person's own turn in the lead's chat, a goal that waits for+ the person continues (their words are the answer or the go-ahead), and+ work handed out with no goal open starts one in the person's words. A+ lead working unprompted (a check-in) names the goal it starts itself.+ """group_id = self._leads.get(lead_id)if group_id is None:raise TeamLeadError("You do not lead a team.")@@ -1276,37 +1345,88 @@ class TeamLeads:"This goal is no longer in progress. End your turn; you are woken ""when there is something to do.")- active = await self._active_goal(group_id)- if active is not None:- if active.state is not TeamGoalState.RUNNING:- raise TeamLeadError(- f'The goal "{active.title}" is {active.state}; the person continues it '- "from the team board."- )- return active- if not create_title:- raise TeamLeadError("Your team has no goal in progress.")- new_id = uuid7_str()- stamp = now_ms()- await self._rt.store.insert_team_goal(- {- "goal_id": new_id,- "group_id": group_id,- "lead_agent_id": lead_id,- "title": goal_title(create_title),- "text": create_title,- "state": str(TeamGoalState.RUNNING),- "lead_turns": 1,- "origin_json": json.dumps({"kind": "lead"}),- "created_ms": stamp,- "updated_ms": stamp,- }- )+ turn = self._person_turn(lead_id)+ # One caller at a time decides what holds the team: two tasks handed+ # out in the same step must land in one goal, never open two.+ async with self._lock(group_id):+ active = await self._active_goal(group_id)+ if active is not None:+ return await self._adopt(active, turn)+ if not create_title:+ raise TeamLeadError("Your team has no goal in progress.")+ words = _CHAT_MARKS.split(turn.user_text, maxsplit=1)[0].strip() if turn else ""+ text = (words or goal_hint or create_title)[:MAX_GOAL_TEXT]+ new_id = uuid7_str()+ stamp = now_ms()+ await self._rt.store.insert_team_goal(+ {+ "goal_id": new_id,+ "group_id": group_id,+ "lead_agent_id": lead_id,+ "title": goal_title(text, goal_hint) if words else goal_title(text),+ "text": text,+ "state": str(TeamGoalState.RUNNING),+ "lead_turns": 1,+ "lang": self._language(words, None) if words else "",+ "origin_json": json.dumps({"kind": "chat" if words else "lead"}),+ "created_ms": stamp,+ "updated_ms": stamp,+ }+ )+ if turn is not None:+ self._chat_goals.add(new_id)await self._announce(group_id, goal_id=new_id, state=TeamGoalState.RUNNING)created = await self.get_goal(new_id)assert created is not Nonereturn created+ async def _adopt(self, active: TeamGoal, turn: Any | None) -> TeamGoal:+ """The goal that holds the team, for a lead's tool call outside a+ managing turn. One that waits for the person continues only inside+ the person's own turn, and only while nobody stopped it meanwhile."""+ if active.state is not TeamGoalState.RUNNING:+ waited = (TeamGoalState.NEEDS_INPUT, TeamGoalState.PAUSED)+ if (+ turn is None+ or await self._rt.store.kill_switch()+ or not await self._move(+ active, TeamGoalState.RUNNING, waited, note="", lead_turns=0+ )+ ):+ raise TeamLeadError(+ f'The goal "{active.title}" is {active.state}; it continues when '+ "the person answers you in this chat."+ )+ self._nudged.discard(active.goal_id)+ active = await self._require_goal(active.goal_id)+ if active.state is not TeamGoalState.RUNNING:+ # Stopped between the move and this read: the stop wins.+ raise TeamLeadError("This goal is no longer in progress.")+ if turn is not None:+ self._chat_goals.add(active.goal_id)+ return active++ async def person_turn_ended(self, lead_id: str, *, ok: bool, final: str = "") -> None:+ """The person's own turn in the lead's chat ended.++ A goal the lead acted on in that turn gets what follows a managing+ turn: results that landed meanwhile are reviewed, and a goal left with+ nothing running and no report is asked once for a typed one. A turn+ that failed is the person's to see in the chat; the sweep parks a goal+ it left with nothing in progress.+ """+ group_id = self._leads.get(lead_id)+ if group_id is None:+ return+ goal = await self._active_goal(group_id)+ touched = goal is not None and goal.goal_id in self._chat_goals+ self._chat_goals -= {g.goal_id for g in await self.goals(group_id, limit=200)}+ if not ok or goal is None or not touched or goal.state is not TeamGoalState.RUNNING:+ return+ if goal.goal_id in self._turns or f"lead:{goal.goal_id}" in self._timers:+ return # A managing turn is already running or on its way.+ await self._after_lead_turn(goal.goal_id, ok=True, final=final.strip(), error="")+def _resolve_member(self, group: Mapping[str, Any], lead_id: str, wanted: str) -> AgentRecord:by_id = {a.agent_id: a for a in self._rt.roster.snapshot()}members = [@@ -1343,10 +1463,14 @@ class TeamLeads:target = self._resolve_member(group, lead_id, member)if target.state is not AgentState.ACTIVE:raise TeamLeadError(f"{target.name} is {target.state} and cannot take work.")- goal = await self._goal_for_lead(lead_id, create_title=goal_title_hint or title)+ goal = await self._goal_for_lead(lead_id, create_title=title, goal_hint=goal_title_hint)tasks = await self.tasks(goal.goal_id)if len(tasks) >= MAX_TASKS_PER_GOAL:raise TeamLeadError("This goal reached its task limit; report to the person.")+ fresh = await self.get_goal(goal.goal_id)+ if fresh is None or fresh.state is not TeamGoalState.RUNNING:+ # Stopped while this call was on its way: no task joins a closed goal.+ raise TeamLeadError("This goal is no longer in progress.")task_id = uuid7_str()stamp = now_ms()env = self._assign_envelope(goal, lead_id, target.agent_id, task_id, title, brief)@@ -1423,7 +1547,11 @@ class TeamLeads:raise TeamLeadError("You do not lead a team.")group = self._groups[group_id]await self._rt.roster.refresh()- goals = [g for g in await self.goals(group_id, limit=30) if g.state not in GOAL_TERMINAL]+ every = await self.goals(group_id, limit=30)+ goals = [g for g in every if g.state not in GOAL_TERMINAL]+ closed = sorted(+ (g for g in every if g.state in GOAL_TERMINAL), key=lambda g: g.updated_ms, reverse=True+ )rows = []for goal in sorted(goals, key=lambda g: g.created_ms):tasks = await self.tasks(goal.goal_id)@@ -1449,6 +1577,10 @@ class TeamLeads:"mission": group.get("mission") or "","members": self._roster_lines(group, lead_id),"goals": rows,+ "finished": [+ {"title": g.title, "state": str(g.state), "report": g.report[:400]}+ for g in closed[:BOARD_FINISHED]+ ],}async def report(self, lead_id: str, *, status: str, summary: str) -> dict[str, Any]:@@ -1483,8 +1615,32 @@ class TeamLeads:raise TeamLeadError("This goal is no longer in progress.")else:raise TeamLeadError("status must be progress, needs_input, done or failed")+ await self._post_report(goal, status, text)return {"goal_id": goal.goal_id, "title": goal.title, "recorded": status}+ async def _post_report(self, goal: TeamGoal, status: str, text: str) -> None:+ """The report as a card in the lead's chat, where the person reads along:+ a report made with a tool is otherwise visible on the team panel only."""+ lead = await self._rt.roster.get(goal.lead_agent_id)+ if lead is None:+ return+ try:+ await self._rt.post_chat_notice(+ lead,+ {+ "kind": "team_report",+ "status": status,+ "goal_id": goal.goal_id,+ "title": goal.title,+ "agent_id": lead.agent_id,+ "agent_name": lead.name,+ "text": text[:20_000],+ },+ )+ except Exception: # noqa: BLE001 — the report stays on the team panel either way+ log.warning("society team lead: report of %s not shown in chat", goal.goal_id,+ exc_info=True)+# --------------------------------------------------------- the boardasync def _on_envelope(self, env: SocietyEnvelope) -> None:diff --git a/jarvis/society/team_tools.py b/jarvis/society/team_tools.pyindex 2991080c75..9cefd7b72d 100644--- a/jarvis/society/team_tools.py+++ b/jarvis/society/team_tools.py@@ -79,6 +79,11 @@ class TeamAssignTool:"type": "string","description": "The output and evidence that establish the task is done.",},+ "goal": {+ "type": "string",+ "description": "Optional. When no goal is in progress, this task opens one: "+ "a name for that goal, a few words long.",+ },},"required": ["member", "title", "task"],}@@ -105,6 +110,7 @@ class TeamAssignTool:member=str(args.get("member") or ""),title=title,brief=brief,+ goal_title_hint=str(args.get("goal") or "").strip(),)except TeamLeadError as exc: # The refusal is the tool's answer; the lead reads why.return _refused(exc)@@ -126,8 +132,9 @@ class TeamBoardTool:risk_tier: str = "safe"description: str = ("Read the board of the team you lead: its mission, who is on it and whether they are "- "free, every open goal, and each task with its state and result. Read-only. Use it "- "to check where a goal stands before deciding, never to wait for a result."+ "free, every open goal, each task with its state and result, and the goals finished "+ "most recently. Read-only. Use it to check where the team stands before deciding or "+ "answering the person, never to wait for a result.")schema: dict[str, Any] = {"type": "object", "properties": {}}@@ -186,7 +193,14 @@ class TeamReportTool:)except TeamLeadError as exc: # The refusal is the tool's answer; the lead reads why.return _refused(exc)- return ToolResult(success=True, output=outcome)+ return ToolResult(+ success=True,+ output={+ **outcome,+ "next": "The person reads this report in your chat as written. End your turn "+ "in one short line; do not repeat the report.",+ },+ )def team_lead_tools(runtime: Any, agent_id: str) -> dict[str, Any]:diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.tsindex 09b2df3166..08062cf7fd 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts@@ -42,6 +42,22 @@ describe("agent-chat reduce", () => {expect(failed.items[0]).toMatchObject({ status: "error", error: "claude-cli did not finish within 3600 s." });});+ it("marks the turns the team engine gave a lead, and none the person typed", () => {+ const frame = (kind: string) => `[${kind} for team Launch]\nGoal: Launch the page\nGoal id: g1. Managing turns left: 20.`;+ const tl = reduceEvents(EMPTY_TIMELINE, [+ ev("user_message", { text: frame("team goal"), typed: "Launch the page" }),+ ev("user_message", { text: frame("team update"), typed: "Launch the page: 2 results" }),+ ev("user_message", { text: frame("team goal check"), typed: "Launch the page" }),+ ev("user_message", { text: frame("team goal resumed"), typed: "Launch the page" }),+ ev("user_message", { text: frame("team goal reply"), typed: "Germany" }),+ ev("user_message", { text: "I read [team update for team Launch] somewhere" }),+ ]);+ expect(tl.items.map((item) => (item.type === "user" ? item.teamEvent : "?"))).toEqual([+ undefined, "update", "check", "resumed", undefined, undefined,+ ]);+ expect(tl.items[1]).toMatchObject({ type: "user", text: "Launch the page: 2 results" });+ });+it("folds a full turn: user line, deltas into one text block, tool call + result, finish", () => {const tl = reduceEvents(EMPTY_TIMELINE, [ev("user_message", { text: "hi" }),diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.tsindex 2c9dc62967..3faafab59d 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts@@ -231,9 +231,26 @@ export interface UserItem {toolChoices?: ToolChoice[];/** A Jarvis agent wrote this message into a coding thread on the person's behalf. */author?: { agentId: string; name: string };+ /**+ * The team engine woke a team lead with this turn; nobody typed it. `update`+ * brings members' results, `check` asks for the report, `resumed` continues+ * a goal the person resumed.+ */+ teamEvent?: TeamEvent;tsMs: number;}+export type TeamEvent = "update" | "check" | "resumed";++/** The frame the team engine puts on a lead's managing turn (jarvis/society/team_lead.py `_frame`). */+const TEAM_FRAME = /^\[team (update|goal check|goal resumed) for team /;+const TEAM_EVENTS: Record<string, TeamEvent> = { update: "update", "goal check": "check", "goal resumed": "resumed" };++function teamEventOf(prompt: string): TeamEvent | undefined {+ const match = TEAM_FRAME.exec(prompt);+ return match ? TEAM_EVENTS[match[1]] : undefined;+}+/** One file's receipt in the timeline — enough to say what was sent, no more. */export interface UserAttachment {name: string;@@ -803,6 +820,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {...(p.origin === "control" ? { origin: "control" as const } : {}),...(p.origin === "background" ? { origin: "background" as const } : {}),...(messageAuthor(p.author) ? { author: messageAuthor(p.author) } : {}),+ ...(teamEventOf(str(p.text)) ? { teamEvent: teamEventOf(str(p.text)) } : {}),// `typed` is present only when the message carried files, and it// is the person's own sentence; `text` is the composed prompt.text: str(p.typed) || str(p.text),diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 631d1935df..6ba3bdb8ef 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -6,9 +6,9 @@ import {DelegationActivity,RoutineActivity,assignmentOf,- routineTask,-} from "./ChatActivity";+ routineTask, TeamEventLine } from "./ChatActivity";import { MemoryNoticeViewer, MemoryUpdateNotice, memoryNoticePath, memoryNoticeTitle } from "./MemoryUpdateNotice";+import { TeamReportNotice } from "./TeamReportNotice";import { foldMemoryNotices } from "./memoryNotices";import { foldRepeatedThreadStatus } from "@/components/agentic/threads/openCodingThread";import { mergeOutgoingMessages, useOutgoingMessages } from "@/components/agentchat/useOutgoingMessages";@@ -32,7 +32,7 @@ import { mergeOutgoingMessages, useOutgoingMessages } from "@/components/agentch* the voice runs on the realtime tier (`[brain.realtime]`), which no text* runner can drive. The header says so while voice is showing.*/-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useRoutineNavigation } from "./routineNavigation";import { notifyRoutineChanged } from "../cardData";import { routineTaskId } from "./routineExecution";@@ -127,6 +127,8 @@ export interface AgentChatPanelProps {roster: SocietyAgent[];/** An isolated store lets two canonical agent sessions remain open side by side. */chatStore?: AgentChatStoreHook;+ /** Shown directly above the composer of an agent's own chat (a team lead's actions). */+ composerExtras?: ReactNode;}/**@@ -185,7 +187,7 @@ export function AgentChatPanel(props: AgentChatPanelProps) {</PairConversationBoundary>;}-function AgentChatPanelContent({ agent, roster, chatStore }: AgentChatPanelProps) {+function AgentChatPanelContent({ agent, roster, chatStore, composerExtras }: AgentChatPanelProps) {if (agent.tier === "lead") {return (<AgentChatStoreProvider store={useAgentChatStore}>@@ -196,7 +198,7 @@ function AgentChatPanelContent({ agent, roster, chatStore }: AgentChatPanelPropsif (!agent.chatSessionId) return <NotBoundYet />;return (<AgentChatStoreProvider store={chatStore ?? useSocietyChatStore}>- <SpecialistChat agent={agent} roster={roster} />+ <SpecialistChat agent={agent} roster={roster} composerExtras={composerExtras} /></AgentChatStoreProvider>);}@@ -216,7 +218,7 @@ async function bindAgentChat(agentId: string): Promise<void> {if (!res.ok) throw new Error(`HTTP ${res.status}`);}-function SpecialistChat({ agent, roster }: AgentChatPanelProps) {+function SpecialistChat({ agent, roster, composerExtras }: AgentChatPanelProps) {const t = useT();const items = useAgentChat((s) => s.timeline.items);const activeSessionId = useAgentChat((s) => s.activeSessionId);@@ -317,6 +319,7 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {{`${t("society.card.chat_bind_failed")} (${bindError})`}</p>) : null}+ {composerExtras}<Composerkey={agent.agentId}agent={agent}@@ -741,6 +744,8 @@ export function Transcript({<AgentMessageActivity item={item} roster={roster} />) : item.type === "user" && assignmentOf(item.text) ? (<DelegationActivity {...assignmentOf(item.text)!} roster={roster} />+ ) : item.type === "user" && item.teamEvent ? (+ <TeamEventLine event={item.teamEvent} text={item.text} />) : item.type === "user" ? (<UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} tint={tint} />) : item.type === "turn" ? (@@ -784,6 +789,7 @@ function TimeStamp({ ms }: { ms: number }) {export function NoticeLine({ item }: { item: NoticeItem }) {const t = useT();if (item.kind === "memory_updated") return <MemoryUpdateNotice item={item} />;+ if (item.kind === "team_report") return <TeamReportNotice item={item} />;if (item.kind === "message_queued") {return <p className="self-end py-1 text-xs text-muted-foreground" data-testid="message-queued">{t("society.chat.message_waiting")} · {item.text}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsxindex abbcaa3dc6..8d5d4d26dc 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx@@ -1,7 +1,7 @@import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeAll, expect, it } from "vitest";import { loadLocaleChunk } from "@/i18n";-import { AgentMessageActivity, RoutineActivity, routineTask } from "./ChatActivity";+import { AgentMessageActivity, RoutineActivity, TeamEventLine, routineTask } from "./ChatActivity";import { ReasoningTrace, WorkTrace } from "@/components/agentchat/WorkTrace";import type { InternalMessageItem, ReasoningBlock, ToolBlock } from "@/components/agentchat/reduce";@@ -191,3 +191,16 @@ it("folds a finished turn to the reply and opens the whole trace again", () => {fireEvent.click(toggle);expect(screen.queryByText(/Check the report first/)).toBeNull();});++it("shows a turn the team engine gave a lead as a quiet line, never as a message", () => {+ const { rerender } = render(<TeamEventLine event="update" text={"Launch the page: 2 results"} />);+ const line = screen.getByTestId("team-event-line");+ expect(line.getAttribute("data-event")).toBe("update");+ expect(line.textContent).toContain("Results from the team (2)");+ expect(line.textContent).toContain("· Launch the page");+ expect(line.textContent).not.toContain("2 results");+ rerender(<TeamEventLine event="check" text="Launch the page" />);+ expect(screen.getByTestId("team-event-line").textContent).toBe("Asked for the report· Launch the page");+ rerender(<TeamEventLine event="resumed" text="" />);+ expect(screen.getByTestId("team-event-line").textContent).toBe("Goal continued");+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsxindex fa6b76dd59..bf7e717c42 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx@@ -1,10 +1,10 @@import { useId, useState, type ReactNode } from "react";-import { ArrowDownLeft, ArrowUpRight, ChevronRight, Clock3, Inbox } from "lucide-react";+import { ArrowDownLeft, ArrowUpRight, ChevronRight, Clock3, Inbox, Users } from "lucide-react";import { CodingThreadActivity } from "@/components/agentic/threads/CodingThreadLink";import { codingThreadOf } from "@/components/agentic/threads/openCodingThread";import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";import { useOpenPairConversation } from "@/components/agentchat/PairConversation";-import type { InternalMessageItem } from "@/components/agentchat/reduce";+import type { InternalMessageItem, TeamEvent } from "@/components/agentchat/reduce";import { useT } from "@/i18n";import { NEUTRAL_ASSISTANT_NAME } from "@/lib/assistantNameCache";import { societyDisplayName } from "@/lib/societyDisplayName";@@ -68,6 +68,27 @@ export function DelegationActivity({ sender, task, roster }: {</ChatActivity>;}+/** What the engine shows for a turn that brings results: "<goal>: 2 results". */+const TEAM_RESULTS = /^(.*): (\d+) results?$/s;++/**+ * A turn the team engine gave a team lead: members' results arrived, a report+ * is due, or a goal the person resumed goes on. Nobody typed it, so it is a+ * quiet line in the conversation and never a message bubble.+ */+export function TeamEventLine({ event, text }: { event: TeamEvent; text: string }) {+ const t = useT();+ const results = event === "update" ? TEAM_RESULTS.exec(text) : null;+ const label = results ? t("society.lead.event_update").replace("{0}", results[2]) : t(`society.lead.event_${event}`).replace("{0}", "");+ const goal = (results ? results[1] : text).split(/\r?\n/)[0];+ return <p data-testid="team-event-line" data-event={event}+ className="mx-auto my-1 flex max-w-[min(100%,36rem)] items-center justify-center gap-2 px-2 py-1 text-xs text-muted-foreground">+ <Users aria-hidden className="h-3.5 w-3.5 shrink-0" />+ <span className="shrink-0">{label.trim()}</span>+ {goal ? <span className="min-w-0 truncate">· {goal}</span> : null}+ </p>;+}+export function RoutineActivity({ task, original, onOpen }: { task: string; original: string; onOpen?: () => void }) {const t = useT();if (onOpen) return <button type="button" onClick={onOpen}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsxindex ab7c5bafbb..88fe07f90b 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx@@ -20,7 +20,7 @@ vi.mock("./AgentChatPanel", () => ({},}));vi.mock("./MeetingChat", () => ({ MeetingChat: () => <div data-testid="meeting" /> }));-vi.mock("./TeamLeadBoard", () => ({ TeamLeadBoard: () => <div data-testid="lead-board" /> }));+vi.mock("./TeamLeadView", () => ({ TeamLeadView: () => <div data-testid="lead-board" /> }));afterEach(() => { cleanup(); groupApi.remove.mockClear(); });diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsxindex 6e3f7454f9..ab299e9f7e 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx@@ -14,7 +14,7 @@ import { RosterRail } from "../roster/RosterRail";import { AgentChatPanel } from "./AgentChatPanel";import { ChatGroupDialog } from "./ChatGroupDialog";import { MeetingChat } from "./MeetingChat";-import { TeamLeadBoard } from "./TeamLeadBoard";+import { TeamLeadView } from "./TeamLeadView";/** What the team's main column shows. */type GroupView = "lead" | "meeting" | "individual";@@ -51,7 +51,7 @@ export function ChatGroupPanel({const [leftId, setLeftId] = useState(group.members[0] ?? "");const [rightId, setRightId] = useState(group.members[1] ?? "");const [editing, setEditing] = useState(false);- // A team that has a lead opens on the lead's board; the others on their meeting.+ // A team that has a lead opens on the chat with its lead; the others on their meeting.const [view, setView] = useState<GroupView>(group.lead_agent_id ? "lead" : "meeting");const [confirmUngroup, setConfirmUngroup] = useState(false);const [removing, setRemoving] = useState(false);@@ -164,7 +164,7 @@ export function ChatGroupPanel({<button type="button" aria-pressed={view === "individual"} onClick={() => setView("individual")}className={viewToggle(view === "individual")}>{t("society.meeting.individual")}</button></div>- {view === "lead" ? <TeamLeadBoard key={group.group_id} group={group} roster={roster} onOpenAgent={onOpenAgent} />+ {view === "lead" ? <TeamLeadView key={group.group_id} group={group} roster={roster} onOpenAgent={onOpenAgent} />: view === "meeting" ? <MeetingChat key={group.group_id} group={group} roster={roster} />: <div className="grid min-h-0 min-w-0 flex-1 grid-cols-2 divide-x-2 divide-border-strong overflow-hidden bg-background"data-testid="society-group-split">diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsxdeleted file mode 100644index 3069b9b6c3..0000000000--- a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.test.tsx+++ /dev/null@@ -1,223 +0,0 @@-import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { afterEach, beforeEach, expect, it, vi } from "vitest";-import type { SocietyChatGroup, SocietyTeam, SocietyTeamGoal } from "@/lib/societyChatGroups";-import type { SocietyAgent } from "../data";-import { TeamLeadBoard } from "./TeamLeadBoard";--const api = vi.hoisted(() => ({- team: null as unknown,- setLead: vi.fn(),- createLead: vi.fn(),- setMission: vi.fn(),- setCheckin: vi.fn(),- startGoal: vi.fn(),- message: vi.fn(),- resume: vi.fn(),- cancel: vi.fn(),-}));--vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));-vi.mock("../AgentSwatch", () => ({ AgentSwatch: () => <i data-testid="swatch" /> }));-vi.mock("./AgentChatPanel", () => ({ Prose: ({ text }: { text: string }) => <p>{text}</p> }));-vi.mock("@/components/ui/select", () => ({- BrandedSelect: ({ options, onValueChange, testId, value }: {- options: { value: string; label: string }[]; onValueChange: (value: string) => void; testId: string; value: string;- }) => <div data-testid={testId} data-value={value}>- {options.map((option) => <button key={option.value} type="button" onClick={() => onValueChange(option.value)}>{option.label}</button>)}- </div>,-}));-vi.mock("@/lib/societyChatGroups", () => ({- TEAM_GOAL_OPEN: ["queued", "running", "needs_input", "paused"],- useSocietyTeam: () => ({ data: api.team, isLoading: false, isError: false, error: null }),- setSocietyTeamLead: api.setLead,- createSocietyTeamLead: api.createLead,- setSocietyTeamMission: api.setMission,- setSocietyTeamCheckin: api.setCheckin,- startSocietyTeamGoal: api.startGoal,- messageSocietyTeamGoal: api.message,- resumeSocietyTeamGoal: api.resume,- cancelSocietyTeamGoal: api.cancel,-}));--const agent = (agentId: string, name: string, tier = "specialist") => ({- agentId, name, tier, title: `${name} title`, lifecycle: "active", chatSessionId: `society:${agentId}`,-}) as unknown as SocietyAgent;-const roster = [agent("jarvis", "Jarvis", "lead"), agent("boss", "Boss", "orchestrator"), agent("scout", "Scout"), agent("writer", "Writer")];-const group: SocietyChatGroup = {- group_id: "team", name: "Launch", members: ["jarvis", "boss", "scout", "writer"], created_ms: 1, updated_ms: 1, lead_agent_id: "boss",-};--function team(over: Partial<SocietyTeam> = {}): SocietyTeam {- return {- group_id: "team", lead_agent_id: "boss", lead_available: true, mission: "", checkin_minutes: 0,- goals: [], working: false, max_lead_turns: 24, ...over,- };-}--function goal(over: Partial<SocietyTeamGoal> = {}): SocietyTeamGoal {- return {- goal_id: "g1", group_id: "team", lead_agent_id: "boss", title: "Launch the page", text: "Launch the page",- state: "running", report: "", note: "", lead_turns: 1, source: "board", created_ms: 1, updated_ms: 1, done_ms: null,- tasks: [], ...over,- };-}--function mount(onOpenAgent = vi.fn()) {- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });- render(<QueryClientProvider client={client}><TeamLeadBoard group={group} roster={roster} onOpenAgent={onOpenAgent} /></QueryClientProvider>);- return onOpenAgent;-}--beforeEach(() => {- for (const fn of [api.setLead, api.createLead, api.setMission, api.setCheckin, api.startGoal, api.message, api.resume, api.cancel]) {- fn.mockReset();- fn.mockImplementation(async () => api.team);- }-});-afterEach(cleanup);--it("offers to create a lead or promote a member, never the assistant or nobody", async () => {- api.team = team({ lead_agent_id: null, lead_available: false });- mount();- expect(screen.getByText("society.lead.none_title")).toBeTruthy();- const pick = screen.getByTestId("team-lead-pick");- expect(within(pick).getAllByRole("button").map((button) => button.textContent)).toEqual(["Boss", "Scout", "Writer"]);- expect(screen.getByRole("button", { name: "society.lead.make" }).hasAttribute("disabled")).toBe(true);- fireEvent.click(within(pick).getByRole("button", { name: "Scout" }));- fireEvent.click(screen.getByRole("button", { name: "society.lead.make" }));- await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", "scout"));- fireEvent.click(screen.getByTestId("team-lead-create"));- await waitFor(() => expect(api.createLead).toHaveBeenCalledWith("team"));-});--it("gives the team a goal and clears the field once the lead has it", async () => {- api.team = team();- const onOpenAgent = mount();- expect(screen.getByRole("heading", { name: "Boss" })).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "society.lead.open_chat" }));- expect(onOpenAgent).toHaveBeenCalledWith("boss");-- const send = screen.getByRole("button", { name: "society.lead.goal_send" });- expect(send.hasAttribute("disabled")).toBe(true);- const field = screen.getByLabelText("society.lead.goal_label") as HTMLTextAreaElement;- fireEvent.change(field, { target: { value: " Launch the page " } });- fireEvent.click(send);- await waitFor(() => expect(api.startGoal).toHaveBeenCalledWith("team", "Launch the page"));- await waitFor(() => expect(field.value).toBe(""));-});--it("keeps the goal text and shows the reason when the team refuses it", async () => {- api.team = team();- api.startGoal.mockImplementation(async () => { throw new Error("The society is paused."); });- mount();- const field = screen.getByLabelText("society.lead.goal_label") as HTMLTextAreaElement;- fireEvent.change(field, { target: { value: "Launch" } });- fireEvent.click(screen.getByRole("button", { name: "society.lead.goal_send" }));- expect((await screen.findByRole("alert")).textContent).toBe("The society is paused.");- expect(field.value).toBe("Launch");-});--it("shows each task with its member, state and result", () => {- api.team = team({- working: true,- goals: [goal({- tasks: [- { task_id: "t1", goal_id: "g1", agent_id: "scout", title: "Research", brief: "", state: "done", result: "Three found.", reviewed: true, created_ms: 1, updated_ms: 2, done_ms: 2 },- { task_id: "t2", goal_id: "g1", agent_id: "writer", title: "Draft", brief: "", state: "running", result: "", reviewed: false, created_ms: 2, updated_ms: 2, done_ms: null },- ],- })],- });- mount();- expect(screen.getByRole("status").textContent).toBe("society.lead.working");- const card = screen.getByTestId("team-goal-g1");- expect(card.getAttribute("data-state")).toBe("running");- const research = within(card).getByTestId("team-task-t1");- expect(research.textContent).toContain("Scout");- expect(research.textContent).toContain("society.lead.task_state_done");- expect(within(research).queryByText("Three found.")).toBeNull();- fireEvent.click(within(research).getByRole("button", { name: "society.lead.show_result" }));- expect(within(research).getByText("Three found.")).toBeTruthy();- const draft = within(card).getByTestId("team-task-t2");- expect(draft.textContent).toContain("society.lead.task_state_running");- expect(within(draft).queryByRole("button")).toBeNull();-});--it("shows a goal's text once: the full first line as heading, the rest below", () => {- const long = "Research the three largest cities of the country and then do a good deal more with them";- api.team = team({- goals: [- goal({ title: `${long.slice(0, 40)}…`, text: `${long}-Second line with details.` }),- goal({ goal_id: "g2", title: "Short goal", text: "Short goal" }),- goal({ goal_id: "g3", title: "Given title", text: "A different description." }),- ],- });- mount();- const cut = screen.getByTestId("team-goal-g1");- expect(within(cut).getByRole("heading", { level: 4 }).textContent).toBe(long);- expect(within(cut).getByText("Second line with details.")).toBeTruthy();- expect(cut.textContent?.split(long).length).toBe(2);- const short = screen.getByTestId("team-goal-g2");- expect(short.textContent?.split("Short goal").length).toBe(2);- const given = screen.getByTestId("team-goal-g3");- expect(within(given).getByRole("heading", { level: 4 }).textContent).toBe("Given title");- expect(within(given).getByText("A different description.")).toBeTruthy();-});--it("answers the lead's question and stops a goal", async () => {- api.team = team({ goals: [goal({ state: "needs_input", report: "Which market?", note: "question" })] });- mount();- const card = screen.getByTestId("team-goal-g1");- expect(within(card).getByText("society.lead.question")).toBeTruthy();- expect(within(card).getByText("Which market?")).toBeTruthy();- fireEvent.change(within(card).getByLabelText("society.lead.answer_placeholder"), { target: { value: "Germany" } });- fireEvent.click(within(card).getByRole("button", { name: "society.lead.send" }));- await waitFor(() => expect(api.message).toHaveBeenCalledWith("team", "g1", "Germany"));- fireEvent.click(within(card).getByRole("button", { name: "society.lead.stop" }));- await waitFor(() => expect(api.cancel).toHaveBeenCalledWith("team", "g1"));-});--it("explains why a goal is paused and continues it", async () => {- api.team = team({- goals: [- goal({ state: "paused", note: "turn_budget" }),- goal({ goal_id: "g2", state: "paused", note: "error:provider unavailable" }),- goal({ goal_id: "g3", state: "queued" }),- goal({ goal_id: "g4", state: "done", report: "All shipped." }),- ],- });- mount();- expect(within(screen.getByTestId("team-goal-g1")).getByText("society.lead.note_turn_budget")).toBeTruthy();- expect(within(screen.getByTestId("team-goal-g2")).getByText("society.lead.note_error")).toBeTruthy();- fireEvent.click(within(screen.getByTestId("team-goal-g1")).getByRole("button", { name: "society.lead.resume" }));- await waitFor(() => expect(api.resume).toHaveBeenCalledWith("team", "g1"));- const queued = screen.getByTestId("team-goal-g3");- expect(within(queued).getByRole("button", { name: "society.lead.start_now" })).toBeTruthy();- expect(within(queued).getByRole("button", { name: "society.lead.remove_goal" })).toBeTruthy();- // A finished goal keeps its report and offers nothing to do.- const done = screen.getByTestId("team-goal-g4");- expect(within(done).getByText("All shipped.")).toBeTruthy();- expect(within(done).queryByRole("button")).toBeNull();- expect(screen.getByText("society.lead.finished")).toBeTruthy();-});--it("saves the mission, switches check-ins and changes the lead", async () => {- api.team = team({ mission: "Ship the launch." });- mount();- const mission = screen.getByLabelText("society.lead.mission") as HTMLTextAreaElement;- await waitFor(() => expect(mission.value).toBe("Ship the launch."));- expect(screen.queryByRole("button", { name: "society.lead.mission_save" })).toBeNull();- fireEvent.change(mission, { target: { value: "Ship it by Friday." } });- fireEvent.click(screen.getByRole("button", { name: "society.lead.mission_save" }));- await waitFor(() => expect(api.setMission).toHaveBeenCalledWith("team", "Ship it by Friday."));-- fireEvent.click(within(screen.getByTestId("team-lead-checkin")).getByRole("button", { name: "society.lead.checkin_60" }));- await waitFor(() => expect(api.setCheckin).toHaveBeenCalledWith("team", 60));-- fireEvent.click(screen.getByRole("button", { name: "society.lead.change" }));- // The current lead is not offered as its own replacement.- expect(within(screen.getByTestId("team-lead-pick")).getAllByRole("button").map((button) => button.textContent)).toEqual(["Scout", "Writer"]);- fireEvent.click(screen.getByRole("button", { name: "society.lead.remove" }));- await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", null));-});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsxdeleted file mode 100644index a18c49d439..0000000000--- a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadBoard.tsx+++ /dev/null@@ -1,419 +0,0 @@-/**- * The team's lead and its work: who manages the team, what the team is for,- * the goals the person gave it, and every task the lead handed out.- *- * The person only sets a goal. The lead plans it, hands tasks to the members,- * is woken with each result and reports back; this board follows that live- * (`useSocietyTeam`) and offers the few moments that are the person's: answer- * the lead's question, continue a paused goal, stop one.- */-import { useEffect, useRef, useState, type FormEvent, type ReactNode } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { ChevronDown, Crown, Loader2 } from "lucide-react";-import { Button } from "@/components/ui/button";-import { BrandedSelect } from "@/components/ui/select";-import { Textarea } from "@/components/ui/textarea";-import { useT } from "@/i18n";-import {- TEAM_GOAL_OPEN,- cancelSocietyTeamGoal,- createSocietyTeamLead,- messageSocietyTeamGoal,- resumeSocietyTeamGoal,- setSocietyTeamCheckin,- setSocietyTeamLead,- setSocietyTeamMission,- startSocietyTeamGoal,- useSocietyTeam,- type SocietyChatGroup,- type SocietyTeam,- type SocietyTeamGoal,- type SocietyTeamTask,-} from "@/lib/societyChatGroups";-import { societyDisplayName } from "@/lib/societyDisplayName";-import { cn } from "@/lib/utils";-import { useEventStore } from "@/store/events";-import type { SocietyAgent } from "../data";-import { AgentSwatch } from "../AgentSwatch";-import { Prose } from "./AgentChatPanel";--/** The server's check-in intervals (jarvis/society/team_lead.py CHECKIN_MINUTES). */-const CHECKIN_CHOICES = [0, 60, 240, 1440] as const;-/** Reasons a goal waits that have their own sentence; anything else shows as written. */-const NOTE_KEYS = new Set([- "society_paused", "interrupted", "turn_budget", "lead_busy", "lead_unavailable", "stalled",-]);--const DOT: Record<string, string> = {- running: "bg-success",- assigned: "bg-success",- needs_input: "bg-warning",- waiting: "bg-warning",- paused: "bg-warning",- queued: "bg-muted-foreground",- done: "bg-foreground",- blocked: "bg-destructive",- failed: "bg-destructive",- cancelled: "bg-muted-foreground",-};--function StateChip({ state, label }: { state: string; label: string }) {- return (- <span data-state={state}- className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">- <i className={cn("h-1.5 w-1.5 rounded-full", DOT[state] ?? "bg-muted-foreground")} aria-hidden />- {label}- </span>- );-}--function Section({ title, children }: { title: string; children: ReactNode }) {- return (- <section className="flex flex-col gap-2">- <h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{title}</h3>- {children}- </section>- );-}--interface Props {- group: SocietyChatGroup;- roster: SocietyAgent[];- onOpenAgent: (id: string) => void;-}--export function TeamLeadBoard({ group, roster, onOpenAgent }: Props) {- const t = useT();- const client = useQueryClient();- const assistantName = useEventStore((s) => s.assistantName);- const query = useSocietyTeam(group.group_id);- const team = query.data;- const [busy, setBusy] = useState("");- const [problem, setProblem] = useState("");- const [picked, setPicked] = useState("");- const [changing, setChanging] = useState(false);- const [goalText, setGoalText] = useState("");- const [mission, setMission] = useState("");- const savedMission = useRef("");- const serverMission = team?.mission;-- // The saved mission fills the field until the person starts editing it.- useEffect(() => {- if (serverMission === undefined) return;- const previous = savedMission.current;- savedMission.current = serverMission;- setMission((current) => (current === previous ? serverMission : current));- }, [serverMission]);-- const agentOf = (id: string | null | undefined) => roster.find((agent) => agent.agentId === id);- const nameOf = (id: string | null | undefined) => {- const agent = agentOf(id);- return agent ? societyDisplayName(agent, assistantName) : (id ?? "");- };- const lead = agentOf(team?.lead_agent_id);- const leadName = nameOf(team?.lead_agent_id);- const members = group.members.map(agentOf).filter((agent): agent is SocietyAgent => Boolean(agent));- // Jarvis already leads every agent; a team lead is one of the others.- const candidates = members.filter((agent) => agent.tier !== "lead" && agent.lifecycle !== "archived"- && agent.agentId !== team?.lead_agent_id);-- /** Run one board action: the answer replaces the board, a refusal shows as written. */- const run = async (key: string, action: () => Promise<SocietyTeam>): Promise<boolean> => {- if (busy) return false;- setBusy(key);- setProblem("");- try {- client.setQueryData(["society", "team", group.group_id], await action());- return true;- } catch (cause) {- setProblem(cause instanceof Error ? cause.message : String(cause));- return false;- } finally {- setBusy("");- }- };- /** A lead change also changes the roster (tier) and the group (members). */- const leadChanged = async (key: string, action: () => Promise<SocietyTeam>) => {- if (!(await run(key, action))) return;- setChanging(false);- setPicked("");- await Promise.all([- client.invalidateQueries({ queryKey: ["society", "chat-groups"] }),- client.invalidateQueries({ queryKey: ["society", "roster"] }),- ]);- };-- const submitGoal = async (event: FormEvent) => {- event.preventDefault();- const text = goalText.trim();- if (!text) return;- if (await run("goal", () => startSocietyTeamGoal(group.group_id, text))) setGoalText("");- };-- if (query.isLoading) {- return <p className="m-auto p-6 text-sm text-muted-foreground" role="status">{t("society.lead.loading")}</p>;- }- if (query.isError || !team) {- return <p className="m-auto p-6 text-sm text-destructive" role="alert">{String(query.error ?? "")}</p>;- }-- const picker = (- <div className="flex flex-wrap items-center gap-2">- <BrandedSelect- ariaLabel={t("society.lead.pick")}- testId="team-lead-pick"- value={picked}- onValueChange={setPicked}- placeholder={t("society.lead.pick_placeholder")}- className="min-w-[12rem] flex-1"- options={candidates.map((agent) => ({ value: agent.agentId, label: societyDisplayName(agent, assistantName) }))}- />- <Button size="sm" variant="secondary" disabled={!picked || Boolean(busy)}- onClick={() => void leadChanged("pick", () => setSocietyTeamLead(group.group_id, picked))}>- {t("society.lead.make")}- </Button>- </div>- );-- const createButton = (variant: "default" | "secondary") => (- <Button size="sm" variant={variant} disabled={Boolean(busy)} data-testid="team-lead-create"- onClick={() => void leadChanged("create", () => createSocietyTeamLead(group.group_id))}>- {busy === "create" ? <Loader2 className="animate-spin" aria-hidden /> : <Crown aria-hidden />}- {t("society.lead.create")}- </Button>- );-- if (!team.lead_agent_id) {- return (- <section className="flex min-h-0 flex-1 flex-col overflow-y-auto bg-background" data-testid="team-lead-board">- <div className="mx-auto flex w-full max-w-[36rem] flex-col gap-4 px-6 py-12">- <span className="grid h-11 w-11 place-items-center rounded-xl bg-secondary text-foreground"><Crown className="h-5 w-5" aria-hidden /></span>- <h2 className="text-lg font-semibold text-foreground">{t("society.lead.none_title")}</h2>- <p className="text-sm text-muted-foreground">{t("society.lead.none_body")}</p>- <div>{createButton("default")}</div>- {candidates.length > 0 && <>- <p className="pt-2 text-sm font-medium text-foreground">{t("society.lead.pick")}</p>- {picker}- </>}- {problem && <p role="alert" className="text-sm text-destructive">{problem}</p>}- </div>- </section>- );- }-- const open = team.goals.filter((goal) => TEAM_GOAL_OPEN.includes(goal.state))- .sort((a, b) => Number(b.state !== "queued") - Number(a.state !== "queued") || a.created_ms - b.created_ms);- const finished = team.goals.filter((goal) => !TEAM_GOAL_OPEN.includes(goal.state));-- return (- <section className="flex min-h-0 flex-1 flex-col overflow-y-auto bg-background" data-testid="team-lead-board">- <div className="mx-auto flex w-full max-w-[52rem] flex-col gap-6 px-4 py-5 sm:px-6">- <header className="flex flex-wrap items-center gap-3 rounded-xl border border-border bg-card p-3">- <span className="grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-secondary">- {lead ? <AgentSwatch agent={lead} size={38} /> : <Crown className="h-5 w-5" aria-hidden />}- </span>- <div className="min-w-0 flex-1">- <p className="flex items-center gap-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">- <Crown className="h-3 w-3" aria-hidden />{t("society.lead.role")}- </p>- <h2 className="truncate text-base font-semibold text-foreground">{leadName}</h2>- <p className="truncate text-xs text-muted-foreground" role="status">- {!team.lead_available ? t("society.lead.unavailable")- : team.working ? t("society.lead.working").replace("{0}", leadName)- : (lead?.title ?? "")}- </p>- </div>- {lead && <Button size="sm" variant="secondary" onClick={() => onOpenAgent(lead.agentId)}>{t("society.lead.open_chat")}</Button>}- <Button size="sm" variant="ghost" aria-expanded={changing} onClick={() => setChanging((value) => !value)}>- {t("society.lead.change")}<ChevronDown className={cn("transition-transform", changing && "rotate-180")} aria-hidden />- </Button>- {changing && <div className="flex w-full flex-col gap-2 border-t border-border pt-3">- {candidates.length > 0 && picker}- <div className="flex flex-wrap gap-2">- {createButton("secondary")}- <Button size="sm" variant="ghost" disabled={Boolean(busy)}- onClick={() => void leadChanged("remove", () => setSocietyTeamLead(group.group_id, null))}>- {t("society.lead.remove")}- </Button>- </div>- </div>}- </header>-- {problem && <p role="alert" className="text-sm text-destructive">{problem}</p>}-- <form onSubmit={(event) => void submitGoal(event)} className="flex flex-col gap-2">- <label htmlFor="team-goal" className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t("society.lead.goal_label")}</label>- <Textarea id="team-goal" value={goalText} maxLength={20000} rows={3}- placeholder={t("society.lead.goal_placeholder")}- onChange={(event) => setGoalText(event.target.value)}- onKeyDown={(event) => { if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) void submitGoal(event); }} />- <div className="flex items-center justify-between gap-3">- <p className="text-xs text-muted-foreground">{t("society.lead.goal_hint").replace("{0}", leadName)}</p>- <Button type="submit" size="sm" disabled={!goalText.trim() || Boolean(busy) || !team.lead_available}>- {busy === "goal" && <Loader2 className="animate-spin" aria-hidden />}{t("society.lead.goal_send")}- </Button>- </div>- </form>-- <Section title={t("society.lead.goals")}>- {open.length === 0 && <p className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-sm text-muted-foreground">- {t("society.lead.goals_empty").replace("{0}", leadName)}- </p>}- {open.map((goal) => <GoalCard key={goal.goal_id} goal={goal} leadName={leadName} assistantName={assistantName}- agentOf={agentOf} nameOf={nameOf} busy={busy}- onMessage={(text) => run(`message:${goal.goal_id}`, () => messageSocietyTeamGoal(group.group_id, goal.goal_id, text))}- onResume={() => void run(`resume:${goal.goal_id}`, () => resumeSocietyTeamGoal(group.group_id, goal.goal_id))}- onCancel={() => void run(`cancel:${goal.goal_id}`, () => cancelSocietyTeamGoal(group.group_id, goal.goal_id))} />)}- </Section>-- {finished.length > 0 && <details className="group/finished">- <summary className="cursor-pointer list-none text-xs font-medium uppercase tracking-wide text-muted-foreground hover:text-foreground">- <ChevronDown className="mr-1 inline h-3.5 w-3.5 -rotate-90 transition-transform group-open/finished:rotate-0" aria-hidden />- {t("society.lead.finished").replace("{0}", String(finished.length))}- </summary>- <div className="mt-2 flex flex-col gap-2">- {finished.map((goal) => <GoalCard key={goal.goal_id} goal={goal} leadName={leadName} assistantName={assistantName}- agentOf={agentOf} nameOf={nameOf} busy={busy}- onMessage={async () => false}- onResume={() => void run(`resume:${goal.goal_id}`, () => resumeSocietyTeamGoal(group.group_id, goal.goal_id))}- onCancel={() => undefined} />)}- </div>- </details>}-- <Section title={t("society.lead.mission")}>- <Textarea value={mission} maxLength={4000} rows={2} aria-label={t("society.lead.mission")}- placeholder={t("society.lead.mission_placeholder")} onChange={(event) => setMission(event.target.value)} />- {mission.trim() !== team.mission && <div>- <Button size="sm" variant="secondary" disabled={Boolean(busy)}- onClick={() => void run("mission", () => setSocietyTeamMission(group.group_id, mission))}>- {t("society.lead.mission_save")}- </Button>- </div>}- </Section>-- <Section title={t("society.lead.checkin")}>- <div className="flex flex-wrap items-center gap-3">- <BrandedSelect- ariaLabel={t("society.lead.checkin")}- testId="team-lead-checkin"- value={String(team.checkin_minutes)}- disabled={Boolean(busy)}- onValueChange={(value) => void run("checkin", () => setSocietyTeamCheckin(group.group_id, Number(value)))}- className="w-[12rem]"- options={CHECKIN_CHOICES.map((minutes) => ({ value: String(minutes), label: t(`society.lead.checkin_${minutes}`) }))}- />- <p className="min-w-[14rem] flex-1 text-xs text-muted-foreground">{t("society.lead.checkin_hint").replace("{0}", leadName)}</p>- </div>- </Section>- </div>- </section>- );-}--function TaskRow({ task, agent, name }: { task: SocietyTeamTask; agent: SocietyAgent | undefined; name: string }) {- const t = useT();- const [shown, setShown] = useState(false);- return (- <li className="flex flex-col gap-1.5 py-2" data-testid={`team-task-${task.task_id}`}>- <div className="flex items-center gap-2">- {agent ? <AgentSwatch agent={agent} size={22} /> : null}- <span className="min-w-0 flex-1 truncate text-sm text-foreground">- <span className="font-medium">{name}</span>- <span className="text-muted-foreground"> · {task.title}</span>- </span>- {task.result && <button type="button" aria-expanded={shown} onClick={() => setShown((value) => !value)}- className="shrink-0 rounded-md px-1.5 py-0.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground">- {t(shown ? "society.lead.hide_result" : "society.lead.show_result")}- </button>}- <StateChip state={task.state} label={t(`society.lead.task_state_${task.state}`)} />- </div>- {shown && <div className="ml-7 rounded-lg bg-secondary/50 px-3 py-2 text-sm"><Prose text={task.result} /></div>}- </li>- );-}--function GoalCard({ goal, leadName, assistantName, agentOf, nameOf, busy, onMessage, onResume, onCancel }: {- goal: SocietyTeamGoal;- leadName: string;- assistantName: string;- agentOf: (id: string) => SocietyAgent | undefined;- nameOf: (id: string) => string;- busy: string;- onMessage: (text: string) => Promise<boolean>;- onResume: () => void;- onCancel: () => void;-}) {- const t = useT();- const [reply, setReply] = useState("");- const waiting = goal.state === "needs_input";- const live = goal.state === "running" || waiting;- const source = goal.source === "jarvis" ? t("society.lead.source_jarvis").replace("{0}", assistantName)- : goal.source === "lead" ? t("society.lead.source_lead").replace("{0}", leadName)- : goal.source === "assignment" ? t("society.lead.source_assignment") : "";- // The title is the goal's first line, cut short when it is long. Show the- // line in full as the heading and only what the text adds to it below.- const text = goal.text.trim();- const firstLine = text.split("\n", 1)[0].trim();- const stem = goal.title.endsWith("\u2026") ? goal.title.slice(0, -1).trimEnd() : goal.title;- const ownsTitle = stem.length > 0 && firstLine.replace(/\s+/g, " ").startsWith(stem);- const heading = ownsTitle ? firstLine : goal.title;- const detailText = ownsTitle ? text.slice(text.indexOf(firstLine) + firstLine.length).trim() : text;- const detail = goal.note.startsWith("error:") ? goal.note.slice(6) : "";- const note = goal.state !== "paused" && goal.state !== "failed" ? ""- : detail ? t("society.lead.note_error").replace("{0}", detail)- : NOTE_KEYS.has(goal.note) ? t(`society.lead.note_${goal.note}`) : "";-- const send = async (event: FormEvent) => {- event.preventDefault();- const text = reply.trim();- if (text && await onMessage(text)) setReply("");- };-- return (- <article className={cn("flex flex-col gap-3 rounded-xl border bg-card p-4", waiting ? "border-warning/50" : "border-border")}- data-testid={`team-goal-${goal.goal_id}`} data-state={goal.state}>- <header className="flex items-start gap-3">- <div className="min-w-0 flex-1">- <h4 className="text-sm font-semibold text-foreground">{heading}</h4>- {detailText && <p className="mt-1 whitespace-pre-wrap text-sm text-muted-foreground">{detailText}</p>}- {source && <p className="mt-1 text-xs text-muted-foreground">{source}</p>}- </div>- <StateChip state={goal.state} label={t(`society.lead.state_${goal.state}`)} />- </header>-- {note && <p className="text-sm text-muted-foreground">{note}</p>}-- {goal.tasks.length > 0 && <ul className="divide-y divide-border border-y border-border">- {goal.tasks.map((task) => <TaskRow key={task.task_id} task={task} agent={agentOf(task.agent_id)} name={nameOf(task.agent_id)} />)}- </ul>}- {goal.tasks.length === 0 && goal.state === "running" && <p className="text-xs text-muted-foreground">{t("society.lead.tasks_none").replace("{0}", leadName)}</p>}-- {goal.report && <div className="flex flex-col gap-1">- <p className="text-xs font-medium text-muted-foreground">- {t(waiting ? "society.lead.question" : "society.lead.report").replace("{0}", leadName)}- </p>- <div className="rounded-lg bg-secondary/50 px-3 py-2 text-sm"><Prose text={goal.report} /></div>- </div>}-- {live && <form onSubmit={(event) => void send(event)} className="flex items-end gap-2">- <Textarea value={reply} rows={1} maxLength={20000} className="min-h-[36px] flex-1"- aria-label={t(waiting ? "society.lead.answer_placeholder" : "society.lead.message_placeholder").replace("{0}", leadName)}- placeholder={t(waiting ? "society.lead.answer_placeholder" : "society.lead.message_placeholder").replace("{0}", leadName)}- onChange={(event) => setReply(event.target.value)}- onKeyDown={(event) => { if (event.key === "Enter" && !event.shiftKey) void send(event); }} />- <Button type="submit" size="sm" variant={waiting ? "default" : "secondary"} disabled={!reply.trim() || Boolean(busy)}>- {t("society.lead.send")}- </Button>- </form>}-- {goal.state !== "done" && goal.state !== "cancelled" && <div className="flex flex-wrap justify-end gap-2">- {goal.state === "paused" && <Button size="sm" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.resume")}</Button>}- {goal.state === "failed" && <Button size="sm" variant="secondary" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.retry")}</Button>}- {goal.state === "queued" && <Button size="sm" variant="secondary" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.start_now")}</Button>}- {goal.state !== "failed" && <Button size="sm" variant="ghost" disabled={Boolean(busy)} onClick={onCancel}>- {t(goal.state === "queued" ? "society.lead.remove_goal" : "society.lead.stop")}- </Button>}- </div>}- </article>- );-}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadPanel.test.tsxnew file mode 100644index 0000000000..f5c233b4e1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadPanel.test.tsx@@ -0,0 +1,251 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { SocietyChatGroup, SocietyTeam, SocietyTeamGoal, SocietyTeamTask } from "@/lib/societyChatGroups";+import type { SocietyAgent } from "../data";+import { TeamLeadPanel, initiativeMode } from "./TeamLeadPanel";++const api = vi.hoisted(() => ({+ setLead: vi.fn(),+ createLead: vi.fn(),+ setMission: vi.fn(),+ setCheckin: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+}));++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("../AgentSwatch", () => ({ AgentSwatch: () => <i data-testid="swatch" /> }));+vi.mock("./AgentChatPanel", () => ({ Prose: ({ text }: { text: string }) => <p>{text}</p> }));+vi.mock("@/components/ui/select", () => ({+ BrandedSelect: ({ options, onValueChange, testId, value }: {+ options: { value: string; label: string }[]; onValueChange: (value: string) => void; testId: string; value: string;+ }) => <div data-testid={testId} data-value={value}>+ {options.map((option) => <button key={option.value} type="button" onClick={() => onValueChange(option.value)}>{option.label}</button>)}+ </div>,+}));+vi.mock("@/lib/societyChatGroups", () => ({+ TEAM_GOAL_OPEN: ["queued", "running", "needs_input", "paused"],+ setSocietyTeamLead: api.setLead,+ createSocietyTeamLead: api.createLead,+ setSocietyTeamMission: api.setMission,+ setSocietyTeamCheckin: api.setCheckin,+ resumeSocietyTeamGoal: api.resume,+ cancelSocietyTeamGoal: api.cancel,+}));++const agent = (agentId: string, name: string, tier = "specialist", state = "idle") => ({+ agentId, name, tier, title: `${name} title`, lifecycle: "active", state, chatSessionId: `society:${agentId}`,+}) as unknown as SocietyAgent;+const roster = [+ agent("jarvis", "Jarvis", "lead"), agent("boss", "Boss", "orchestrator"), agent("scout", "Scout"),+ agent("writer", "Writer", "specialist", "paused"),+];+const group: SocietyChatGroup = {+ group_id: "team", name: "Launch", members: ["jarvis", "boss", "scout", "writer"], created_ms: 1, updated_ms: 1, lead_agent_id: "boss",+};++function team(over: Partial<SocietyTeam> = {}): SocietyTeam {+ return {+ group_id: "team", lead_agent_id: "boss", lead_available: true, mission: "", checkin_minutes: 0, initiative: false,+ goals: [], working: false, max_lead_turns: 24, ...over,+ };+}++function goal(over: Partial<SocietyTeamGoal> = {}): SocietyTeamGoal {+ return {+ goal_id: "g1", group_id: "team", lead_agent_id: "boss", title: "Launch the page", text: "Launch the page",+ state: "running", report: "", note: "", lead_turns: 1, source: "chat", created_ms: 1, updated_ms: 1, done_ms: null,+ tasks: [], ...over,+ };+}++function task(over: Partial<SocietyTeamTask> = {}): SocietyTeamTask {+ return {+ task_id: "t1", goal_id: "g1", agent_id: "scout", title: "Research", brief: "Find three", state: "running",+ result: "", reviewed: false, created_ms: 1, updated_ms: 1, done_ms: null, ...over,+ };+}++interface Mounted {+ run: ReturnType<typeof vi.fn>;+ leadChanged: ReturnType<typeof vi.fn>;+ onOpenAgent: ReturnType<typeof vi.fn>;+ onSetupOpen: ReturnType<typeof vi.fn>;+}++function mount(value: SocietyTeam, setupOpen = false): Mounted {+ const run = vi.fn(async (_key: string, action: () => Promise<SocietyTeam>) => { await action(); return true; });+ const leadChanged = vi.fn(async (_key: string, action: () => Promise<SocietyTeam>) => { await action(); return true; });+ const onOpenAgent = vi.fn();+ const onSetupOpen = vi.fn();+ render(<TeamLeadPanel team={value} group={group} roster={roster} busy="" setupOpen={setupOpen} onSetupOpen={onSetupOpen}+ run={run} leadChanged={leadChanged} onOpenAgent={onOpenAgent} />);+ return { run, leadChanged, onOpenAgent, onSetupOpen };+}++beforeEach(() => {+ for (const fn of Object.values(api)) {+ fn.mockReset();+ fn.mockImplementation(async () => team());+ }+});+afterEach(cleanup);++it("reads the three ways a lead works from the check-in and its initiative", () => {+ expect(initiativeMode({ checkin_minutes: 0, initiative: false })).toBe("off");+ expect(initiativeMode({ checkin_minutes: 0, initiative: true })).toBe("off");+ expect(initiativeMode({ checkin_minutes: 60, initiative: false })).toBe("watch");+ expect(initiativeMode({ checkin_minutes: 240, initiative: true })).toBe("drive");+});++it("says there is nothing in progress and points at the chat", () => {+ mount(team());+ expect(screen.getByText("society.lead.now_empty")).toBeTruthy();+ expect(screen.queryByText("society.lead.next")).toBeNull();+ expect(screen.queryByTestId("team-lead-finished")).toBeNull();+});++it("shows the goal in progress with every task, and a result only when asked", () => {+ mount(team({+ goals: [goal({+ text: "Launch the page\nBy Friday, in German.",+ tasks: [task(), task({ task_id: "t2", agent_id: "writer", title: "Copy", state: "done", result: "Draft is ready." })],+ })],+ }));+ const card = within(screen.getByTestId("team-goal-g1"));+ expect(card.getByRole("heading", { name: "Launch the page" })).toBeTruthy();+ expect(card.getByText("By Friday, in German.")).toBeTruthy();+ expect(card.getByText("society.lead.state_running")).toBeTruthy();+ expect(within(screen.getByTestId("team-task-t1")).getByText("society.lead.task_state_running")).toBeTruthy();+ const done = within(screen.getByTestId("team-task-t2"));+ expect(done.queryByText("Draft is ready.")).toBeNull();+ fireEvent.click(done.getByRole("button", { name: "society.lead.show_result" }));+ expect(done.getByText("Draft is ready.")).toBeTruthy();+});++it("shows the lead's question and sends the person to the chat for the answer", () => {+ mount(team({ goals: [goal({ state: "needs_input", report: "Which market?" })] }));+ const card = within(screen.getByTestId("team-goal-g1"));+ expect(card.getByText("society.lead.question")).toBeTruthy();+ expect(card.getByText("Which market?")).toBeTruthy();+ expect(card.getByText("society.lead.answer_in_chat")).toBeTruthy();+ // The answer is a chat message, so the card carries no text field of its own.+ expect(card.queryByRole("textbox")).toBeNull();+});++it("continues a paused goal, with the reason it stopped, and stops one in progress", async () => {+ const { run } = mount(team({ goals: [goal({ state: "paused", note: "turn_budget" })] }));+ expect(screen.getByText("society.lead.note_turn_budget")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "society.lead.resume" }));+ await waitFor(() => expect(api.resume).toHaveBeenCalledWith("team", "g1"));+ expect(run.mock.calls[0][0]).toBe("resume:g1");+ fireEvent.click(screen.getByRole("button", { name: "society.lead.stop" }));+ await waitFor(() => expect(api.cancel).toHaveBeenCalledWith("team", "g1"));+});++it("lists what waits behind the current goal", () => {+ mount(team({ goals: [goal(), goal({ goal_id: "g2", title: "Write the post", text: "Write the post", state: "queued", created_ms: 2 })] }));+ expect(screen.getByText("society.lead.next")).toBeTruthy();+ const queued = within(screen.getByTestId("team-goal-g2"));+ expect(queued.getByRole("button", { name: "society.lead.start_now" })).toBeTruthy();+ expect(queued.getByRole("button", { name: "society.lead.remove_goal" })).toBeTruthy();+});++it("shows each member with what it is on, and opens its chat", () => {+ const { onOpenAgent } = mount(team({ goals: [goal({ tasks: [task()] })] }));+ expect(screen.queryByTestId("team-member-boss")).toBeNull();+ expect(screen.queryByTestId("team-member-jarvis")).toBeNull();+ const scout = within(screen.getByTestId("team-member-scout"));+ expect(scout.getByText("Research")).toBeTruthy();+ expect(scout.getByText("society.lead.member_working")).toBeTruthy();+ const writer = within(screen.getByTestId("team-member-writer"));+ expect(writer.getByText("Writer title")).toBeTruthy();+ expect(writer.getByText("society.lead.member_paused")).toBeTruthy();+ fireEvent.click(screen.getByTestId("team-member-scout"));+ expect(onOpenAgent).toHaveBeenCalledWith("scout");+});++it("keeps finished goals folded, one line each, and opens a report on request", async () => {+ mount(team({+ goals: [+ goal({ goal_id: "d1", title: "Old launch", text: "Old launch", state: "done", report: "Shipped." }),+ goal({ goal_id: "f1", title: "Broken", text: "Broken", state: "failed", note: "error:boom" }),+ ],+ }));+ const fold = screen.getByRole("button", { name: "society.lead.finished" });+ expect(fold.getAttribute("aria-expanded")).toBe("false");+ expect(screen.queryByTestId("team-goal-d1")).toBeNull();+ fireEvent.click(fold);+ expect(screen.queryByText("Shipped.")).toBeNull();+ fireEvent.click(screen.getByTestId("team-goal-d1"));+ expect(screen.getByText("Shipped.")).toBeTruthy();+ fireEvent.click(screen.getByTestId("team-goal-f1"));+ expect(screen.getByText("society.lead.note_error")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "society.lead.retry" }));+ await waitFor(() => expect(api.resume).toHaveBeenCalledWith("team", "f1"));+});++it("folds a long report until the person asks for all of it", () => {+ const long = "A ".repeat(400);+ mount(team({ goals: [goal({ report: long })] }));+ const more = screen.getByRole("button", { name: "society.lead.show_more" });+ expect(more.getAttribute("aria-expanded")).toBe("false");+ fireEvent.click(more);+ expect(screen.getByRole("button", { name: "society.lead.show_less" }).getAttribute("aria-expanded")).toBe("true");+});++it("keeps the setup folded until it is opened", () => {+ const { onSetupOpen } = mount(team());+ expect(screen.queryByLabelText("society.lead.mission")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "society.lead.setup" }));+ expect(onSetupOpen).toHaveBeenCalledWith(true);+});++it("switches how the lead works: only when asked, watching, or taking the initiative", async () => {+ mount(team(), true);+ expect(screen.getByTestId("team-initiative-off").getAttribute("aria-checked")).toBe("true");+ expect(screen.queryByTestId("team-lead-checkin")).toBeNull();+ fireEvent.click(screen.getByTestId("team-initiative-watch"));+ await waitFor(() => expect(api.setCheckin).toHaveBeenCalledWith("team", 240, false));+ fireEvent.click(screen.getByTestId("team-initiative-drive"));+ await waitFor(() => expect(api.setCheckin).toHaveBeenCalledWith("team", 240, true));+});++it("changes the rhythm without changing the way, and asks for a mission to drive from", async () => {+ mount(team({ checkin_minutes: 60, initiative: true }), true);+ expect(screen.getByTestId("team-initiative-drive").getAttribute("aria-checked")).toBe("true");+ expect(screen.getByRole("note").textContent).toBe("society.lead.initiative_needs_mission");+ expect(screen.getByTestId("team-lead-checkin").getAttribute("data-value")).toBe("60");+ fireEvent.click(within(screen.getByTestId("team-lead-checkin")).getByText("society.lead.checkin_1440"));+ await waitFor(() => expect(api.setCheckin).toHaveBeenCalledWith("team", 1440, true));+ fireEvent.click(screen.getByTestId("team-initiative-off"));+ await waitFor(() => expect(api.setCheckin).toHaveBeenCalledWith("team", 0, false));+ // Choosing the way that is already on changes nothing.+ api.setCheckin.mockClear();+ fireEvent.click(screen.getByTestId("team-initiative-drive"));+ expect(api.setCheckin).not.toHaveBeenCalled();+});++it("saves the mission only when it changed", async () => {+ mount(team({ mission: "Ship the launch.", checkin_minutes: 60, initiative: true }), true);+ expect(screen.queryByRole("note")).toBeNull();+ expect(screen.queryByRole("button", { name: "society.lead.mission_save" })).toBeNull();+ fireEvent.change(screen.getByLabelText("society.lead.mission"), { target: { value: "Ship it by Friday." } });+ fireEvent.click(screen.getByRole("button", { name: "society.lead.mission_save" }));+ await waitFor(() => expect(api.setMission).toHaveBeenCalledWith("team", "Ship it by Friday."));+});++it("changes who leads: another member, a new lead, or nobody", async () => {+ const { leadChanged } = mount(team(), true);+ const picker = screen.getByTestId("team-lead-pick");+ expect(within(picker).queryByText("Boss")).toBeNull();+ expect(within(picker).queryByText("Jarvis")).toBeNull();+ fireEvent.click(within(picker).getByText("Writer"));+ fireEvent.click(screen.getByRole("button", { name: "society.lead.make" }));+ await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", "writer"));+ fireEvent.click(screen.getByTestId("team-lead-create"));+ await waitFor(() => expect(api.createLead).toHaveBeenCalledWith("team"));+ fireEvent.click(screen.getByRole("button", { name: "society.lead.remove" }));+ await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", null));+ expect(leadChanged.mock.calls.map((call) => call[0])).toEqual(["pick", "create", "remove"]);+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadPanel.tsxnew file mode 100644index 0000000000..d31f21d61f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadPanel.tsx@@ -0,0 +1,413 @@+/**+ * The team beside its lead's chat: what the team works on now, what waits,+ * who is on it, what is finished, and how the lead works (mission, initiative,+ * who leads).+ *+ * The chat is where the person talks to the lead. This panel is where they+ * look, and it holds the few controls that are not a sentence: stop a goal,+ * continue a paused one, set the team up.+ */+import { useEffect, useRef, useState, type ReactNode } from "react";+import { ChevronDown, Crown, Loader2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { BrandedSelect } from "@/components/ui/select";+import { Textarea } from "@/components/ui/textarea";+import { useT } from "@/i18n";+import {+ TEAM_GOAL_OPEN,+ cancelSocietyTeamGoal,+ createSocietyTeamLead,+ resumeSocietyTeamGoal,+ setSocietyTeamCheckin,+ setSocietyTeamLead,+ setSocietyTeamMission,+ type SocietyChatGroup,+ type SocietyTeam,+ type SocietyTeamGoal,+ type SocietyTeamTask,+} from "@/lib/societyChatGroups";+import { societyDisplayName } from "@/lib/societyDisplayName";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";+import type { SocietyAgent } from "../data";+import { AgentSwatch } from "../AgentSwatch";+import { Prose } from "./AgentChatPanel";++/** How a lead works without being asked. */+export type InitiativeMode = "off" | "watch" | "drive";+/** The server's check-in intervals that are "on" (jarvis/society/team_lead.py CHECKIN_MINUTES). */+const RHYTHMS = [60, 240, 1440] as const;+const DEFAULT_RHYTHM = 240;+const MODES: readonly InitiativeMode[] = ["off", "watch", "drive"];+/** Reasons a goal waits that have their own sentence; anything else shows as written. */+const NOTE_KEYS = new Set([+ "society_paused", "interrupted", "turn_budget", "lead_busy", "lead_unavailable", "stalled",+]);+/** A report longer than this starts folded. */+const LONG_TEXT = 320;++export function initiativeMode(team: Pick<SocietyTeam, "checkin_minutes" | "initiative">): InitiativeMode {+ return team.checkin_minutes === 0 ? "off" : team.initiative ? "drive" : "watch";+}++const DOT: Record<string, string> = {+ running: "bg-success",+ assigned: "bg-success",+ working: "bg-success",+ needs_input: "bg-warning",+ waiting: "bg-warning",+ paused: "bg-warning",+ queued: "bg-muted-foreground",+ idle: "bg-muted-foreground/40",+ done: "bg-foreground",+ blocked: "bg-destructive",+ failed: "bg-destructive",+ cancelled: "bg-muted-foreground",+};++function StateChip({ state, label }: { state: string; label: string }) {+ return (+ <span data-state={state}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">+ <i className={cn("h-1.5 w-1.5 rounded-full", DOT[state] ?? "bg-muted-foreground")} aria-hidden />+ {label}+ </span>+ );+}++function Section({ title, count, children }: { title: string; count?: number; children: ReactNode }) {+ return (+ <section className="flex flex-col gap-2">+ <h3 className="flex items-center gap-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">+ {title}{count ? <span className="rounded-full bg-secondary px-1.5 text-[11px] normal-case tracking-normal">{count}</span> : null}+ </h3>+ {children}+ </section>+ );+}++/** A section that folds; its heading is the switch. */+function Fold({ title, open, onToggle, testId, children }: {+ title: string; open: boolean; onToggle: () => void; testId?: string; children: ReactNode;+}) {+ return (+ <section className="flex flex-col gap-2" data-testid={testId}>+ <button type="button" aria-expanded={open} onClick={onToggle}+ className="flex items-center gap-1 rounded-sm text-left text-xs font-medium uppercase tracking-wide text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <ChevronDown className={cn("h-3.5 w-3.5 transition-transform", !open && "-rotate-90")} aria-hidden />{title}+ </button>+ {open ? children : null}+ </section>+ );+}++/** Long text folded to a few lines until the person asks for all of it. */+function Folded({ text }: { text: string }) {+ const t = useT();+ const [all, setAll] = useState(false);+ const long = text.length > LONG_TEXT;+ return (+ <div className="rounded-lg bg-secondary/50 px-3 py-2 text-sm">+ <div className={cn(long && !all && "max-h-24 overflow-hidden")}><Prose text={text} /></div>+ {long && <button type="button" aria-expanded={all} onClick={() => setAll((value) => !value)}+ className="mt-1 rounded-sm text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground">+ {t(all ? "society.lead.show_less" : "society.lead.show_more")}+ </button>}+ </div>+ );+}++function TaskRow({ task, agent, name }: { task: SocietyTeamTask; agent: SocietyAgent | undefined; name: string }) {+ const t = useT();+ const [shown, setShown] = useState(false);+ return (+ <li className="flex flex-col gap-1.5 py-2" data-testid={`team-task-${task.task_id}`}>+ <div className="flex items-center gap-2">+ {agent ? <AgentSwatch agent={agent} size={20} /> : null}+ <span className="min-w-0 flex-1 text-sm text-foreground">+ <span className="block truncate font-medium">{name}</span>+ <span className="block truncate text-xs text-muted-foreground" title={task.title}>{task.title}</span>+ </span>+ <StateChip state={task.state} label={t(`society.lead.task_state_${task.state}`)} />+ </div>+ {task.result && <button type="button" aria-expanded={shown} onClick={() => setShown((value) => !value)}+ className="self-start rounded-sm text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground">+ {t(shown ? "society.lead.hide_result" : "society.lead.show_result")}+ </button>}+ {shown && <Folded text={task.result} />}+ </li>+ );+}++interface GoalProps {+ goal: SocietyTeamGoal;+ leadName: string;+ assistantName: string;+ agentOf: (id: string) => SocietyAgent | undefined;+ nameOf: (id: string) => string;+ busy: string;+ onResume: () => void;+ onCancel: () => void;+}++function GoalCard({ goal, leadName, assistantName, agentOf, nameOf, busy, onResume, onCancel }: GoalProps) {+ const t = useT();+ const waiting = goal.state === "needs_input";+ const source = goal.source === "jarvis" ? t("society.lead.source_jarvis").replace("{0}", assistantName)+ : goal.source === "lead" ? t("society.lead.source_lead").replace("{0}", leadName)+ : goal.source === "assignment" ? t("society.lead.source_assignment") : "";+ // The title is the goal's first line, cut short when it is long. Show the+ // line in full as the heading and only what the text adds to it below.+ const text = goal.text.trim();+ const firstLine = text.split("\n", 1)[0].trim();+ const stem = goal.title.endsWith("…") ? goal.title.slice(0, -1).trimEnd() : goal.title;+ const ownsTitle = stem.length > 0 && firstLine.replace(/\s+/g, " ").startsWith(stem);+ const heading = ownsTitle ? firstLine : goal.title;+ const detailText = ownsTitle ? text.slice(text.indexOf(firstLine) + firstLine.length).trim() : text === goal.title ? "" : text;+ const detail = goal.note.startsWith("error:") ? goal.note.slice(6) : "";+ const note = goal.state !== "paused" && goal.state !== "failed" ? ""+ : detail ? t("society.lead.note_error").replace("{0}", detail)+ : NOTE_KEYS.has(goal.note) ? t(`society.lead.note_${goal.note}`) : "";+ const closed = goal.state === "done" || goal.state === "cancelled";++ return (+ <article className={cn("flex flex-col gap-2.5 rounded-xl border bg-card p-3", waiting ? "border-warning/50" : "border-border")}+ data-testid={`team-goal-${goal.goal_id}`} data-state={goal.state}>+ <header className="flex items-start gap-2">+ <div className="min-w-0 flex-1">+ <h4 className="line-clamp-3 text-sm font-semibold text-foreground [overflow-wrap:anywhere]" title={heading}>{heading}</h4>+ {detailText && <p className="mt-1 line-clamp-3 whitespace-pre-wrap text-xs text-muted-foreground" title={detailText}>{detailText}</p>}+ {source && <p className="mt-1 text-xs text-muted-foreground">{source}</p>}+ </div>+ <StateChip state={goal.state} label={t(`society.lead.state_${goal.state}`)} />+ </header>++ {note && <p className="text-xs text-muted-foreground">{note}</p>}++ {goal.tasks.length > 0 && <ul className="divide-y divide-border border-y border-border">+ {goal.tasks.map((task) => <TaskRow key={task.task_id} task={task} agent={agentOf(task.agent_id)} name={nameOf(task.agent_id)} />)}+ </ul>}+ {goal.tasks.length === 0 && goal.state === "running" && <p className="text-xs text-muted-foreground">{t("society.lead.tasks_none").replace("{0}", leadName)}</p>}++ {goal.report && <div className="flex flex-col gap-1">+ <p className="text-xs font-medium text-muted-foreground">+ {t(waiting ? "society.lead.question" : "society.lead.report").replace("{0}", leadName)}+ </p>+ <Folded text={goal.report} />+ </div>}+ {waiting && <p className="text-xs font-medium text-warning">{t("society.lead.answer_in_chat").replace("{0}", leadName)}</p>}++ {!closed && <div className="flex flex-wrap justify-end gap-2">+ {goal.state === "paused" && <Button size="sm" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.resume")}</Button>}+ {goal.state === "failed" && <Button size="sm" variant="secondary" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.retry")}</Button>}+ {goal.state === "queued" && <Button size="sm" variant="secondary" disabled={Boolean(busy)} onClick={onResume}>{t("society.lead.start_now")}</Button>}+ {goal.state !== "failed" && <Button size="sm" variant="ghost" disabled={Boolean(busy)} onClick={onCancel}>+ {t(goal.state === "queued" ? "society.lead.remove_goal" : "society.lead.stop")}+ </Button>}+ </div>}+ </article>+ );+}++/** A finished goal: one line until opened. */+function FinishedRow(props: GoalProps) {+ const t = useT();+ const [open, setOpen] = useState(false);+ const { goal } = props;+ if (open) {+ return <div className="flex flex-col gap-1">+ <GoalCard {...props} />+ <button type="button" onClick={() => setOpen(false)}+ className="self-end rounded-sm text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground">{t("society.lead.show_less")}</button>+ </div>;+ }+ return (+ <button type="button" aria-expanded={false} onClick={() => setOpen(true)} data-testid={`team-goal-${goal.goal_id}`} data-state={goal.state}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <i className={cn("h-1.5 w-1.5 shrink-0 rounded-full", DOT[goal.state] ?? "bg-muted-foreground")} aria-hidden />+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{goal.title}</span>+ <span className="shrink-0 text-xs text-muted-foreground">{t(`society.lead.state_${goal.state}`)}</span>+ </button>+ );+}++interface PanelProps {+ team: SocietyTeam;+ group: SocietyChatGroup;+ roster: SocietyAgent[];+ busy: string;+ setupOpen: boolean;+ onSetupOpen: (open: boolean) => void;+ /** Run one team action; the answer replaces the team, a refusal shows as written. */+ run: (key: string, action: () => Promise<SocietyTeam>) => Promise<boolean>;+ /** As `run`, for an action that changes who leads (the roster and the group change too). */+ leadChanged: (key: string, action: () => Promise<SocietyTeam>) => Promise<boolean>;+ onOpenAgent: (id: string) => void;+}++export function TeamLeadPanel({ team, group, roster, busy, setupOpen, onSetupOpen, run, leadChanged, onOpenAgent }: PanelProps) {+ const t = useT();+ const assistantName = useEventStore((s) => s.assistantName);+ const [finishedOpen, setFinishedOpen] = useState(false);+ const [picked, setPicked] = useState("");+ const [mission, setMission] = useState(team.mission);+ const savedMission = useRef(team.mission);++ // The saved mission fills the field until the person starts editing it.+ useEffect(() => {+ const previous = savedMission.current;+ savedMission.current = team.mission;+ setMission((current) => (current === previous ? team.mission : current));+ }, [team.mission]);++ const agentOf = (id: string | null | undefined) => roster.find((agent) => agent.agentId === id);+ const nameOf = (id: string | null | undefined) => {+ const agent = agentOf(id);+ return agent ? societyDisplayName(agent, assistantName) : (id ?? "");+ };+ const leadName = nameOf(team.lead_agent_id);+ const everyone = group.members.map(agentOf).filter((agent): agent is SocietyAgent => Boolean(agent));+ const members = everyone.filter((agent) => agent.tier !== "lead" && agent.agentId !== team.lead_agent_id && agent.lifecycle !== "archived");++ const open = team.goals.filter((goal) => TEAM_GOAL_OPEN.includes(goal.state));+ const now = open.filter((goal) => goal.state !== "queued").sort((a, b) => a.created_ms - b.created_ms);+ const next = open.filter((goal) => goal.state === "queued").sort((a, b) => a.created_ms - b.created_ms);+ const finished = team.goals.filter((goal) => !TEAM_GOAL_OPEN.includes(goal.state));+ /** What each member is on right now, from the goals in progress. */+ const taskOf = (agentId: string) => now.flatMap((goal) => goal.tasks)+ .find((task) => task.agent_id === agentId && ["waiting", "assigned", "running"].includes(task.state));++ const card = (goal: SocietyTeamGoal) => ({+ goal, leadName, assistantName, agentOf, nameOf, busy,+ onResume: () => void run(`resume:${goal.goal_id}`, () => resumeSocietyTeamGoal(group.group_id, goal.goal_id)),+ onCancel: () => void run(`cancel:${goal.goal_id}`, () => cancelSocietyTeamGoal(group.group_id, goal.goal_id)),+ });++ const mode = initiativeMode(team);+ const rhythm = team.checkin_minutes || DEFAULT_RHYTHM;+ const setMode = (nextMode: InitiativeMode, minutes = rhythm) => void run("initiative", () =>+ setSocietyTeamCheckin(group.group_id, nextMode === "off" ? 0 : minutes, nextMode === "drive"));++ return (+ <aside data-testid="team-lead-panel" aria-label={t("society.lead.panel_title")}+ className="flex min-h-0 w-[340px] shrink-0 flex-col gap-5 overflow-y-auto border-l border-border bg-background px-4 py-4 max-xl:absolute max-xl:inset-y-0 max-xl:right-0 max-xl:z-10 max-xl:w-[min(340px,100%)] max-xl:shadow-float">+ <Section title={t("society.lead.now")}>+ {now.length === 0 && <p className="rounded-xl border border-dashed border-border px-3 py-4 text-center text-sm text-muted-foreground">+ {t("society.lead.now_empty").replace("{0}", leadName)}+ </p>}+ {now.map((goal) => <GoalCard key={goal.goal_id} {...card(goal)} />)}+ </Section>++ {next.length > 0 && <Section title={t("society.lead.next")} count={next.length}>+ {next.map((goal) => <GoalCard key={goal.goal_id} {...card(goal)} />)}+ </Section>}++ <Section title={t("society.lead.members")}>+ {members.length === 0 && <p className="text-sm text-muted-foreground">{t("society.lead.members_empty")}</p>}+ <ul className="flex flex-col">+ {members.map((agent) => {+ const task = taskOf(agent.agentId);+ const state = task ? "working" : agent.state;+ return <li key={agent.agentId}>+ <button type="button" onClick={() => onOpenAgent(agent.agentId)} data-testid={`team-member-${agent.agentId}`}+ className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <AgentSwatch agent={agent} size={26} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">{societyDisplayName(agent, assistantName)}</span>+ <span className="block truncate text-xs text-muted-foreground">{task ? task.title : agent.title}</span>+ </span>+ <StateChip state={state} label={t(`society.lead.member_${state}`)} />+ </button>+ </li>;+ })}+ </ul>+ </Section>++ {finished.length > 0 && <Fold title={t("society.lead.finished").replace("{0}", String(finished.length))}+ open={finishedOpen} onToggle={() => setFinishedOpen((value) => !value)} testId="team-lead-finished">+ <div className="flex flex-col gap-1">+ {finished.map((goal) => <FinishedRow key={goal.goal_id} {...card(goal)} onCancel={() => undefined} />)}+ </div>+ </Fold>}++ <Fold title={t("society.lead.setup")} open={setupOpen} onToggle={() => onSetupOpen(!setupOpen)} testId="team-lead-setup">+ <div className="flex flex-col gap-4 pt-1">+ <div className="flex flex-col gap-2">+ <label htmlFor="team-mission" className="text-sm font-medium text-foreground">{t("society.lead.mission")}</label>+ <Textarea id="team-mission" value={mission} maxLength={4000} rows={3}+ placeholder={t("society.lead.mission_placeholder")} onChange={(event) => setMission(event.target.value)} />+ {mission.trim() !== team.mission && <div>+ <Button size="sm" variant="secondary" disabled={Boolean(busy)}+ onClick={() => void run("mission", () => setSocietyTeamMission(group.group_id, mission))}>+ {t("society.lead.mission_save")}+ </Button>+ </div>}+ </div>++ <div className="flex flex-col gap-2">+ <p id="team-initiative" className="text-sm font-medium text-foreground">{t("society.lead.initiative")}</p>+ <div role="radiogroup" aria-labelledby="team-initiative" className="flex flex-col gap-1.5">+ {MODES.map((value) => <button key={value} type="button" role="radio" aria-checked={mode === value}+ disabled={Boolean(busy)} data-testid={`team-initiative-${value}`} onClick={() => { if (mode !== value) setMode(value); }}+ className={cn("flex items-start gap-2.5 rounded-lg border px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60",+ mode === value ? "border-border-strong bg-secondary" : "border-border hover:bg-secondary/60")}>+ <i className={cn("mt-1 grid h-3.5 w-3.5 shrink-0 place-items-center rounded-full border", mode === value ? "border-foreground" : "border-muted-foreground")} aria-hidden>+ {mode === value && <i className="h-1.5 w-1.5 rounded-full bg-foreground" />}+ </i>+ <span className="min-w-0">+ <span className="block text-sm font-medium text-foreground">{t(`society.lead.initiative_${value}`)}</span>+ <span className="block text-xs text-muted-foreground">{t(`society.lead.initiative_${value}_hint`).replace("{0}", leadName)}</span>+ </span>+ </button>)}+ </div>+ {mode !== "off" && <div className="flex flex-wrap items-center gap-2">+ <BrandedSelect+ ariaLabel={t("society.lead.initiative_rhythm")}+ testId="team-lead-checkin"+ value={String(rhythm)}+ disabled={Boolean(busy)}+ onValueChange={(value) => setMode(mode, Number(value))}+ className="w-[11rem]"+ options={RHYTHMS.map((minutes) => ({ value: String(minutes), label: t(`society.lead.checkin_${minutes}`) }))}+ />+ <p className="min-w-[10rem] flex-1 text-xs text-muted-foreground">{t("society.lead.initiative_cost")}</p>+ </div>}+ {mode === "drive" && !team.mission.trim() && <p role="note" className="text-xs text-warning">+ {t("society.lead.initiative_needs_mission").replace("{0}", leadName)}+ </p>}+ </div>++ <div className="flex flex-col gap-2">+ <p className="text-sm font-medium text-foreground">{t("society.lead.change")}</p>+ {members.length > 0 && <div className="flex flex-wrap items-center gap-2">+ <BrandedSelect+ ariaLabel={t("society.lead.pick")}+ testId="team-lead-pick"+ value={picked}+ onValueChange={setPicked}+ placeholder={t("society.lead.pick_placeholder")}+ className="min-w-[9rem] flex-1"+ options={members.map((agent) => ({ value: agent.agentId, label: societyDisplayName(agent, assistantName) }))}+ />+ <Button size="sm" variant="secondary" disabled={!picked || Boolean(busy)}+ onClick={() => void leadChanged("pick", () => setSocietyTeamLead(group.group_id, picked)).then((done) => { if (done) setPicked(""); })}>+ {t("society.lead.make")}+ </Button>+ </div>}+ <div className="flex flex-wrap gap-2">+ <Button size="sm" variant="secondary" disabled={Boolean(busy)} data-testid="team-lead-create"+ onClick={() => void leadChanged("create", () => createSocietyTeamLead(group.group_id))}>+ {busy === "create" ? <Loader2 className="animate-spin" aria-hidden /> : <Crown aria-hidden />}+ {t("society.lead.create")}+ </Button>+ <Button size="sm" variant="ghost" disabled={Boolean(busy)}+ onClick={() => void leadChanged("remove", () => setSocietyTeamLead(group.group_id, null))}>+ {t("society.lead.remove")}+ </Button>+ </div>+ </div>+ </div>+ </Fold>+ </aside>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadView.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadView.test.tsxnew file mode 100644index 0000000000..323f0fbfb0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadView.test.tsx@@ -0,0 +1,221 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { SocietyChatGroup, SocietyTeam, SocietyTeamGoal } from "@/lib/societyChatGroups";+import type { SocietyAgent } from "../data";+import { TeamLeadView } from "./TeamLeadView";++const api = vi.hoisted(() => ({+ team: null as unknown,+ setLead: vi.fn(),+ createLead: vi.fn(),+ setMission: vi.fn(),+ setCheckin: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+}));++/** The lead's chat store: what the action row reads and where it sends. */+const chat = vi.hoisted(() => {+ const state = {+ busy: false,+ running: false,+ activeSessionId: "society:boss" as string | null,+ send: vi.fn(async () => "sent" as const),+ disconnect: vi.fn(),+ };+ const hook = Object.assign((selector: (value: typeof state) => unknown) => selector(state), { getState: () => state });+ return { state, hook, namespaces: [] as string[] };+});++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("@/components/agentchat/reduce", () => ({ runningTurn: () => (chat.state.running ? { id: "t1" } : null) }));+vi.mock("../AgentSwatch", () => ({ AgentSwatch: () => <i data-testid="swatch" /> }));+vi.mock("@/store/agentChat", () => ({+ createAgentChatStore: (_surface: string, namespace: string) => {+ chat.namespaces.push(namespace);+ return chat.hook;+ },+}));+vi.mock("./AgentChatPanel", () => ({+ CHAT_MEASURE: "measure",+ Prose: ({ text }: { text: string }) => <p>{text}</p>,+ AgentChatPanel: ({ agent, composerExtras }: { agent: SocietyAgent; composerExtras?: ReactNode }) => (+ <div data-testid={`chat-${agent.agentId}`}>{composerExtras}</div>+ ),+}));+vi.mock("@/components/ui/select", () => ({+ BrandedSelect: ({ options, onValueChange, testId, value }: {+ options: { value: string; label: string }[]; onValueChange: (value: string) => void; testId: string; value: string;+ }) => <div data-testid={testId} data-value={value}>+ {options.map((option) => <button key={option.value} type="button" onClick={() => onValueChange(option.value)}>{option.label}</button>)}+ </div>,+}));+vi.mock("@/lib/societyChatGroups", () => ({+ TEAM_GOAL_OPEN: ["queued", "running", "needs_input", "paused"],+ useSocietyTeam: () => ({ data: api.team, isLoading: false, isError: false, error: null }),+ setSocietyTeamLead: api.setLead,+ createSocietyTeamLead: api.createLead,+ setSocietyTeamMission: api.setMission,+ setSocietyTeamCheckin: api.setCheckin,+ resumeSocietyTeamGoal: api.resume,+ cancelSocietyTeamGoal: api.cancel,+}));++const agent = (agentId: string, name: string, tier = "specialist") => ({+ agentId, name, tier, title: `${name} title`, lifecycle: "active", state: "idle", chatSessionId: `society:${agentId}`,+}) as unknown as SocietyAgent;+const roster = [agent("jarvis", "Jarvis", "lead"), agent("boss", "Boss", "orchestrator"), agent("scout", "Scout"), agent("writer", "Writer")];+const group: SocietyChatGroup = {+ group_id: "team", name: "Launch", members: ["jarvis", "boss", "scout", "writer"], created_ms: 1, updated_ms: 1, lead_agent_id: "boss",+};++function team(over: Partial<SocietyTeam> = {}): SocietyTeam {+ return {+ group_id: "team", lead_agent_id: "boss", lead_available: true, mission: "", checkin_minutes: 0, initiative: false,+ goals: [], working: false, max_lead_turns: 24, ...over,+ };+}++function goal(over: Partial<SocietyTeamGoal> = {}): SocietyTeamGoal {+ return {+ goal_id: "g1", group_id: "team", lead_agent_id: "boss", title: "Launch the page", text: "Launch the page",+ state: "running", report: "", note: "", lead_turns: 1, source: "chat", created_ms: 1, updated_ms: 1, done_ms: null,+ tasks: [], ...over,+ };+}++function mount(onOpenAgent = vi.fn()) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}><TeamLeadView group={group} roster={roster} onOpenAgent={onOpenAgent} /></QueryClientProvider>);+ return onOpenAgent;+}++beforeEach(() => {+ for (const fn of [api.setLead, api.createLead, api.setMission, api.setCheckin, api.resume, api.cancel]) {+ fn.mockReset();+ fn.mockImplementation(async () => api.team);+ }+ chat.state.busy = false;+ chat.state.running = false;+ chat.state.activeSessionId = "society:boss";+ chat.state.send.mockClear();+ chat.state.disconnect.mockClear();+ chat.namespaces.length = 0;+ window.localStorage.clear();+ window.localStorage.setItem("society.lead.panel", "open");+});+afterEach(cleanup);++it("offers to create a lead or promote a member, never the assistant", async () => {+ api.team = team({ lead_agent_id: null, lead_available: false });+ mount();+ expect(screen.getByText("society.lead.none_title")).toBeTruthy();+ expect(screen.queryByTestId("chat-boss")).toBeNull();+ const picker = screen.getByTestId("team-lead-pick");+ expect(within(picker).queryByText("Jarvis")).toBeNull();+ fireEvent.click(within(picker).getByText("Scout"));+ fireEvent.click(screen.getByRole("button", { name: "society.lead.make" }));+ await waitFor(() => expect(api.setLead).toHaveBeenCalledWith("team", "scout"));+ fireEvent.click(screen.getByTestId("team-lead-create"));+ await waitFor(() => expect(api.createLead).toHaveBeenCalledWith("team"));+});++it("is the lead's own chat, marked as the lead's, with the team beside it", () => {+ api.team = team();+ mount();+ expect(screen.getByTestId("chat-boss")).toBeTruthy();+ expect(chat.namespaces).toEqual(["group:team:lead"]);+ expect(screen.getByText("Boss")).toBeTruthy();+ expect(screen.getByText("society.lead.role")).toBeTruthy();+ expect(screen.getByTestId("team-lead-status").textContent).toBe("society.lead.status_idle");+ expect(screen.getByTestId("team-lead-panel")).toBeTruthy();+ // The chat is the one place to write: the view adds no goal form of its own.+ expect(screen.queryByRole("textbox", { name: /goal/i })).toBeNull();+});++it("sends a lead action as the person's own message", () => {+ api.team = team();+ mount();+ const actions = within(screen.getByTestId("team-lead-actions"));+ expect(actions.getAllByRole("button").map((button) => button.textContent)).toEqual([+ "society.lead.action_status", "society.lead.action_next", "society.lead.action_check", "society.lead.action_drive",+ ]);+ fireEvent.click(screen.getByTestId("team-lead-action-drive"));+ expect(chat.state.send).toHaveBeenCalledWith("society.lead.action_drive_prompt");+});++it("holds the lead actions back while a message is on its way, the lead is in a turn, or its chat is not open yet", () => {+ api.team = team();+ chat.state.busy = true;+ mount();+ expect((screen.getByTestId("team-lead-action-status") as HTMLButtonElement).disabled).toBe(true);+ cleanup();+ chat.state.busy = false;+ chat.state.running = true;+ mount();+ expect((screen.getByTestId("team-lead-action-status") as HTMLButtonElement).disabled).toBe(true);+ cleanup();+ chat.state.running = false;+ chat.state.activeSessionId = "society:someone-else";+ mount();+ expect((screen.getByTestId("team-lead-action-status") as HTMLButtonElement).disabled).toBe(true);+});++it("says in one line what the team is doing and what waits for the person", () => {+ api.team = team({ goals: [goal()] });+ mount();+ expect(screen.getByTestId("team-lead-status").textContent).toBe("society.lead.status_running");+ cleanup();+ api.team = team({ goals: [goal()], working: true });+ mount();+ expect(screen.getByTestId("team-lead-status").textContent).toBe("society.lead.working");+ cleanup();+ api.team = team({ goals: [goal({ state: "needs_input", report: "Which market?" })] });+ mount();+ expect(screen.getByTestId("team-lead-status").textContent).toBe("society.lead.status_needs_input");+ cleanup();+ api.team = team({ goals: [goal({ state: "paused", note: "turn_budget" })] });+ mount();+ expect(screen.getByTestId("team-lead-status").textContent).toBe("society.lead.status_paused");+ cleanup();+ api.team = team({ lead_available: false });+ mount();+ expect(screen.getByTestId("team-lead-status").textContent).toBe("society.lead.unavailable");+});++it("folds the team panel away and remembers it; the closed panel still counts open work", () => {+ api.team = team({ goals: [goal(), goal({ goal_id: "g2", state: "queued" })] });+ mount();+ const toggle = screen.getByTestId("team-lead-panel-toggle");+ expect(toggle.getAttribute("aria-pressed")).toBe("true");+ fireEvent.click(toggle);+ expect(screen.queryByTestId("team-lead-panel")).toBeNull();+ expect(window.localStorage.getItem("society.lead.panel")).toBe("closed");+ expect(toggle.textContent).toContain("2");+ expect(screen.getByTestId("chat-boss")).toBeTruthy();+ cleanup();+ mount();+ expect(screen.queryByTestId("team-lead-panel")).toBeNull();+});++it("shows how the lead works at a glance and opens the setup from there", () => {+ api.team = team({ checkin_minutes: 60, initiative: true });+ window.localStorage.setItem("society.lead.panel", "closed");+ mount();+ const chip = screen.getByTestId("team-lead-initiative");+ expect(chip.getAttribute("data-mode")).toBe("drive");+ expect(chip.textContent).toBe("society.lead.initiative_drive");+ fireEvent.click(chip);+ const setup = screen.getByTestId("team-lead-setup");+ expect(within(setup).getByTestId("team-initiative-drive").getAttribute("aria-checked")).toBe("true");+});++it("shows a refused action as written", async () => {+ api.team = team({ goals: [goal({ state: "paused" })] });+ api.resume.mockRejectedValueOnce(new Error("The society is paused."));+ mount();+ fireEvent.click(screen.getByRole("button", { name: "society.lead.resume" }));+ expect((await screen.findByRole("alert")).textContent).toBe("The society is paused.");+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadView.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadView.tsxnew file mode 100644index 0000000000..b08cf3c776--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamLeadView.tsx@@ -0,0 +1,248 @@+/**+ * A team's lead, as a chat.+ *+ * The person talks to the lead the way they talk to any agent: one+ * conversation, one composer. The lead plans, hands the work to the members+ * and reports in that same conversation; what the person writes there is their+ * goal, their answer or their go-ahead. What marks this chat as the lead's are+ * the actions above the composer (status, next steps, a look at the team,+ * taking the initiative) and the team panel beside it (`TeamLeadPanel`), which+ * follows the work live through `useSocietyTeam`.+ */+import { useEffect, useMemo, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { Activity, Crown, Lightbulb, ListChecks, Loader2, PanelRightClose, PanelRightOpen, Rocket } from "lucide-react";+import { runningTurn } from "@/components/agentchat/reduce";+import { Button } from "@/components/ui/button";+import { BrandedSelect } from "@/components/ui/select";+import { useT } from "@/i18n";+import {+ TEAM_GOAL_OPEN,+ createSocietyTeamLead,+ setSocietyTeamLead,+ useSocietyTeam,+ type SocietyChatGroup,+ type SocietyTeam,+} from "@/lib/societyChatGroups";+import { societyDisplayName } from "@/lib/societyDisplayName";+import { cn } from "@/lib/utils";+import { createAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";+import { useEventStore } from "@/store/events";+import type { SocietyAgent } from "../data";+import { AgentSwatch } from "../AgentSwatch";+import { AgentChatPanel, CHAT_MEASURE } from "./AgentChatPanel";+import { TeamLeadPanel, initiativeMode } from "./TeamLeadPanel";++/** What only a lead is asked: each sends its sentence as the person's message. */+const LEAD_ACTIONS = [+ { id: "status", Icon: ListChecks },+ { id: "next", Icon: Lightbulb },+ { id: "check", Icon: Activity },+ { id: "drive", Icon: Rocket },+] as const;++const PANEL_KEY = "society.lead.panel";+/** Below this width the panel lies over the conversation (`max-xl`), so it starts closed. */+const PANEL_MIN_WIDTH = 1280;++function readPanelOpen(): boolean {+ try {+ const saved = window.localStorage.getItem(PANEL_KEY);+ if (saved === "open" || saved === "closed") return saved === "open";+ } catch {+ // Storage is unavailable (a private window): the width decides.+ }+ return window.innerWidth >= PANEL_MIN_WIDTH;+}++function LeadActions({ store, sessionId, leadName }: { store: AgentChatStoreHook; sessionId: string | null; leadName: string }) {+ const t = useT();+ // Held back while a message is on its way or the lead is in a turn: an+ // action is a whole request, and a second click must not queue it twice.+ const busy = store((state) => state.busy || runningTurn(state.timeline) !== null);+ const ready = store((state) => Boolean(sessionId) && state.activeSessionId === sessionId);+ return (+ <div className="shrink-0 px-4 pt-1 sm:px-6">+ <div role="group" aria-label={t("society.lead.actions_label").replace("{0}", leadName)}+ className={cn(CHAT_MEASURE, "flex flex-wrap gap-1.5")} data-testid="team-lead-actions">+ {LEAD_ACTIONS.map(({ id, Icon }) => <button key={id} type="button" disabled={busy || !ready}+ data-testid={`team-lead-action-${id}`} title={t(`society.lead.action_${id}_prompt`)}+ onClick={() => void store.getState().send(t(`society.lead.action_${id}_prompt`))}+ className="inline-flex items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:border-border-strong hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50">+ <Icon className="h-3.5 w-3.5" aria-hidden />{t(`society.lead.action_${id}`)}+ </button>)}+ </div>+ </div>+ );+}++interface Props {+ group: SocietyChatGroup;+ roster: SocietyAgent[];+ onOpenAgent: (id: string) => void;+}++export function TeamLeadView({ group, roster, onOpenAgent }: Props) {+ const t = useT();+ const client = useQueryClient();+ const assistantName = useEventStore((s) => s.assistantName);+ const query = useSocietyTeam(group.group_id);+ const team = query.data;+ const [busy, setBusy] = useState("");+ const [problem, setProblem] = useState("");+ const [picked, setPicked] = useState("");+ const [panelOpen, setPanelOpen] = useState(readPanelOpen);+ const [setupOpen, setSetupOpen] = useState(false);+ // The lead's chat has a store of its own, so it stays open beside the members' chats.+ const leadStore = useMemo(() => createAgentChatStore("society", `group:${group.group_id}:lead`), [group.group_id]);+ useEffect(() => () => leadStore.getState().disconnect(), [leadStore]);++ const agentOf = (id: string | null | undefined) => roster.find((agent) => agent.agentId === id);+ const lead = agentOf(team?.lead_agent_id);+ const leadName = lead ? societyDisplayName(lead, assistantName) : (team?.lead_agent_id ?? "");+ // The assistant already leads every agent; a team lead is one of the others.+ const candidates = group.members.map(agentOf)+ .filter((agent): agent is SocietyAgent => Boolean(agent) && agent!.tier !== "lead" && agent!.lifecycle !== "archived");++ /** Run one team action: the answer replaces the team, a refusal shows as written. */+ const run = async (key: string, action: () => Promise<SocietyTeam>): Promise<boolean> => {+ if (busy) return false;+ setBusy(key);+ setProblem("");+ try {+ client.setQueryData(["society", "team", group.group_id], await action());+ return true;+ } catch (cause) {+ setProblem(cause instanceof Error ? cause.message : String(cause));+ return false;+ } finally {+ setBusy("");+ }+ };+ /** A lead change also changes the roster (tier) and the group (members). */+ const leadChanged = async (key: string, action: () => Promise<SocietyTeam>): Promise<boolean> => {+ if (!(await run(key, action))) return false;+ setPicked("");+ await Promise.all([+ client.invalidateQueries({ queryKey: ["society", "chat-groups"] }),+ client.invalidateQueries({ queryKey: ["society", "roster"] }),+ ]);+ return true;+ };++ const togglePanel = (open: boolean) => {+ setPanelOpen(open);+ try {+ window.localStorage.setItem(PANEL_KEY, open ? "open" : "closed");+ } catch {+ // Storage is unavailable: the choice holds for this visit.+ }+ };+ const openSetup = () => {+ togglePanel(true);+ setSetupOpen(true);+ };++ if (query.isLoading) {+ return <p className="m-auto p-6 text-sm text-muted-foreground" role="status">{t("society.lead.loading")}</p>;+ }+ if (query.isError || !team) {+ return <p className="m-auto p-6 text-sm text-destructive" role="alert">{String(query.error ?? "")}</p>;+ }++ if (!team.lead_agent_id) {+ return (+ <section className="flex min-h-0 flex-1 flex-col overflow-y-auto bg-background" data-testid="team-lead-view">+ <div className="mx-auto flex w-full max-w-[36rem] flex-col gap-4 px-6 py-12">+ <span className="grid h-11 w-11 place-items-center rounded-xl bg-secondary text-foreground"><Crown className="h-5 w-5" aria-hidden /></span>+ <h2 className="text-lg font-semibold text-foreground">{t("society.lead.none_title")}</h2>+ <p className="text-sm text-muted-foreground">{t("society.lead.none_body")}</p>+ <div>+ <Button size="sm" disabled={Boolean(busy)} data-testid="team-lead-create"+ onClick={() => void leadChanged("create", () => createSocietyTeamLead(group.group_id))}>+ {busy === "create" ? <Loader2 className="animate-spin" aria-hidden /> : <Crown aria-hidden />}+ {t("society.lead.create")}+ </Button>+ </div>+ {candidates.length > 0 && <>+ <p className="pt-2 text-sm font-medium text-foreground">{t("society.lead.pick")}</p>+ <div className="flex flex-wrap items-center gap-2">+ <BrandedSelect+ ariaLabel={t("society.lead.pick")}+ testId="team-lead-pick"+ value={picked}+ onValueChange={setPicked}+ placeholder={t("society.lead.pick_placeholder")}+ className="min-w-[12rem] flex-1"+ options={candidates.map((agent) => ({ value: agent.agentId, label: societyDisplayName(agent, assistantName) }))}+ />+ <Button size="sm" variant="secondary" disabled={!picked || Boolean(busy)}+ onClick={() => void leadChanged("pick", () => setSocietyTeamLead(group.group_id, picked))}>+ {t("society.lead.make")}+ </Button>+ </div>+ </>}+ {problem && <p role="alert" className="text-sm text-destructive">{problem}</p>}+ </div>+ </section>+ );+ }++ const open = team.goals.filter((goal) => TEAM_GOAL_OPEN.includes(goal.state));+ const asking = open.find((goal) => goal.state === "needs_input");+ const running = open.find((goal) => goal.state === "running");+ const paused = open.find((goal) => goal.state === "paused");+ const status = !team.lead_available ? t("society.lead.unavailable")+ : asking ? t("society.lead.status_needs_input").replace("{0}", leadName)+ : team.working ? t("society.lead.working").replace("{0}", leadName)+ : running ? t("society.lead.status_running").replace("{0}", running.title)+ : paused ? t("society.lead.status_paused").replace("{0}", paused.title)+ : t("society.lead.status_idle").replace("{0}", leadName);+ const mode = initiativeMode(team);+ const PanelIcon = panelOpen ? PanelRightClose : PanelRightOpen;++ return (+ <section className="flex min-h-0 flex-1 flex-col bg-background" data-testid="team-lead-view">+ <header className="flex shrink-0 flex-wrap items-center gap-3 border-b border-border px-4 py-2.5">+ <span className="relative grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-secondary">+ {lead ? <AgentSwatch agent={lead} size={34} /> : <Crown className="h-5 w-5" aria-hidden />}+ {lead && <span className="absolute -right-1.5 -top-1.5 grid h-5 w-5 place-items-center rounded-full border border-border bg-card text-foreground">+ <Crown className="h-3 w-3" aria-hidden />+ </span>}+ </span>+ <div className="min-w-0 flex-1">+ <p className="flex items-center gap-2">+ <span className="truncate text-base font-semibold text-foreground">{leadName}</span>+ <span className="shrink-0 rounded-full border border-border px-2 py-0.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">{t("society.lead.role")}</span>+ </p>+ <p role="status" data-testid="team-lead-status"+ className={cn("truncate text-xs", !team.lead_available ? "text-destructive" : asking ? "font-medium text-warning" : "text-muted-foreground")}>+ {status}+ </p>+ </div>+ <button type="button" onClick={openSetup} data-testid="team-lead-initiative" data-mode={mode}+ title={t(`society.lead.initiative_${mode}_hint`).replace("{0}", leadName)}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-xs text-muted-foreground hover:border-border-strong hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <i className={cn("h-1.5 w-1.5 rounded-full", mode === "off" ? "bg-muted-foreground/40" : "bg-success")} aria-hidden />+ {t(`society.lead.initiative_${mode}`)}+ </button>+ <Button size="sm" variant="ghost" aria-pressed={panelOpen} onClick={() => togglePanel(!panelOpen)} data-testid="team-lead-panel-toggle">+ <PanelIcon aria-hidden />{t("society.lead.panel_title")}+ {!panelOpen && open.length > 0 && <span className={cn("rounded-full px-1.5 text-[11px]", asking ? "bg-warning/20 text-warning" : "bg-secondary text-muted-foreground")}>{open.length}</span>}+ </Button>+ </header>++ {problem && <p role="alert" className="shrink-0 border-b border-border px-4 py-2 text-sm text-destructive">{problem}</p>}++ <div className="relative flex min-h-0 flex-1">+ <div className="min-h-0 min-w-0 flex-1">+ {lead ? <AgentChatPanel key={lead.agentId} agent={lead} roster={roster} chatStore={leadStore}+ composerExtras={<LeadActions store={leadStore} sessionId={lead.chatSessionId ?? null} leadName={leadName} />} />+ : <p className="m-auto p-6 text-center text-sm text-muted-foreground">{t("society.lead.unavailable")}</p>}+ </div>+ {panelOpen && <TeamLeadPanel team={team} group={group} roster={roster} busy={busy}+ setupOpen={setupOpen} onSetupOpen={setSetupOpen} run={run} leadChanged={leadChanged} onOpenAgent={onOpenAgent} />}+ </div>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamReportNotice.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamReportNotice.test.tsxnew file mode 100644index 0000000000..3be387812d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamReportNotice.test.tsx@@ -0,0 +1,37 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import type { NoticeItem } from "@/components/agentchat/reduce";+import { TeamReportNotice } from "./TeamReportNotice";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("@/components/agentchat/ChatMarkdown", () => ({ ChatMarkdown: ({ text }: { text: string }) => <p>{text}</p> }));++afterEach(cleanup);++function notice(status: string, over: Partial<NoticeItem> = {}): NoticeItem {+ return {+ type: "notice", id: "n-1", kind: "team_report", text: "Which market?", agentName: "Boss", agentId: "boss",+ status, tsMs: 1, data: { title: "Plan the launch" }, resolved: "", ...over,+ };+}++it.each([+ ["done", "society.lead.card_done"],+ ["needs_input", "society.lead.card_needs_input"],+ ["failed", "society.lead.card_failed"],+ ["progress", "society.lead.card_progress"],+ ["something-new", "society.lead.card_progress"],+])("shows a %s report in the chat with its goal and its words", (status, label) => {+ render(<TeamReportNotice item={notice(status)} />);+ const card = screen.getByTestId("team-report-notice");+ expect(card.getAttribute("data-status")).toBe(status);+ expect(screen.getByText(label)).toBeTruthy();+ expect(screen.getByText("· Plan the launch")).toBeTruthy();+ expect(screen.getByText("Which market?")).toBeTruthy();+});++it("shows a report whose goal has no title", () => {+ render(<TeamReportNotice item={notice("done", { data: {} })} />);+ expect(screen.getByText("society.lead.card_done")).toBeTruthy();+ expect(screen.queryByText(/^· /)).toBeNull();+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/TeamReportNotice.tsx b/jarvis/ui/web/frontend/src/components/society/chat/TeamReportNotice.tsxnew file mode 100644index 0000000000..4bebe5957b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/TeamReportNotice.tsx@@ -0,0 +1,38 @@+import { CheckCircle2, Flag, MessageCircleQuestion, XCircle } from "lucide-react";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import type { NoticeItem } from "@/components/agentchat/reduce";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++/** How each report status reads in the chat: its line, its mark, its edge. */+const LOOK = {+ done: { key: "society.lead.card_done", Icon: CheckCircle2, edge: "border-l-success", tone: "text-success" },+ needs_input: { key: "society.lead.card_needs_input", Icon: MessageCircleQuestion, edge: "border-l-warning", tone: "text-warning" },+ failed: { key: "society.lead.card_failed", Icon: XCircle, edge: "border-l-destructive", tone: "text-destructive" },+ progress: { key: "society.lead.card_progress", Icon: Flag, edge: "border-l-border-strong", tone: "text-muted-foreground" },+} as const;++/**+ * A team lead's report in its own chat: the result of a goal, an interim+ * update, a failure, or the one question the lead needs answered. The lead+ * reports with a tool, so without this card the words would sit on the team+ * panel only and the conversation would skip its most important lines.+ */+export function TeamReportNotice({ item }: { item: NoticeItem }) {+ const t = useT();+ const look = LOOK[item.status as keyof typeof LOOK] ?? LOOK.progress;+ const title = typeof item.data.title === "string" ? item.data.title : "";+ return (+ <section data-testid="team-report-notice" data-status={item.status}+ className={cn("my-2 w-full min-w-0 rounded-xl border border-border border-l-2 bg-card px-4 py-3", look.edge)}>+ <p className="flex min-w-0 items-center gap-1.5 text-xs font-medium text-muted-foreground">+ <look.Icon className={cn("h-3.5 w-3.5 shrink-0", look.tone)} aria-hidden />+ <span className="shrink-0">{t(look.key).replace("{0}", item.agentName)}</span>+ {title ? <span className="min-w-0 truncate font-normal">· {title}</span> : null}+ </p>+ <div className="mt-1.5 text-sm text-foreground [overflow-wrap:anywhere]">+ <ChatMarkdown text={item.text} className="leading-relaxed" />+ </div>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b7c43a3ce2..3d3fa3aaa5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -6365,31 +6365,21 @@"tab": "Leitung","loading": "Team wird geladen…","none_title": "Dieses Team hat noch keine Leitung",- "none_body": "Eine Leitung ist ein Agent, der das Team für dich managt. Du gibst dem Team ein Ziel; die Leitung zerlegt es in Aufgaben, verteilt sie an die Mitglieder, prüft die Ergebnisse und meldet sich bei dir, wenn alles erledigt ist.",+ "none_body": "Eine Leitung ist ein Agent, der das Team für dich führt. Du schreibst ihr wie jedem anderen Agenten: Sag, was du willst, und sie teilt die Arbeit in Aufgaben auf, verteilt sie an die Mitglieder, prüft die Ergebnisse und berichtet dir.","create": "Leitung erstellen","pick": "Oder ein Mitglied zur Leitung machen","pick_placeholder": "Mitglied auswählen","make": "Zur Leitung machen","role": "Teamleitung","rail": "Leitung: {0}",- "open_chat": "Chat öffnen",- "change": "Ändern",+ "change": "Leitung wechseln","remove": "Leitung entfernen","unavailable": "Diese Leitung ist pausiert oder wurde gelöscht. Wähle eine andere.","working": "{0} arbeitet gerade daran…",- "goal_label": "Neues Ziel für das Team",- "goal_placeholder": "Was soll das Team erreichen?",- "goal_hint": "{0} plant es, verteilt die Aufgaben und meldet sich mit dem Ergebnis.",- "goal_send": "Ziel übergeben",- "goals": "Ziele",- "goals_empty": "Kein offenes Ziel. Gib dem Team eines, {0} übernimmt ab da.","finished": "Abgeschlossen ({0})","tasks_none": "{0} plant gerade die Arbeit.","report": "Bericht von {0}","question": "{0} fragt",- "answer_placeholder": "Deine Antwort für {0}",- "message_placeholder": "Sag {0} etwas zu diesem Ziel",- "send": "Senden","stop": "Ziel stoppen","resume": "Fortsetzen","retry": "Erneut versuchen",@@ -6400,9 +6390,6 @@"mission": "Auftrag des Teams","mission_placeholder": "Wofür ist dieses Team da? Die Leitung liest das bei jedem Schritt.","mission_save": "Auftrag speichern",- "checkin": "Check-ins",- "checkin_hint": "{0} schaut von sich aus nach dem Team und handelt, wenn etwas ansteht. Jeder Check-in ist ein Durchlauf auf dem Modell der Leitung.",- "checkin_0": "Aus","checkin_60": "Jede Stunde","checkin_240": "Alle 4 Stunden","checkin_1440": "Einmal am Tag",@@ -6428,7 +6415,51 @@"note_lead_busy": "Die Leitung war zu lange in einem anderen Gespräch beschäftigt.","note_lead_unavailable": "Die Leitung ist gerade nicht verfügbar.","note_stalled": "Bei diesem Ziel hat sich nichts mehr bewegt.",- "note_error": "Der Durchlauf der Leitung ist fehlgeschlagen: {0}"+ "note_error": "Der Durchlauf der Leitung ist fehlgeschlagen: {0}",+ "panel_title": "Team",+ "status_idle": "Bereit. Schreib {0}, was das Team tun soll.",+ "status_running": "Das Team arbeitet an: {0}",+ "status_needs_input": "{0} braucht deine Antwort",+ "status_paused": "Pausiert: {0}",+ "now": "Jetzt",+ "now_empty": "Gerade läuft nichts. Schreib {0}, und das Team legt los.",+ "next": "Als Nächstes",+ "members": "Mitglieder",+ "members_empty": "Noch keine Mitglieder. Füge dem Team Agenten hinzu.",+ "member_idle": "Frei",+ "member_working": "Arbeitet",+ "member_waiting": "Wartet",+ "member_paused": "Pausiert",+ "setup": "Einrichtung",+ "answer_in_chat": "Antworte {0} im Chat.",+ "show_more": "Mehr anzeigen",+ "show_less": "Weniger anzeigen",+ "initiative": "Eigeninitiative",+ "initiative_off": "Nur auf Anfrage",+ "initiative_off_hint": "{0} arbeitet, wenn du schreibst und sobald ein Ergebnis eintrifft.",+ "initiative_watch": "Behält das Team im Blick",+ "initiative_watch_hint": "{0} schaut zusätzlich von sich aus nach dem Team und hakt bei festhängender Arbeit nach.",+ "initiative_drive": "Ergreift die Initiative",+ "initiative_drive_hint": "{0} setzt dem Team außerdem selbst das nächste Ziel aus dem Auftrag, wenn nichts offen ist.",+ "initiative_rhythm": "Wie oft",+ "initiative_cost": "Jeder Blick ist ein Durchlauf auf dem Modell der Leitung.",+ "initiative_needs_mission": "Schreib einen Auftrag für das Team, damit {0} weiß, worauf hingearbeitet wird.",+ "actions_label": "Aktionen für {0}",+ "action_status": "Status",+ "action_status_prompt": "Wo steht das Team? Gib mir einen kurzen Stand zu jedem offenen Ziel und jeder Aufgabe.",+ "action_next": "Nächste Schritte vorschlagen",+ "action_next_prompt": "Schau dir unseren Auftrag und das bisher Erledigte an. Schlag die nächsten drei Ziele für das Team vor, das wertvollste zuerst. Starte sie noch nicht.",+ "action_check": "Nach dem Team sehen",+ "action_check_prompt": "Prüf jetzt das Team-Board und kümmere dich um alles, was festhängt, blockiert ist oder wartet.",+ "action_drive": "Initiative ergreifen",+ "action_drive_prompt": "Entscheide, was unseren Auftrag gerade am meisten voranbringt, mach es unter einem kurzen Namen zum Ziel des Teams und verteile die ersten Aufgaben. Sag mir in einer Zeile, was du gestartet hast.",+ "card_done": "Bericht von {0}",+ "card_needs_input": "{0} fragt",+ "card_failed": "{0} konnte das Ziel nicht erreichen",+ "card_progress": "Zwischenstand von {0}",+ "event_update": "Ergebnisse aus dem Team ({0})",+ "event_check": "Bericht angefordert",+ "event_resumed": "Ziel fortgesetzt"},"groups": {"create": "Neues Agent-Team",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 1ba5c64b22..398010e827 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -6365,31 +6365,21 @@"tab": "Lead","loading": "Loading the team…","none_title": "This team has no lead yet",- "none_body": "A lead is an agent that manages the team for you. You give the team a goal; the lead breaks it into tasks, hands them to the members, checks what comes back and reports to you when it is done.",+ "none_body": "A lead is an agent that manages the team for you. You talk to it like to any other agent: say what you want, and it breaks the work into tasks, hands them to the members, checks what comes back and reports to you.","create": "Create a lead","pick": "Or make a member the lead","pick_placeholder": "Choose a member","make": "Make lead","role": "Team lead","rail": "Lead: {0}",- "open_chat": "Open chat",- "change": "Change",+ "change": "Change the lead","remove": "Remove lead","unavailable": "This lead is paused or was deleted. Choose another one.","working": "{0} is working on it…",- "goal_label": "New goal for the team",- "goal_placeholder": "What should the team achieve?",- "goal_hint": "{0} plans it, hands out the tasks and reports back.",- "goal_send": "Give goal",- "goals": "Goals",- "goals_empty": "No open goal. Give the team one and {0} takes it from there.","finished": "Finished ({0})","tasks_none": "{0} is planning the work.","report": "Report from {0}","question": "{0} asks",- "answer_placeholder": "Your answer for {0}",- "message_placeholder": "Tell {0} something about this goal",- "send": "Send","stop": "Stop goal","resume": "Continue","retry": "Try again",@@ -6400,9 +6390,6 @@"mission": "Team mission","mission_placeholder": "What is this team for? The lead reads this on every turn.","mission_save": "Save mission",- "checkin": "Check-ins",- "checkin_hint": "{0} looks at the team unprompted and acts when something needs it. Every check-in is one turn on the lead's model.",- "checkin_0": "Off","checkin_60": "Every hour","checkin_240": "Every 4 hours","checkin_1440": "Once a day",@@ -6428,7 +6415,51 @@"note_lead_busy": "The lead was busy in another conversation for too long.","note_lead_unavailable": "The lead is not available right now.","note_stalled": "Nothing was moving on this goal any more.",- "note_error": "The lead's turn failed: {0}"+ "note_error": "The lead's turn failed: {0}",+ "panel_title": "Team",+ "status_idle": "Ready. Tell {0} what the team should do.",+ "status_running": "The team is working on: {0}",+ "status_needs_input": "{0} needs your answer",+ "status_paused": "Paused: {0}",+ "now": "Now",+ "now_empty": "Nothing in progress. Write to {0} and the team gets going.",+ "next": "Up next",+ "members": "Members",+ "members_empty": "No members yet. Add agents to this team.",+ "member_idle": "Free",+ "member_working": "Working",+ "member_waiting": "Waiting",+ "member_paused": "Paused",+ "setup": "Setup",+ "answer_in_chat": "Answer {0} in the chat.",+ "show_more": "Show more",+ "show_less": "Show less",+ "initiative": "Initiative",+ "initiative_off": "Only when asked",+ "initiative_off_hint": "{0} works when you write and whenever a result comes in.",+ "initiative_watch": "Keeps watch",+ "initiative_watch_hint": "{0} also looks at the team unprompted and follows up on stuck work.",+ "initiative_drive": "Takes the initiative",+ "initiative_drive_hint": "{0} also sets the team's next goal from the mission when nothing is open.",+ "initiative_rhythm": "How often",+ "initiative_cost": "Each look is one turn on the lead's model.",+ "initiative_needs_mission": "Write a team mission so {0} knows what to work toward.",+ "actions_label": "Actions for {0}",+ "action_status": "Status",+ "action_status_prompt": "Where does the team stand? Give me a short status of every open goal and task.",+ "action_next": "Suggest next steps",+ "action_next_prompt": "Look at our mission and at what is finished. Suggest the next three goals for the team, the most valuable first. Do not start them yet.",+ "action_check": "Check on the team",+ "action_check_prompt": "Check the team board now and act on whatever is stuck, blocked or waiting.",+ "action_drive": "Take the initiative",+ "action_drive_prompt": "Decide what moves our mission forward most right now, make it the team's goal under a short name and hand out the first tasks. Tell me in one line what you started.",+ "card_done": "Report from {0}",+ "card_needs_input": "{0} asks",+ "card_failed": "{0} could not reach the goal",+ "card_progress": "Update from {0}",+ "event_update": "Results from the team ({0})",+ "event_check": "Asked for the report",+ "event_resumed": "Goal continued"},"groups": {"create": "New agent team",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 03cc1adbf8..01f9872e79 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -6365,31 +6365,21 @@"tab": "Líder","loading": "Cargando el equipo…","none_title": "Este equipo aún no tiene líder",- "none_body": "Un líder es un agente que dirige el equipo por ti. Tú le das un objetivo al equipo; el líder lo divide en tareas, las reparte entre los miembros, revisa lo que vuelve y te informa cuando está hecho.",+ "none_body": "Un líder es un agente que dirige el equipo por ti. Le escribes como a cualquier otro agente: di lo que quieres y él divide el trabajo en tareas, las reparte entre los miembros, revisa lo que vuelve y te informa.","create": "Crear un líder","pick": "O convertir a un miembro en líder","pick_placeholder": "Elige un miembro","make": "Hacer líder","role": "Líder del equipo","rail": "Líder: {0}",- "open_chat": "Abrir chat",- "change": "Cambiar",+ "change": "Cambiar de líder","remove": "Quitar líder","unavailable": "Este líder está en pausa o fue eliminado. Elige otro.","working": "{0} está trabajando en ello…",- "goal_label": "Nuevo objetivo para el equipo",- "goal_placeholder": "¿Qué debe lograr el equipo?",- "goal_hint": "{0} lo planifica, reparte las tareas y te informa.",- "goal_send": "Dar objetivo",- "goals": "Objetivos",- "goals_empty": "Ningún objetivo abierto. Dale uno al equipo y {0} se encarga.","finished": "Terminados ({0})","tasks_none": "{0} está planificando el trabajo.","report": "Informe de {0}","question": "{0} pregunta",- "answer_placeholder": "Tu respuesta para {0}",- "message_placeholder": "Dile algo a {0} sobre este objetivo",- "send": "Enviar","stop": "Detener objetivo","resume": "Continuar","retry": "Reintentar",@@ -6400,9 +6390,6 @@"mission": "Misión del equipo","mission_placeholder": "¿Para qué es este equipo? El líder lo lee en cada turno.","mission_save": "Guardar misión",- "checkin": "Revisiones",- "checkin_hint": "{0} revisa el equipo por su cuenta y actúa cuando algo lo necesita. Cada revisión es un turno en el modelo del líder.",- "checkin_0": "Desactivado","checkin_60": "Cada hora","checkin_240": "Cada 4 horas","checkin_1440": "Una vez al día",@@ -6428,7 +6415,51 @@"note_lead_busy": "El líder estuvo ocupado demasiado tiempo en otra conversación.","note_lead_unavailable": "El líder no está disponible ahora.","note_stalled": "Ya no avanzaba nada en este objetivo.",- "note_error": "El turno del líder falló: {0}"+ "note_error": "El turno del líder falló: {0}",+ "panel_title": "Equipo",+ "status_idle": "Listo. Dile a {0} qué debe hacer el equipo.",+ "status_running": "El equipo trabaja en: {0}",+ "status_needs_input": "{0} necesita tu respuesta",+ "status_paused": "En pausa: {0}",+ "now": "Ahora",+ "now_empty": "No hay nada en curso. Escribe a {0} y el equipo se pone en marcha.",+ "next": "A continuación",+ "members": "Miembros",+ "members_empty": "Aún no hay miembros. Añade agentes a este equipo.",+ "member_idle": "Libre",+ "member_working": "Trabajando",+ "member_waiting": "En espera",+ "member_paused": "En pausa",+ "setup": "Configuración",+ "answer_in_chat": "Responde a {0} en el chat.",+ "show_more": "Mostrar más",+ "show_less": "Mostrar menos",+ "initiative": "Iniciativa",+ "initiative_off": "Solo cuando se lo pides",+ "initiative_off_hint": "{0} trabaja cuando escribes y cada vez que llega un resultado.",+ "initiative_watch": "Vigila el equipo",+ "initiative_watch_hint": "{0} además revisa el equipo por su cuenta y da seguimiento al trabajo atascado.",+ "initiative_drive": "Toma la iniciativa",+ "initiative_drive_hint": "{0} además fija el siguiente objetivo del equipo a partir de la misión cuando no hay nada abierto.",+ "initiative_rhythm": "Con qué frecuencia",+ "initiative_cost": "Cada revisión es un turno en el modelo del líder.",+ "initiative_needs_mission": "Escribe una misión del equipo para que {0} sepa hacia dónde trabajar.",+ "actions_label": "Acciones para {0}",+ "action_status": "Estado",+ "action_status_prompt": "¿Cómo va el equipo? Dame un estado breve de cada objetivo y tarea abiertos.",+ "action_next": "Proponer próximos pasos",+ "action_next_prompt": "Mira nuestra misión y lo que ya está terminado. Propón los tres próximos objetivos para el equipo, el más valioso primero. No los inicies todavía.",+ "action_check": "Revisar el equipo",+ "action_check_prompt": "Revisa ahora el tablero del equipo y actúa sobre todo lo que esté atascado, bloqueado o en espera.",+ "action_drive": "Tomar la iniciativa",+ "action_drive_prompt": "Decide qué hace avanzar más nuestra misión ahora mismo, conviértelo en el objetivo del equipo con un nombre corto y reparte las primeras tareas. Dime en una línea qué has iniciado.",+ "card_done": "Informe de {0}",+ "card_needs_input": "{0} pregunta",+ "card_failed": "{0} no pudo alcanzar el objetivo",+ "card_progress": "Novedades de {0}",+ "event_update": "Resultados del equipo ({0})",+ "event_check": "Informe solicitado",+ "event_resumed": "Objetivo reanudado"},"groups": {"create": "Nuevo equipo de agentes",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.jsonindex 9ab6258390..543bd0e522 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json@@ -6365,31 +6365,21 @@"tab": "Líder","loading": "A carregar a equipa…","none_title": "Esta equipa ainda não tem líder",- "none_body": "Um líder é um agente que gere a equipa por ti. Dás um objetivo à equipa; o líder divide-o em tarefas, entrega-as aos membros, verifica o que regressa e informa-te quando estiver concluído.",+ "none_body": "Um líder é um agente que gere a equipa por ti. Escreves-lhe como a qualquer outro agente: diz o que queres e ele divide o trabalho em tarefas, entrega-as aos membros, verifica o que regressa e informa-te.","create": "Criar um líder","pick": "Ou torna um membro líder","pick_placeholder": "Escolhe um membro","make": "Tornar líder","role": "Líder da equipa","rail": "Líder: {0}",- "open_chat": "Abrir chat",- "change": "Alterar",+ "change": "Mudar de líder","remove": "Remover líder","unavailable": "Este líder está em pausa ou foi eliminado. Escolhe outro.","working": "{0} está a tratar disso…",- "goal_label": "Novo objetivo para a equipa",- "goal_placeholder": "O que deve a equipa alcançar?",- "goal_hint": "{0} planeia, distribui as tarefas e dá-te o ponto da situação.",- "goal_send": "Dar objetivo",- "goals": "Objetivos",- "goals_empty": "Nenhum objetivo em aberto. Dá um à equipa e {0} trata do resto.","finished": "Concluídos ({0})","tasks_none": "{0} está a planear o trabalho.","report": "Relatório de {0}","question": "{0} pergunta",- "answer_placeholder": "A tua resposta para {0}",- "message_placeholder": "Diz algo a {0} sobre este objetivo",- "send": "Enviar","stop": "Parar objetivo","resume": "Continuar","retry": "Tentar novamente",@@ -6400,9 +6390,6 @@"mission": "Missão da equipa","mission_placeholder": "Para que serve esta equipa? O líder lê isto em cada turno.","mission_save": "Guardar missão",- "checkin": "Verificações",- "checkin_hint": "{0} olha pela equipa por iniciativa própria e age quando algo o exige. Cada verificação é um turno no modelo do líder.",- "checkin_0": "Desligado","checkin_60": "De hora a hora","checkin_240": "De 4 em 4 horas","checkin_1440": "Uma vez por dia",@@ -6428,7 +6415,51 @@"note_lead_busy": "O líder esteve ocupado noutra conversa durante demasiado tempo.","note_lead_unavailable": "O líder não está disponível neste momento.","note_stalled": "Já nada avançava neste objetivo.",- "note_error": "O turno do líder falhou: {0}"+ "note_error": "O turno do líder falhou: {0}",+ "panel_title": "Equipa",+ "status_idle": "Pronto. Diz a {0} o que a equipa deve fazer.",+ "status_running": "A equipa está a trabalhar em: {0}",+ "status_needs_input": "{0} precisa da tua resposta",+ "status_paused": "Em pausa: {0}",+ "now": "Agora",+ "now_empty": "Nada em curso. Escreve a {0} e a equipa arranca.",+ "next": "A seguir",+ "members": "Membros",+ "members_empty": "Ainda não há membros. Adiciona agentes a esta equipa.",+ "member_idle": "Livre",+ "member_working": "A trabalhar",+ "member_waiting": "À espera",+ "member_paused": "Em pausa",+ "setup": "Configuração",+ "answer_in_chat": "Responde a {0} no chat.",+ "show_more": "Mostrar mais",+ "show_less": "Mostrar menos",+ "initiative": "Iniciativa",+ "initiative_off": "Só quando pedes",+ "initiative_off_hint": "{0} trabalha quando escreves e sempre que chega um resultado.",+ "initiative_watch": "Vigia a equipa",+ "initiative_watch_hint": "{0} também olha pela equipa por iniciativa própria e acompanha o trabalho parado.",+ "initiative_drive": "Toma a iniciativa",+ "initiative_drive_hint": "{0} também define o próximo objetivo da equipa a partir da missão quando nada está aberto.",+ "initiative_rhythm": "Com que frequência",+ "initiative_cost": "Cada verificação é um turno no modelo do líder.",+ "initiative_needs_mission": "Escreve uma missão da equipa para {0} saber para onde trabalhar.",+ "actions_label": "Ações para {0}",+ "action_status": "Estado",+ "action_status_prompt": "Como está a equipa? Dá-me um ponto da situação breve de cada objetivo e tarefa em aberto.",+ "action_next": "Sugerir próximos passos",+ "action_next_prompt": "Olha para a nossa missão e para o que já está concluído. Sugere os três próximos objetivos para a equipa, o mais valioso primeiro. Não os inicies ainda.",+ "action_check": "Ver como está a equipa",+ "action_check_prompt": "Verifica agora o quadro da equipa e trata de tudo o que estiver parado, bloqueado ou à espera.",+ "action_drive": "Tomar a iniciativa",+ "action_drive_prompt": "Decide o que mais faz avançar a nossa missão neste momento, torna-o o objetivo da equipa com um nome curto e distribui as primeiras tarefas. Diz-me numa linha o que iniciaste.",+ "card_done": "Relatório de {0}",+ "card_needs_input": "{0} pergunta",+ "card_failed": "{0} não conseguiu atingir o objetivo",+ "card_progress": "Ponto da situação de {0}",+ "event_update": "Resultados da equipa ({0})",+ "event_check": "Relatório pedido",+ "event_resumed": "Objetivo retomado"},"groups": {"create": "Nova equipa de agentes",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 1c59274f95..4342465b1c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -6365,31 +6365,21 @@"tab": "负责人","loading": "正在加载团队…","none_title": "这个团队还没有负责人",- "none_body": "负责人是替你管理团队的智能体。你给团队一个目标,负责人把它拆成任务、分配给成员、检查结果,并在完成后向你汇报。",+ "none_body": "负责人是替你管理团队的智能体。你像和其他智能体聊天一样给它发消息:说出你想要什么,它会把工作拆成任务、分配给成员、检查结果并向你汇报。","create": "创建负责人","pick": "或让一名成员担任负责人","pick_placeholder": "选择成员","make": "设为负责人","role": "团队负责人","rail": "负责人:{0}",- "open_chat": "打开对话",- "change": "更换",+ "change": "更换负责人","remove": "移除负责人","unavailable": "这位负责人已暂停或被删除,请另选一位。","working": "{0} 正在处理…",- "goal_label": "给团队的新目标",- "goal_placeholder": "团队要达成什么?",- "goal_hint": "{0} 会规划、分配任务并向你汇报。",- "goal_send": "下达目标",- "goals": "目标",- "goals_empty": "没有进行中的目标。给团队一个目标,{0} 会接手。","finished": "已结束({0})","tasks_none": "{0} 正在规划工作。","report": "{0} 的汇报","question": "{0} 提问",- "answer_placeholder": "你给 {0} 的回答",- "message_placeholder": "就这个目标对 {0} 说点什么",- "send": "发送","stop": "停止目标","resume": "继续","retry": "重试",@@ -6400,9 +6390,6 @@"mission": "团队使命","mission_placeholder": "这个团队是做什么的?负责人每一轮都会读到。","mission_save": "保存使命",- "checkin": "例行检查",- "checkin_hint": "{0} 会主动查看团队,并在需要时采取行动。每次检查都是负责人模型的一轮。",- "checkin_0": "关闭","checkin_60": "每小时","checkin_240": "每 4 小时","checkin_1440": "每天一次",@@ -6428,7 +6415,51 @@"note_lead_busy": "负责人在另一段对话中忙碌太久。","note_lead_unavailable": "负责人目前不可用。","note_stalled": "这个目标已经没有任何进展。",- "note_error": "负责人的这一轮失败了:{0}"+ "note_error": "负责人的这一轮失败了:{0}",+ "panel_title": "团队",+ "status_idle": "已就绪。告诉 {0} 团队该做什么。",+ "status_running": "团队正在处理:{0}",+ "status_needs_input": "{0} 需要你的回答",+ "status_paused": "已暂停:{0}",+ "now": "当前",+ "now_empty": "目前没有进行中的工作。给 {0} 发消息,团队就会开始。",+ "next": "接下来",+ "members": "成员",+ "members_empty": "还没有成员。请为这个团队添加智能体。",+ "member_idle": "空闲",+ "member_working": "处理中",+ "member_waiting": "等待中",+ "member_paused": "已暂停",+ "setup": "设置",+ "answer_in_chat": "请在对话中回答 {0}。",+ "show_more": "显示更多",+ "show_less": "收起",+ "initiative": "主动性",+ "initiative_off": "仅在被要求时",+ "initiative_off_hint": "{0} 在你发消息时以及每次有结果返回时工作。",+ "initiative_watch": "留意团队",+ "initiative_watch_hint": "{0} 还会主动查看团队,并跟进卡住的工作。",+ "initiative_drive": "主动推进",+ "initiative_drive_hint": "没有进行中的目标时,{0} 还会根据使命为团队设定下一个目标。",+ "initiative_rhythm": "频率",+ "initiative_cost": "每次查看都是负责人模型的一轮。",+ "initiative_needs_mission": "请写下团队使命,让 {0} 知道该朝什么方向努力。",+ "actions_label": "{0} 的操作",+ "action_status": "进度",+ "action_status_prompt": "团队现在进展如何?请简要说明每个进行中的目标和任务的状态。",+ "action_next": "建议下一步",+ "action_next_prompt": "看看我们的使命和已经完成的工作。为团队建议接下来的三个目标,最有价值的排在最前。先不要开始。",+ "action_check": "查看团队",+ "action_check_prompt": "现在检查团队任务板,处理所有卡住、受阻或等待中的事项。",+ "action_drive": "主动推进",+ "action_drive_prompt": "判断现在什么最能推进我们的使命,给它起一个简短的名字并设为团队目标,然后分配第一批任务。用一句话告诉我你启动了什么。",+ "card_done": "{0} 的汇报",+ "card_needs_input": "{0} 提问",+ "card_failed": "{0} 未能达成目标",+ "card_progress": "{0} 的进展",+ "event_update": "团队返回了结果({0})",+ "event_check": "已要求汇报",+ "event_resumed": "目标已继续"},"groups": {"create": "新建智能体团队",diff --git a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts b/jarvis/ui/web/frontend/src/lib/societyChatGroups.tsindex 34045a30b8..fee11e3a1d 100644--- a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts+++ b/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts@@ -147,7 +147,7 @@ export interface SocietyTeamGoal {/** Why the goal waits: a code (`turn_budget`), or `error:<detail>`. */note: string;lead_turns: number;- /** Where it came from: the team board, the assistant, the lead's own chat. */+ /** Where it came from: `chat` (the person, in the lead's chat), `board`, `jarvis`, `assignment`, or `lead` (its own initiative). */source: string;created_ms: number;updated_ms: number;@@ -163,6 +163,8 @@ export interface SocietyTeam {mission: string;/** Minutes between the lead's unprompted looks at the team; 0 = off. */checkin_minutes: number;+ /** Whether such a look may also set the team's next goal from its mission. */+ initiative: boolean;goals: SocietyTeamGoal[];/** Whether the lead is in a managing turn right now. */working: boolean;@@ -227,8 +229,8 @@ export function setSocietyTeamMission(groupId: string, mission: string) {return json<SocietyTeam>(`${teamUrl(groupId)}/mission`, { ...body({ mission }), method: "PUT" });}-export function setSocietyTeamCheckin(groupId: string, minutes: number) {- return json<SocietyTeam>(`${teamUrl(groupId)}/checkin`, { ...body({ minutes }), method: "PUT" });+export function setSocietyTeamCheckin(groupId: string, minutes: number, initiative = false) {+ return json<SocietyTeam>(`${teamUrl(groupId)}/checkin`, { ...body({ minutes, initiative }), method: "PUT" });}export function startSocietyTeamGoal(groupId: string, text: string) {diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 1dbb739834..448bd8b36b 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -729,6 +729,9 @@ class TeamMissionBody(BaseModel):class TeamCheckinBody(BaseModel):#: Minutes between the lead's unprompted looks at its team; 0 = off.minutes: int = Field(default=0, ge=0, le=1_440)+ #: Whether such a look may also set the team's next goal from its mission;+ #: left out, the team keeps the way it has.+ initiative: bool | None = Noneclass TeamGoalBody(BaseModel):@@ -818,10 +821,15 @@ async def set_team_mission(async def set_team_checkin(group_id: str, body: TeamCheckinBody, request: Request) -> dict[str, Any]:- """Switch the lead's unprompted team check-in on (0 = off). Each check-in is a turn."""+ """Switch the lead's unprompted team check-in on (0 = off). Each check-in is a turn;+ with ``initiative`` it may also set the team's next goal."""rt = await _runtime(request)try:- await rt.team_leads.set_checkin(group_id, body.minutes)+ initiative = body.initiative+ if initiative is None:+ # A caller that only changes the rhythm must not switch initiative off.+ initiative = (await rt.team_leads.checkin(group_id))[1]+ await rt.team_leads.set_checkin(group_id, body.minutes, initiative=initiative)return await rt.team_leads.snapshot(group_id)except TeamLeadError as exc:raise _team_error(exc) from excdiff --git a/tests/fakes/team_chat.py b/tests/fakes/team_chat.pyindex d12cb55ab5..8af2f7232a 100644--- a/tests/fakes/team_chat.py+++ b/tests/fakes/team_chat.py@@ -64,6 +64,13 @@ class TeamChatFake:for queue in list(self._subscribers.get(session_id, ())):queue.put_nowait(event)+ def notices(self, session_id: str) -> list[dict[str, Any]]:+ return [+ event["payload"]+ for event in self.store.list_events(session_id, tail=200)+ if event["kind"] == "notice"+ ]+# -------------------------------------------------------------- turnsasync def send(self, session_id: str, text: str, **kwargs: Any) -> str:@@ -127,3 +134,28 @@ class TeamChatFake:task.cancel()if self._turns:await asyncio.wait(set(self._turns.values()))+++class FakeTasks:+ """The slice of the task store and scheduler a routine needs."""++ def __init__(self) -> None:+ self.specs: dict[str, Any] = {}+ self.cancelled: list[str] = []++ async def schedule(self, spec: Any, **_: Any) -> str:+ self.specs[str(spec.id)] = spec+ return str(spec.id)++ async def cancel_task(self, task_id: str) -> None:+ self.cancelled.append(task_id)++ async def delete(self, task_id: str) -> None:+ self.specs.pop(task_id, None)++ async def list(self, limit: int = 1000) -> list[dict[str, Any]]:+ return [+ {"id": task_id, "title": spec.title, "state": "scheduled",+ "spec_json": spec.model_dump_json()}+ for task_id, spec in self.specs.items()+ ]diff --git a/tests/unit/society/test_team_lead.py b/tests/unit/society/test_team_lead.pyindex 95fb19f07c..b16411b63d 100644--- a/tests/unit/society/test_team_lead.py+++ b/tests/unit/society/test_team_lead.py@@ -3,7 +3,9 @@from __future__ import annotationsimport asyncio+import jsonfrom collections.abc import Callable+from contextlib import contextmanagerfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -12,11 +14,13 @@ import aiosqliteimport pytestfrom jarvis.agent_chat.store import AgentChatStore+from jarvis.core.protocols import ChatTurn, current_chat_turnfrom jarvis.society.events import MsgType, SocietyEnvelope, TeamGoalState, TeamTaskState, Tierfrom jarvis.society.lead_card import render_lead_cardfrom jarvis.society.runtime import SocietyRuntimefrom jarvis.society.store import SocietyStorefrom jarvis.society.team_lead import (+ INITIATIVE_PROMPT,MAX_LEAD_TURNS,TRACE_PREFIX,TeamLeadError,@@ -30,7 +34,7 @@ from jarvis.society.team_tools import (TeamReportTool,team_lead_tools,)-from tests.fakes.team_chat import TeamChatFake+from tests.fakes.team_chat import FakeTasks, TeamChatFakeLEAD = "society:boss"SCOUT = "society:scout"@@ -225,6 +229,25 @@ async def test_an_answer_without_open_work_is_the_report(team):assert "society_team_report" in prompts[1]+async def test_the_view_hears_when_the_turn_that_closed_a_goal_ends(team):+ rt, svc = team+ leads = rt.team_leads+ pushed: list[tuple[str, bool]] = []+ leads._publish = lambda event: pushed.append((event.reason, bool(leads._turns))) # noqa: SLF001++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ await leads.report("boss", status="done", summary="Done.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Do it")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ # The goal closed while its turn still ran; the last push comes once the+ # turn is over, so no view keeps showing the lead at work.+ await until(lambda: pushed and pushed[-1] == ("turn", False))+ assert (await leads.snapshot("team"))["working"] is False++async def test_results_arriving_during_a_lead_turn_reach_the_next_one(team):rt, svc = teamleads = rt.team_leads@@ -338,6 +361,17 @@ async def test_a_question_waits_for_the_person_and_their_answer_continues(team):await leads.tell(goal.goal_id, "Germany")await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))assert "The person says about this goal:" in seen[1] and "Germany" in seen[1]+ # Both reports are cards in the lead's chat, where the person reads along.+ def reports() -> list[dict[str, Any]]:+ return [n for n in svc.notices(LEAD) if n["kind"] == "team_report"]++ await until(lambda: len(reports()) == 2)+ cards = reports()+ assert [(n["status"], n["text"]) for n in cards] == [+ ("needs_input", "Which market?"),+ ("done", "Planned for Germany."),+ ]+ assert cards[0]["title"] == "Plan the launch" and cards[0]["agent_name"] == "Boss"with pytest.raises(TeamLeadError, match="not in progress"):await leads.tell(goal.goal_id, "More")@@ -790,6 +824,228 @@ async def test_a_lead_assigning_from_its_own_chat_opens_a_goal(team):assert "[team update for team Launch]" in svc.prompts(LEAD)[0]+# ------------------------------------------------- the person's own chat turn+++@contextmanager+def person_says(text: str, session_id: str = LEAD, *, direct_user: bool = True):+ """Run the body as a tool call inside a turn of the lead's chat."""+ token = current_chat_turn.set(+ ChatTurn(+ session_id=session_id,+ turn_id="person-turn",+ user_text=text,+ direct_user=direct_user,+ trace_id="trace",+ )+ )+ try:+ yield+ finally:+ current_chat_turn.reset(token)+++async def test_work_asked_for_in_the_leads_chat_opens_a_goal_in_the_persons_words(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[SCOUT] = asyncio.Event()+ asked = "Find out why signups dropped.\nLook at last week first.\n\n[tools: browser]"+ with person_says(asked):+ receipt = await TeamAssignTool(rt, "boss").execute(+ {"member": "Scout", "title": "Pull the numbers", "task": "Go.", "goal": "Signup drop"},+ None,+ )+ assert receipt.success+ goal = await _goal(rt, receipt.output["goal_id"])+ assert goal.origin == {"kind": "chat"} and goal.title == "Signup drop"+ assert goal.text == "Find out why signups dropped.\nLook at last week first."+ assert (await leads.snapshot("team"))["goals"][0]["source"] == "chat"++ # Without a name from the lead the goal is called by the person's first line.+ await leads.cancel(goal.goal_id)+ with person_says("Write the launch post"):+ again = await leads.assign("boss", member="writer", title="Draft", brief="Go.")+ assert (await _goal(rt, again["goal_id"])).title == "Write the launch post"+ svc.gates[SCOUT].set()+++async def test_an_answer_in_the_leads_chat_continues_a_goal_that_waits(team):+ rt, svc = team+ leads = rt.team_leads++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ await leads.report("boss", status="needs_input", summary="Which market?")+ return "I need one answer."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Plan the launch")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.NEEDS_INPUT))+ await until(lambda: svc.idle() and not leads._turns) # noqa: SLF001 — the turn is read back++ # A turn nobody typed (a check-in, another agent's message) cannot answer for the person.+ for stranger in (+ person_says("Germany", direct_user=False),+ person_says("Germany", session_id=SCOUT),+ ):+ with stranger, pytest.raises(TeamLeadError, match="answers you in this chat"):+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.NEEDS_INPUT++ svc.gates[SCOUT] = asyncio.Event()+ with person_says("Germany"):+ receipt = await leads.assign("boss", member="scout", title="Research", brief="Go.")+ assert receipt["goal_id"] == goal.goal_id+ resumed = await _goal(rt, goal.goal_id)+ assert resumed.state is TeamGoalState.RUNNING and resumed.lead_turns == 0+ svc.scripts.pop(LEAD)+ svc.gates[SCOUT].set()+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+++async def test_a_go_ahead_in_the_leads_chat_continues_a_paused_goal_but_not_past_the_switch(team):+ rt, svc = team+ leads = rt.team_leads+ svc.failing.add(LEAD)+ goal = await leads.start_goal("team", "Plan the launch")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.PAUSED))+ svc.failing.discard(LEAD)++ await rt.store.set_kill_switch(True)+ with person_says("Go on"), pytest.raises(TeamLeadError):+ await leads.report("boss", status="progress", summary="Back on it.")+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.PAUSED+ await rt.store.set_kill_switch(False)++ with person_says("Go on"):+ await leads.report("boss", status="done", summary="Finished after all.")+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.DONE+++async def test_tasks_handed_out_together_from_the_chat_share_one_goal(team):+ rt, svc = team+ leads = rt.team_leads+ svc.gates[SCOUT] = asyncio.Event()+ svc.gates[WRITER] = asyncio.Event()+ with person_says("Research it and write it up"):+ first, second = await asyncio.gather(+ leads.assign("boss", member="scout", title="Research", brief="Go."),+ leads.assign("boss", member="writer", title="Write", brief="Go."),+ )+ assert first["goal_id"] == second["goal_id"]+ goals = await leads.goals("team")+ assert len(goals) == 1 and len(await leads.tasks(goals[0].goal_id)) == 2+ svc.gates[SCOUT].set()+ svc.gates[WRITER].set()+++async def test_a_stop_wins_over_an_answer_that_is_on_its_way(team):+ rt, svc = team+ leads = rt.team_leads++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ await leads.report("boss", status="needs_input", summary="Which market?")+ return "I need one answer."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Plan the launch")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.NEEDS_INPUT))+ await until(lambda: svc.idle() and not leads._turns) # noqa: SLF001 — the turn is read back++ # The person stops the goal while the lead's call is between its checks.+ resolved = leads._goal_for_lead # noqa: SLF001 — the seam between resolving and assigning++ async def stopped_meanwhile(lead_id: str, **kwargs: Any) -> Any:+ found = await resolved(lead_id, **kwargs)+ await leads.cancel(found.goal_id)+ return found++ leads._goal_for_lead = stopped_meanwhile # type: ignore[method-assign] # noqa: SLF001+ with person_says("Germany"), pytest.raises(TeamLeadError, match="no longer in progress"):+ await leads.assign("boss", member="scout", title="Research", brief="Go.")+ assert (await _goal(rt, goal.goal_id)).state is TeamGoalState.CANCELLED+ assert await leads.tasks(goal.goal_id) == []+++async def test_the_persons_turn_is_followed_up_like_a_managing_turn(team):+ rt, svc = team+ leads = rt.team_leads+ seen: list[str] = []++ async def boss(text: str, kwargs: dict[str, Any]) -> str:+ seen.append(text)+ if len(seen) == 1:+ await leads.report("boss", status="needs_input", summary="Which market?")+ return "I need one answer."+ await leads.report("boss", status="done", summary="Germany it is.")+ return "Closed."++ svc.scripts[LEAD] = boss+ goal = await leads.start_goal("team", "Plan the launch")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.NEEDS_INPUT))+ await until(lambda: svc.idle() and not leads._turns) # noqa: SLF001 — the turn is read back++ # The lead answers the person in plain words and reports nothing: the+ # goal it reopened is asked once for a typed report.+ with person_says("Germany"):+ await leads.report("boss", status="progress", summary="Noted: Germany.")+ await leads.person_turn_ended("boss", ok=True, final="Noted.")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ assert "[team goal check for team Launch]" in seen[1]++ # A turn that touched no goal, or failed, starts nothing.+ sent = len(svc.sent)+ await leads.person_turn_ended("boss", ok=True, final="Hello.")+ await leads.person_turn_ended("scout", ok=True, final="Hello.")+ await asyncio.sleep(0.05)+ assert len(svc.sent) == sent+++async def test_the_runtime_reports_the_persons_turn_in_a_leads_chat(team):+ rt, _ = team+ ended: list[tuple[str, bool, str]] = []++ async def record(lead_id: str, *, ok: bool, final: str = "") -> None:+ ended.append((lead_id, ok, final))++ rt.team_leads.person_turn_ended = record # type: ignore[method-assign]++ def completion(session_id: str, direct_user: bool, status: str) -> Any:+ events = [+ {"kind": "user_message", "payload": {"text": "Hi"}},+ {"kind": "assistant_text", "payload": {"text": "On it."}},+ {"kind": "turn_finished", "payload": {"status": status}},+ ]+ turn = ChatTurn(+ session_id=session_id, turn_id="t", user_text="Hi", direct_user=direct_user,+ trace_id="x",+ )+ return SimpleNamespace(turn=turn, events_json=json.dumps(events))++ for session_id, direct_user, status in (+ (LEAD, True, "error"),+ (LEAD, False, "done"),+ (SCOUT, True, "done"),+ ):+ await rt.turn_completed(+ SimpleNamespace(session_id=session_id), completion(session_id, direct_user, status)+ )+ await until(lambda: ended)+ assert ended == [("boss", False, "On it.")]+++async def test_the_board_names_what_was_finished_so_it_is_not_done_twice(team):+ rt, svc = team+ leads = rt.team_leads+ svc.replies[LEAD] = "Shipped the page."+ goal = await leads.start_goal("team", "Launch the page")+ await until(_state_is(rt, goal.goal_id, TeamGoalState.DONE))+ board = await leads.board("boss")+ assert board["goals"] == []+ assert board["finished"] == [+ {"title": "Launch the page", "state": "done", "report": "Shipped the page."}+ ]++# ---------------------------------------------------------------- the tools@@ -843,6 +1099,9 @@ async def test_the_assign_tool_composes_a_brief_and_refuses_strangers(team):report = TeamReportTool(rt, "boss")bad = await report.execute({"status": "maybe", "summary": "x"}, None)assert not bad.success+ update = await report.execute({"status": "progress", "summary": "Half way."}, None)+ assert update.success and update.output["recorded"] == "progress"+ assert "do not repeat the report" in update.output["next"]stranger = await TeamReportTool(rt, "scout").execute({"status": "done", "summary": "x"}, None)@@ -876,31 +1135,6 @@ async def test_jarvis_card_names_the_teams_that_have_a_lead(team):# ------------------------------------------------------- check-ins, storage-class FakeTasks:- """The slice of the task store and scheduler a routine needs."""-- def __init__(self) -> None:- self.specs: dict[str, Any] = {}- self.cancelled: list[str] = []-- async def schedule(self, spec: Any, **_: Any) -> str:- self.specs[str(spec.id)] = spec- return str(spec.id)-- async def cancel_task(self, task_id: str) -> None:- self.cancelled.append(task_id)-- async def delete(self, task_id: str) -> None:- self.specs.pop(task_id, None)-- async def list(self, limit: int = 1000) -> list[dict[str, Any]]:- return [- {"id": task_id, "title": spec.title, "state": "scheduled",- "spec_json": spec.model_dump_json()}- for task_id, spec in self.specs.items()- ]--async def test_a_check_in_is_an_agent_routine_the_person_switches_on(team):rt, _ = teamfake = FakeTasks()@@ -923,6 +1157,32 @@ async def test_a_check_in_is_an_agent_routine_the_person_switches_on(team):assert fake.specs == {}+async def test_a_check_in_with_initiative_may_set_the_next_goal(team):+ rt, _ = team+ fake = FakeTasks()+ rt.task_services = lambda: (fake, fake)+ leads = rt.team_leads+ assert (await leads.snapshot("team"))["initiative"] is False++ await leads.set_checkin("team", 60)+ assert await leads.checkin("team") == (60, False)+ assert (await leads.snapshot("team"))["initiative"] is False++ await leads.set_checkin("team", 240, initiative=True)+ (spec,) = fake.specs.values()+ assert {"team-checkin:team", "team-initiative:team"} <= set(spec.tags)+ assert INITIATIVE_PROMPT in spec.action.prompt and "take the initiative" in INITIATIVE_PROMPT+ snapshot = await leads.snapshot("team")+ assert snapshot["checkin_minutes"] == 240 and snapshot["initiative"] is True++ # A new lead inherits how the team is watched.+ await leads.set_lead("team", "writer")+ (moved,) = fake.specs.values()+ assert "agent:writer" in moved.tags and "team-initiative:team" in moved.tags+ await leads.set_checkin("team", 0, initiative=True)+ assert fake.specs == {} and await leads.checkin("team") == (0, False)++async def test_an_older_database_gains_the_lead_columns(tmp_path: Path):path = tmp_path / "society.db"conn = await aiosqlite.connect(path)diff --git a/tests/unit/ui/web/test_society_team_routes.py b/tests/unit/ui/web/test_society_team_routes.pyindex 0d2ca6c216..4987c11cb8 100644--- a/tests/unit/ui/web/test_society_team_routes.py+++ b/tests/unit/ui/web/test_society_team_routes.py@@ -14,7 +14,7 @@ from fastapi.testclient import TestClientfrom jarvis.agent_chat.store import AgentChatStorefrom jarvis.society.runtime import SocietyRuntimefrom jarvis.ui.web.society_routes import router-from tests.fakes.team_chat import TeamChatFake+from tests.fakes.team_chat import FakeTasks, TeamChatFake@pytest.fixture@@ -104,6 +104,27 @@ def test_naming_and_creating_a_lead(client):assert body["agent"]["agent_id"] in members+def test_check_ins_carry_the_initiative_switch(client):+ c, runtime, _ = client+ group_id = _team(c)+ url = f"/api/society/chat-groups/{group_id}"+ assert c.put(f"{url}/lead", json={"agent_id": "scout"}).status_code == 200+ tasks = FakeTasks()+ runtime.task_services = lambda: (tasks, tasks)++ driving = c.put(f"{url}/checkin", json={"minutes": 60, "initiative": True})+ assert driving.status_code == 200, driving.text+ assert driving.json()["checkin_minutes"] == 60 and driving.json()["initiative"] is True+ # A caller that only changes the rhythm keeps the way the team has.+ slower = c.put(f"{url}/checkin", json={"minutes": 240})+ assert slower.json()["checkin_minutes"] == 240 and slower.json()["initiative"] is True+ watching = c.put(f"{url}/checkin", json={"minutes": 240, "initiative": False})+ assert watching.json()["checkin_minutes"] == 240 and watching.json()["initiative"] is False+ assert c.put(f"{url}/checkin", json={"minutes": 7}).status_code == 422+ off = c.put(f"{url}/checkin", json={"minutes": 0, "initiative": True})+ assert off.json()["checkin_minutes"] == 0 and off.json()["initiative"] is False++def test_mission_is_saved_and_shown(client):c, _, _ = clientgroup_id = _team(c)