Skip to content

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.

feat(team-threads): pick each member's seat, model and effort; one seat twice; swarms of up to eight (#692)

Ruben Lütke334e009053d0
diff --git a/docs/agentic-ide-team-threads.md b/docs/agentic-ide-team-threads.md
index 2fdc41a981..f7c610136f 100644
--- a/docs/agentic-ide-team-threads.md
+++ b/docs/agentic-ide-team-threads.md
@@ -17,13 +17,26 @@ working: **Peers** (the default, described first below) and **Planner and
builder** (see [its own section](#planner-and-builder)). The team is suggested
from what is connected on this machine: one seat per model family, a coding CLI
before a provider API (by default Claude, GPT and Gemini when all three are
-there). The person can swap, add and remove members, two to four in total, then
+there). Each member is a row the person sets: which coding agent or provider,
+which model (from the models that seat offers, minus the ones hidden on the
+API Keys page) and, where the seat has levels, how much effort. **Add member**
+asks which seat joins; nothing is added that the person did not pick. A team
+has two to eight members, and one seat may sit in it several times: two Claude
+Code members on different models, or a swarm of reviewers. Then the person
writes the task and sends it. That one prompt is all the team needs.
-A member starts on its coding agent's own default model. When that default is
-refused on the member's first turn (a CLI configured for a model the signed-in
-account may not use), the member is asked once more on the first model the CLI
-lists for the account, and the thread says so.
+A member left on **Default model** starts on its coding agent's own default.
+When that default is refused on the member's first turn (a CLI configured for
+a model the signed-in account may not use), the member is asked once more on
+the first model the CLI lists for the account, and the thread says so. A model
+the person picked is used as it is.
+
+Every member is a session of its own, named after its seat; a model the person
+picked follows the name ("Anthropic Claude · Opus 5.5"), so two members on one
+seat read apart everywhere: on the canvas, in the chat tabs, in the story and
+in the notices. Members that still share a name are numbered ("Anthropic
+Claude 1", "Anthropic Claude 2"). Where a name is cut short, its model or
+number stays readable.
With one model family connected the team still works (two rows of that family,
or the same seat twice) and the thread says what such a team cannot give:
@@ -43,7 +56,13 @@ member reads.
| Review | The others review the change against the plan. Findings go back to the builder, who fixes or rebuts them; then they review again. |
The thread is done when every reviewer approves. A reply without a readable
-verdict never counts as agreement. A vote belongs to one plan: when a plan is
+verdict never counts as agreement.
+
+In a big team each member would read seven plans and seven challenges at full
+length. What several members wrote is therefore passed on within one shared
+budget per prompt (about 48,000 characters): short contributions stay whole,
+and only the long ones are shortened, all to the same length and never below
+2,000 characters each. A vote belongs to one plan: when a plan is
rewritten, it is voted on again.
Reviewers read the change as a diff between two snapshots of the folder (the
@@ -66,7 +85,10 @@ canvas sits above the chats.
(the file it reads, the command it runs, with the time), waiting for the
person, waiting for its turn, finished, or gone with the reason. The person
is a node too. The layout is fixed per team size and fitted to the frame,
- so nothing moves while the team works; it can be zoomed and moved.
+ so nothing moves while the team works; it can be zoomed and moved. Five to
+ eight members sit evenly on a ring with the person on top, member 1 on the
+ person's left, so every pair has a line of its own and no box covers
+ another.
- **Lines.** Every line is a real handoff the coordinator made, never
decoration: the task and the person's messages to every member, a plan to
the members who read it, a vote or a plan review back to its author, a build
@@ -75,13 +97,18 @@ canvas sits above the chats.
"3 findings, 1 blocking", "Change, 4 files", "Agrees"), with a count when
more went that way. A line a member is working on right now flows; the lines
of the current step and the step before it are drawn with their labels;
- older lines stay as faint traces whose label shows on hover.
+ older lines stay as faint traces whose label shows on hover. When more than
+ ten lines would carry a label (a swarm, where everyone sends everyone a
+ plan), only the picked member's lines, the picked line and the line under
+ the pointer show theirs, and the picked member's lines stand out.
- **Chats.** The side column has a tab per member with that member's own
conversation as it streams in: its turns, tool calls, diffs and words. What
the coordinator handed the member is folded to its first line. **Follow**
(on by default) shows whoever is working; picking a tab or a node turns it
off. A member's thread is read from its own socket, one per member however
- many places show it, opened through the app's connect budget.
+ many places show it, opened through the app's connect budget. When the tabs
+ do not fit, arrows at the ends scroll them and the picked tab always scrolls
+ into view.
- **Exchanges.** A click on a line shows everything the two members exchanged,
both ways, in order, the newest unfolded. Escape or the close button returns
to the chat.
@@ -117,7 +144,7 @@ canvas sits above the chats.
| Bound | Default |
|---|---|
| Working time (paused time does not count) | 90 minutes |
-| Model turns | 40 |
+| Model turns | 40; 10 per member from five members on (80 for eight) |
| Master plans before the thread asks | 3 rounds |
| Review rounds before the thread asks | 3 rounds |
| One turn | 30 minutes |
@@ -158,7 +185,9 @@ The second mode gives each member a role instead of making everyone plan:
The start form shows a role per member: by default member 1 plans, member 2
builds and every further member reviews. A team needs exactly one planner and
one builder. Nobody checks only their own work: with two members the builder
-reviews the plan and the planner reviews each step.
+reviews the plan and the planner reviews each step. With more members every
+reviewer reads the plan and every step, and a step is accepted only when all
+of them approve, so a swarm of six reviewers checks each step six times over.
| Step | What happens |
|---|---|
@@ -197,8 +226,12 @@ reviewer.
## API and CLI
`/api/team-threads` (see `jarvis/ui/web/team_thread_routes.py`): list, `seats`,
-start, read, `message`, `pause`, `resume`, `accept`, `stop`, delete. Start takes
-`mode` (`peers` or `planner_builder`) and a `role` per seat; a thread's read
+start, read, `message`, `pause`, `resume`, `accept`, `stop`, delete. `seats`
+lists each seat's `model_options` (id, label, effort levels) and `efforts`,
+`max_members` and the default turn bound per team size (`max_turns`). Start
+takes up to eight seats, the same seat more than once, a `model` and an
+`effort` per seat (an effort the seat does not offer is refused), `mode`
+(`peers` or `planner_builder`) and a `role` per seat; a thread's read
carries `mode`, each member's `role` and, for planner and builder, `plan`. The routes
are reachable through the CLI's `api` group like every other route.
diff --git a/jarvis/agent_chat/team/engine.py b/jarvis/agent_chat/team/engine.py
index faea078e6c..67918fedba 100644
--- a/jarvis/agent_chat/team/engine.py
+++ b/jarvis/agent_chat/team/engine.py
@@ -45,7 +45,10 @@ log = logging.getLogger(__name__)
__all__ = ["MAX_MEMBERS", "MIN_MEMBERS", "Limits", "SeatPick", "TeamError", "TeamThreads"]
MIN_MEMBERS: Final[int] = 2
-MAX_MEMBERS: Final[int] = 4
+#: A swarm: more members than this cost more than another review catches.
+MAX_MEMBERS: Final[int] = 8
+#: Model turns each member brings to a team's default turn bound.
+_TURNS_PER_MEMBER: Final[int] = 10
_MAX_TASK: Final[int] = 40_000
_MAX_TEXT: Final[int] = 60_000
@@ -89,6 +92,9 @@ class SeatPick:
effort: str = ""
name: str = ""
family: str = ""
+ #: The model's short display name, where the person picked the model;
+ #: it follows the seat's name ("Anthropic Claude · Opus 5.5").
+ model_label: str = ""
#: A model the account lists. Tried once when the seat's own default is
#: refused on the member's first turn, so a CLI configured for a model the
#: signed-in account may not use does not cost the team a member.
@@ -111,8 +117,13 @@ class Limits:
max_cost_usd: float = 0.0
@classmethod
- def of(cls, raw: dict[str, Any] | None) -> Limits:
- base = cls()
+ def for_team(cls, members: int) -> Limits:
+ """The default bounds of a team this size: a bigger team takes more turns per step."""
+ return cls(max_turns=max(cls().max_turns, _TURNS_PER_MEMBER * members))
+
+ @classmethod
+ def of(cls, raw: dict[str, Any] | None, *, members: int = 0) -> Limits:
+ base = cls.for_team(members)
raw = raw or {}
def whole(key: str, low: int, high: int) -> int:
@@ -228,7 +239,7 @@ class TeamThreads(PlannedWork):
task=task,
cwd=str(folder),
lang=self._language(task),
- limits=asdict(Limits.of(limits)),
+ limits=asdict(Limits.of(limits, members=len(seats))),
members=members,
mode=mode,
work=work,
@@ -1301,8 +1312,18 @@ def _roles_of(mode: str, roles: list[str] | None, count: int) -> list[str]:
def _unique_names(seats: list[SeatPick]) -> list[str]:
- """Each member's display name; two seats of one kind are told apart by number."""
- base = [(seat.name or seat.model or seat.provider).strip() or seat.provider for seat in seats]
+ """Each member's display name, unique in the team.
+
+ A member is named after its seat, and a model the person picked follows
+ the name ("Anthropic Claude · Opus 5.5"), so two members on one seat with
+ different models read apart. Members that still share a name are told
+ apart by number ("Anthropic Claude 1", "Anthropic Claude 2").
+ """
+ base = []
+ for seat in seats:
+ name = (seat.name or seat.model or seat.provider).strip() or seat.provider
+ label = seat.model_label.strip()
+ base.append(f"{name} · {label}" if label and not name.endswith(label) else name)
counts: dict[str, int] = {}
names = []
for name in base:
diff --git a/jarvis/agent_chat/team/plan_prompts.py b/jarvis/agent_chat/team/plan_prompts.py
index 4894fd700e..ff40539321 100644
--- a/jarvis/agent_chat/team/plan_prompts.py
+++ b/jarvis/agent_chat/team/plan_prompts.py
@@ -10,7 +10,8 @@ from __future__ import annotations
from typing import Any, Final
-from .prompts import MAX_QUOTE
+from .prompts import quote as _quote
+from .prompts import quotes
from .signals import BLOCK, PLAN_BLOCK, STEP_BLOCK
__all__ = [
@@ -49,14 +50,6 @@ def _frame(name: str, team: list[tuple[str, str]], cwd: str, step: str) -> str:
)
-def _quote(label: str, text: str) -> str:
- # A member's text must not close its own block and speak outside of it.
- body = (text or "").replace(f"</{label}>", "").strip()
- if len(body) > MAX_QUOTE:
- body = body[:MAX_QUOTE].rstrip() + "\n[shortened]"
- return f"<{label}>\n{body}\n</{label}>"
-
-
def _notes(notes: list[str]) -> str:
if not notes:
return ""
@@ -159,10 +152,12 @@ def write_plan(
"the point and give the reason in one line, and write the complete plan again."
)
parts.append(_quote("your last proposal", plan_text(previous)))
- parts += [
- _quote(f"objections by {member}", "\n".join(f"- {item}" for item in items))
- for member, items in objections.items()
- ]
+ parts += quotes(
+ [
+ (f"objections by {member}", "\n".join(f"- {item}" for item in items))
+ for member, items in objections.items()
+ ]
+ )
if unreadable:
step += (
f"\n\nYour last reply had no plan the coordinator could read: {unreadable} Write "
@@ -247,9 +242,9 @@ def build_step(
"it, or show with evidence why it is not a defect. Fix minor findings where that is "
"cheap, and go through the findings one by one in your report."
)
- parts += [
- _quote(f"findings by {member}", _findings(items)) for member, items in findings.items()
- ]
+ parts += quotes(
+ [(f"findings by {member}", _findings(items)) for member, items in findings.items()]
+ )
return (
_frame(name, team, cwd, step)
+ f"\n\nThe task:\n{task.strip()}"
@@ -388,7 +383,7 @@ def final_fix(
"findings where that is cheap. Verify again. Finish with a report that goes through "
"the findings one by one and says what you did."
)
- parts = [
- _quote(f"findings by {member}", _findings(items)) for member, items in findings.items()
- ]
+ parts = quotes(
+ [(f"findings by {member}", _findings(items)) for member, items in findings.items()]
+ )
return _frame(name, team, cwd, step) + _material(parts) + _notes(notes)
diff --git a/jarvis/agent_chat/team/prompts.py b/jarvis/agent_chat/team/prompts.py
index 62be02ef71..0cdfcccd6a 100644
--- a/jarvis/agent_chat/team/prompts.py
+++ b/jarvis/agent_chat/team/prompts.py
@@ -12,18 +12,29 @@ from typing import Any, Final
from .signals import BLOCK
__all__ = [
+ "MAX_MATERIAL",
"MAX_QUOTE",
+ "MIN_QUOTE",
"build",
"challenge",
"draft",
"fix",
"master_plan",
+ "quote",
+ "quotes",
"review",
+ "share",
"vote",
]
#: How much of one contribution is passed on to the others.
MAX_QUOTE: Final[int] = 12_000
+#: How much the contributions of several members take together in one prompt.
+#: A swarm of eight would otherwise hand each member seven plans and seven
+#: challenges at full length; the budget is shared out instead.
+MAX_MATERIAL: Final[int] = 48_000
+#: What one contribution keeps however many share the budget.
+MIN_QUOTE: Final[int] = 2_000
_NO_EDITS: Final[str] = (
"You may read the project and run read-only checks, but change no files in this step."
@@ -42,14 +53,45 @@ def _frame(name: str, roster: list[str], cwd: str, step: str) -> str:
)
-def _quote(label: str, text: str) -> str:
+def _body(label: str, text: str) -> str:
# A peer's text must not close its own block and speak outside of it.
- body = (text or "").replace(f"</{label}>", "").strip()
- if len(body) > MAX_QUOTE:
- body = body[:MAX_QUOTE].rstrip() + "\n[shortened]"
+ return (text or "").replace(f"</{label}>", "").strip()
+
+
+def quote(label: str, text: str, limit: int = MAX_QUOTE) -> str:
+ """One contribution as a block of material, at most ``limit`` characters of it."""
+ body = _body(label, text)
+ if len(body) > limit:
+ body = body[:limit].rstrip() + "\n[shortened]"
return f"<{label}>\n{body}\n</{label}>"
+def share(lengths: list[int], budget: int = MAX_MATERIAL) -> int:
+ """The most characters each of several contributions may keep.
+
+ Short contributions keep all of their text and leave what they did not
+ use to the long ones; only the long ones are shortened, all to the same
+ length. Never below ``MIN_QUOTE`` and never above ``MAX_QUOTE``.
+ """
+ left = budget
+ ordered = sorted(lengths)
+ for index, length in enumerate(ordered):
+ fair = left // (len(ordered) - index)
+ if length > fair:
+ return max(MIN_QUOTE, min(MAX_QUOTE, fair))
+ left -= length
+ return MAX_QUOTE
+
+
+def quotes(items: list[tuple[str, str]], budget: int = MAX_MATERIAL) -> list[str]:
+ """Several members' contributions, shortened together to fit one prompt."""
+ limit = share([len(_body(label, text)) for label, text in items], budget)
+ return [quote(label, text, limit) for label, text in items]
+
+
+_quote = quote
+
+
def _notes(notes: list[str]) -> str:
if not notes:
return ""
@@ -87,7 +129,7 @@ def challenge(
"list what the one master plan must contain. Concede a point that is better than "
f"yours; do not defend your plan out of habit. {_NO_EDITS}"
)
- parts = [_quote(f"plan by {peer}", text) for peer, text in drafts.items()]
+ parts = quotes([(f"plan by {peer}", text) for peer, text in drafts.items()])
return _frame(name, roster, cwd, step) + _material(parts) + _notes(notes)
@@ -110,10 +152,12 @@ def master_plan(
f"of changes. {_NO_EDITS}"
)
parts = [_quote("last master plan", previous)]
- parts += [
- _quote(f"objections by {peer}", "\n".join(f"- {item}" for item in items))
- for peer, items in objections.items()
- ]
+ parts += quotes(
+ [
+ (f"objections by {peer}", "\n".join(f"- {item}" for item in items))
+ for peer, items in objections.items()
+ ]
+ )
else:
step = (
"Step 3 of 5: master plan. Write the one plan the team will follow. Take the "
@@ -121,8 +165,10 @@ def master_plan(
"decide and give the reason in one line. The plan must say how the result is "
f"verified. {_NO_EDITS}"
)
- parts = [_quote(f"plan by {peer}", text) for peer, text in drafts.items()]
- parts += [_quote(f"challenge by {peer}", text) for peer, text in critiques.items()]
+ parts = quotes(
+ [(f"plan by {peer}", text) for peer, text in drafts.items()]
+ + [(f"challenge by {peer}", text) for peer, text in critiques.items()]
+ )
return _frame(name, roster, cwd, step) + _material(parts) + _notes(notes)
@@ -236,7 +282,7 @@ def fix(
"where that is cheap. Verify again. Finish with a report that goes through the "
"findings one by one and says what you did."
)
- parts = []
+ found = []
for peer, items in findings.items():
lines = []
for item in items:
@@ -244,5 +290,6 @@ def fix(
if item.get("fix"):
line += f" (suggested fix: {item['fix']})"
lines.append(line)
- parts.append(_quote(f"findings by {peer}", "\n".join(lines)))
+ found.append((f"findings by {peer}", "\n".join(lines)))
+ parts = quotes(found)
return _frame(name, roster, cwd, step) + _material(parts) + _notes(notes)
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/MemberName.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/MemberName.tsx
new file mode 100644
index 0000000000..ac02417b9f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/MemberName.tsx
@@ -0,0 +1,15 @@
+import { cn } from "@/lib/utils";
+import { nameParts } from "./teamGraph";
+
+/**
+ * A member's name whose distinguishing tail never truncates away: in a narrow
+ * place "Anthropic Claude · Opus 5.5" reads "Anthropic Cl… · Opus 5.5", so two
+ * members on one seat still read apart.
+ */
+export function MemberName({ name, className }: { name: string; className?: string }) {
+ const { head, tail } = nameParts(name);
+ return <span className={cn("flex min-w-0 items-baseline", className)} title={name}>
+ <span className="min-w-0 truncate">{head}</span>
+ {tail && <span className="ml-[0.3em] max-w-[60%] shrink-0 truncate">{tail.trim()}</span>}
+ </span>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamCanvas.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamCanvas.tsx
index 42ff2224a0..8b8657a6e2 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamCanvas.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamCanvas.tsx
@@ -23,6 +23,7 @@ import { fill, useT } from "@/i18n";
import type { TeamMember, TeamThread } from "@/lib/teamThreadsApi";
import { cn } from "@/lib/utils";
import { clock, useMemberStatus } from "./memberLive";
+import { MemberName } from "./MemberName";
import { canvasLines, exchangeLabel, latestExchange, YOU, type EdgeTier, type Exchange, type GraphEdge, type GraphNode, type TeamGraph } from "./teamGraph";
/**
@@ -33,6 +34,10 @@ import { canvasLines, exchangeLabel, latestExchange, YOU, type EdgeTier, type Ex
* flows; a line of the step the team is in is drawn in ink with its label; an
* older line stays as a faint trace whose label shows on hover. The layout is
* fixed per team size and fitted to the frame, so the picture never jumps.
+ * When more lines would carry a label than stay readable (a swarm, where
+ * everyone sends everyone a plan), only the lines of the picked member, the
+ * picked line and the line under the pointer keep theirs, and the picked
+ * member's lines stand out from the rest.
* A click on a member opens its chat beside the canvas; a click on a line
* shows what the two exchanged.
*/
@@ -63,9 +68,14 @@ interface LineData extends Record<string, unknown> {
selected: boolean;
hovered: boolean;
faded: boolean;
+ /** Too many labelled lines: this one keeps its label only when it is in focus. */
+ quiet: boolean;
onOpen: (id: string) => void;
}
+/** More labelled lines than this and the canvas labels only what is in focus. */
+export const LABEL_BUDGET = 10;
+
const hidden = "!h-px !w-px !min-h-0 !min-w-0 !border-0 !bg-transparent !opacity-0";
const MemberNode = memo(function MemberNode({ data }: NodeProps<Node<MemberData>>) {
@@ -91,7 +101,7 @@ const MemberNode = memo(function MemberNode({ data }: NodeProps<Node<MemberData>
<span className="grid h-6 w-6 shrink-0 place-items-center rounded-md bg-secondary">
{agent ? <AgentMark agent={agent} label={member.name} variant="plain" size="sm" /> : <Users aria-hidden className="h-3.5 w-3.5 text-muted-foreground" />}
</span>
- <span className={cn("min-w-0 flex-1 truncate text-sm font-medium text-foreground", status.tone === "left" && "line-through")}>{member.name}</span>
+ <MemberName name={member.name} className={cn("flex-1 text-sm font-medium text-foreground", status.tone === "left" && "line-through")} />
{role && <span className="shrink-0 font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground" data-testid={`team-role-${member.role}`}>{role}</span>}
</span>
<span className={cn("flex min-w-0 items-center gap-1.5 text-xs",
@@ -169,11 +179,11 @@ const LineEdge = memo(function LineEdge({ id, data }: EdgeProps<Edge<LineData>>)
const t = useT();
const lang = t("trace_report.locale");
if (!data) return null;
- const { line, both, count, from, to, label, selected, hovered, faded, onOpen } = data;
+ const { line, both, count, from, to, label, selected, hovered, faded, quiet, onOpen } = data;
const { path, label: at } = linePath(from, to, both);
const tier = selected ? "selected" : data.tier;
const exchange = latestExchange(line);
- const showLabel = selected || hovered || data.tier !== "past";
+ const showLabel = selected || hovered || (!quiet && data.tier !== "past");
return <>
<BaseEdge id={id} path={path} interactionWidth={18}
className={cn("fill-none", STROKE[tier], faded && "opacity-40")}
@@ -253,23 +263,29 @@ function Canvas({ thread, graph, agentOf, selectedNode, selectedEdge, onOpenNode
} satisfies MemberData,
}), [graph.nodes, thread.state, selectedNode, onOpenNode, agentOf, over]);
- const edges = useMemo<Edge[]>(() => canvasLines(graph).flatMap(({ line, partner, tier, count }) => {
- const from = byId.get(line.from);
- const to = byId.get(line.to);
- if (!from || !to) return [];
- const exchange = latestExchange(line) as Exchange;
- const faded = [from, to].some((node) => node.member?.state === "left");
- const selected = selectedEdge === line.id || (partner !== null && selectedEdge === partner.id);
- return [{
- id: line.id, source: line.from, target: line.to, type: "line", selectable: false, focusable: false,
- // Live lines draw last, on top of the others.
- zIndex: selected ? 3 : tier === "live" ? 2 : tier === "current" ? 1 : 0,
- data: {
- line, both: partner !== null, tier, count, from, to, label: exchangeLabel(exchange, t, lang), selected,
- hovered: hovered === line.id, faded, onOpen: onOpenEdge,
- } satisfies LineData,
- }];
- }), [graph, byId, selectedEdge, hovered, onOpenEdge, t, lang]);
+ const edges = useMemo<Edge[]>(() => {
+ const lines = canvasLines(graph);
+ const crowded = lines.filter((item) => item.tier !== "past").length > LABEL_BUDGET;
+ return lines.flatMap(({ line, partner, tier, count }) => {
+ const from = byId.get(line.from);
+ const to = byId.get(line.to);
+ if (!from || !to) return [];
+ const exchange = latestExchange(line) as Exchange;
+ // In a crowded picture the picked member's lines are the ones to read.
+ const focused = selectedNode !== null && (line.from === selectedNode || line.to === selectedNode);
+ const faded = [from, to].some((node) => node.member?.state === "left") || (crowded && selectedNode !== null && !focused);
+ const selected = selectedEdge === line.id || (partner !== null && selectedEdge === partner.id);
+ return [{
+ id: line.id, source: line.from, target: line.to, type: "line", selectable: false, focusable: false,
+ // Live lines draw last, on top of the others.
+ zIndex: selected ? 3 : tier === "live" ? 2 : tier === "current" ? 1 : 0,
+ data: {
+ line, both: partner !== null, tier, count, from, to, label: exchangeLabel(exchange, t, lang), selected,
+ hovered: hovered === line.id, faded, quiet: crowded && !focused, onOpen: onOpenEdge,
+ } satisfies LineData,
+ }];
+ });
+ }, [graph, byId, selectedEdge, selectedNode, hovered, onOpenEdge, t, lang]);
// The whole team stays in the frame when the frame or the team changes size.
const count = graph.nodes.length;
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamSide.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamSide.tsx
index ea07e232c7..056f812335 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamSide.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamSide.tsx
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
-import { ArrowDown, ArrowLeftRight, ArrowRight, ChevronRight, Crosshair, ExternalLink, ListChecks, MessagesSquare, ShieldAlert, X } from "lucide-react";
+import { ArrowDown, ArrowLeftRight, ArrowRight, ChevronLeft, ChevronRight, Crosshair, ExternalLink, ListChecks, MessagesSquare, ShieldAlert, X } from "lucide-react";
import { AgentMark } from "@/components/agentic/AgentMark";
import type { TimelineItem, UserItem } from "@/components/agentchat/reduce";
import { plural } from "@/components/agentchat/traceEntries";
@@ -11,6 +11,7 @@ import { useMemberTimeline } from "./memberStreams";
import { useMemberStatus } from "./memberLive";
import { PlanPanel } from "./PlanPanel";
import { PROSE_COMPACT } from "./roomStyle";
+import { MemberName } from "./MemberName";
import { exchangeLabel, YOU, type Exchange, type TeamGraph } from "./teamGraph";
import { EntryBody, kindLabel, leadOf, TeamStory, verdictOf, type RoomNames } from "./TeamStory";
@@ -22,7 +23,8 @@ import { EntryBody, kindLabel, leadOf, TeamStory, verdictOf, type RoomNames } fr
* builder, the living plan are tabs of their own. A line picked on the canvas
* shows what went across it in place of the tab, until it is closed. Nothing
* here navigates away: a member's full thread opens only on request, and
- * that thread leads back to the team.
+ * that thread leads back to the team. A swarm's tabs scroll: arrows at the
+ * ends say there are more, and the picked tab always scrolls into view.
*/
export type RoomTab = { kind: "story" } | { kind: "plan" } | { kind: "member"; id: string };
@@ -63,10 +65,38 @@ export function TeamSide({ thread, graph, names, folder, tab, onTab, following,
refs.current.get(tabKey(tabs[next]))?.focus();
};
const member = tab.kind === "member" ? names.member(tab.id) : undefined;
+ const strip = useRef<HTMLDivElement | null>(null);
+ const [ends, setEnds] = useState({ before: false, after: false });
+ const many = thread.members.length > 4;
+
+ // Which ends of the strip hide tabs, kept current as it scrolls or resizes.
+ useEffect(() => {
+ const box = strip.current;
+ if (!box) return;
+ const measure = () => {
+ const before = box.scrollLeft > 1;
+ const after = box.scrollLeft + box.clientWidth < box.scrollWidth - 1;
+ setEnds((now) => (now.before === before && now.after === after ? now : { before, after }));
+ };
+ measure();
+ box.addEventListener("scroll", measure, { passive: true });
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
+ observer?.observe(box);
+ return () => { box.removeEventListener("scroll", measure); observer?.disconnect(); };
+ }, [tabs.length]);
+ // The picked tab is never hidden past an end of the strip.
+ useEffect(() => {
+ refs.current.get(current)?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
+ }, [current]);
+ const page = (direction: 1 | -1) => strip.current?.scrollBy({ left: direction * strip.current.clientWidth * 0.7, behavior: "smooth" });
+ const pager = "flex w-6 shrink-0 items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring";
return <section className="flex h-full min-h-0 flex-col" data-testid="team-side" aria-label={t("team_threads.room.chats")}>
<div className="flex h-10 shrink-0 items-stretch gap-0.5 border-b border-border pl-2 pr-1">
- <div role="tablist" aria-label={t("team_threads.room.chats")} onKeyDown={onKey}
+ {ends.before && <button type="button" onClick={() => page(-1)} aria-label={t("team_threads.room.tabs_prev")}
+ data-testid="team-tabs-prev" className={pager}><ChevronLeft aria-hidden className="h-3.5 w-3.5" /></button>}
+ <div ref={strip} role="tablist" aria-label={t("team_threads.room.chats")} onKeyDown={onKey}
+ onWheel={(event) => { if (strip.current && Math.abs(event.deltaY) > Math.abs(event.deltaX)) strip.current.scrollLeft += event.deltaY; }}
className="flex min-w-0 flex-1 items-stretch gap-0.5 overflow-x-auto [scrollbar-width:none]">
{tabs.map((item) => {
const key = tabKey(item);
@@ -82,10 +112,12 @@ export function TeamSide({ thread, graph, names, folder, tab, onTab, following,
)}>
{item.kind === "story" ? <><MessagesSquare aria-hidden className="h-3.5 w-3.5" />{t("team_threads.room.story")}</>
: item.kind === "plan" ? <><ListChecks aria-hidden className="h-3.5 w-3.5" />{t("team_threads.phase.planning")}</>
- : person ? <TabMember member={person} names={names} /> : null}
+ : person ? <TabMember member={person} names={names} compact={many} /> : null}
</button>;
})}
</div>
+ {ends.after && <button type="button" onClick={() => page(1)} aria-label={t("team_threads.room.tabs_next")}
+ data-testid="team-tabs-next" className={pager}><ChevronRight aria-hidden className="h-3.5 w-3.5" /></button>}
<button type="button" onClick={onFollow} aria-pressed={following} data-testid="team-follow"
title={t("team_threads.room.follow_hint")}
className={cn(
@@ -105,12 +137,12 @@ export function TeamSide({ thread, graph, names, folder, tab, onTab, following,
</section>;
}
-function TabMember({ member, names }: { member: TeamMember; names: RoomNames }) {
+function TabMember({ member, names, compact }: { member: TeamMember; names: RoomNames; compact: boolean }) {
const agent = names.agent(member);
const left = member.state === "left";
return <>
{agent ? <AgentMark agent={agent} label={member.name} variant="plain" size="sm" /> : null}
- <span className={cn("max-w-[9rem] truncate", left && "line-through opacity-60")}>{member.name}</span>
+ <MemberName name={member.name} className={cn(compact ? "max-w-[9rem]" : "max-w-[13rem]", left && "line-through opacity-60")} />
{!left && member.waiting ? <ShieldAlert aria-hidden className="h-3 w-3 text-warning" />
: !left && member.working ? <span aria-hidden className="team-pulse h-1.5 w-1.5 rounded-full bg-accent" /> : null}
</>;
@@ -180,7 +212,7 @@ function MemberChat({ member, thread, names, folder, onOpenFull }: {
</span>
<span className="min-w-0 flex-1">
<span className="flex items-baseline gap-2">
- <span className="truncate text-sm font-medium text-foreground">{member.name}</span>
+ <MemberName name={member.name} className="text-sm font-medium text-foreground" />
{member.role && <span className="shrink-0 font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground">{t(`team_threads.member_role.${member.role}`)}</span>}
{member.model && !member.name.includes(member.model) && <span className="truncate font-mono text-[11px] text-muted-foreground">{member.model}</span>}
</span>
@@ -230,7 +262,8 @@ function Who({ id, names }: { id: string; names: RoomNames }) {
const agent = member ? names.agent(member) : "";
return <span className="flex min-w-0 items-center gap-1.5">
{agent && member ? <AgentMark agent={agent} label={member.name} variant="plain" size="sm" /> : null}
- <span className="truncate font-medium text-foreground">{id === YOU ? t("team_threads.room.you") : names.name(id)}</span>
+ {id === YOU ? <span className="truncate font-medium text-foreground">{t("team_threads.room.you")}</span>
+ : <MemberName name={names.name(id)} className="font-medium text-foreground" />}
</span>;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.test.tsx
new file mode 100644
index 0000000000..be08df2396
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.test.tsx
@@ -0,0 +1,182 @@
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, expect, it, vi } from "vitest";
+import type { IdeProject } from "@/lib/agenticIdeApi";
+import { TeamThreadDraft } from "./TeamThreadDraft";
+
+vi.mock("@/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/i18n")>()),
+ useT: () => (key: string) => key,
+ fill: (template: string, vars: Record<string, unknown>) => `${template} ${JSON.stringify(vars)}`,
+}));
+
+// Plain stand-ins for the pickers, so a test can pick an option by its words.
+vi.mock("@/components/ui/select", () => ({
+ BrandedSelect: ({ options, onValueChange, testId, value, disabled }: {
+ options: { value: string; label: string }[]; onValueChange: (value: string) => void; testId: string; value: string; disabled?: boolean;
+ }) => <div data-testid={testId} data-value={value} data-disabled={disabled ? "true" : "false"}>
+ {options.map((option) => <button key={option.value} type="button" onClick={() => onValueChange(option.value)}>{option.label}</button>)}
+ </div>,
+}));
+vi.mock("@/components/ui/combobox", () => ({
+ Combobox: ({ groups, onChange, testId, value, fallbackLabel }: {
+ groups: { id: string; label?: string; options: { value: string; label: string; hint?: string }[] }[];
+ onChange: (value: string) => void; testId: string; value: string; fallbackLabel?: string;
+ }) => <div data-testid={testId} data-value={value} data-label={fallbackLabel}>
+ {groups.map((group) => <div key={group.id} data-testid={`${testId}-group-${group.id}`}>
+ {group.options.map((option) => <button key={option.value} type="button" onClick={() => onChange(option.value)}>
+ {option.label}{option.hint ? ` (${option.hint})` : ""}
+ </button>)}
+ </div>)}
+ </div>,
+}));
+
+const project: IdeProject = { id: "p1", name: "shop", path: "/work/shop" } as IdeProject;
+
+const SEATS = {
+ seats: [
+ {
+ provider: "claude-api", label: "Claude", family: "claude", runner: "claude-cli", agent: "claude", model: "", ready: true, local: false,
+ models: ["claude-opus-5-5", "claude-sonnet-5-5"],
+ model_options: [
+ { id: "claude-opus-5-5", label: "Claude Opus 5.5", efforts: [] },
+ { id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5", efforts: ["low", "medium"] },
+ ],
+ efforts: ["low", "medium", "high"],
+ },
+ {
+ provider: "openai-codex", label: "Codex", family: "openai", runner: "codex-cli", agent: "codex", model: "", ready: true, local: false,
+ models: [], model_options: [], efforts: [],
+ },
+ {
+ provider: "gemini", label: "Gemini", family: "gemini", runner: "api", agent: "", model: "", ready: true, local: false,
+ models: [], model_options: [], efforts: [],
+ },
+ {
+ provider: "grok-build", label: "Grok", family: "xai", runner: "grok-cli", agent: "grok-build", model: "", ready: false, local: false,
+ models: [], model_options: [], efforts: [],
+ },
+ ],
+ default: [{ provider: "claude-api", model: "" }, { provider: "openai-codex", model: "" }],
+ min_members: 2,
+ max_members: 8,
+ max_turns: { 2: 40, 3: 40, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80 },
+};
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+function mount() {
+ const calls: { url: string; method: string; body: unknown }[] = [];
+ vi.stubGlobal("fetch", vi.fn(async (url: string, init?: RequestInit) => {
+ calls.push({ url, method: init?.method ?? "GET", body: init?.body ? JSON.parse(init.body as string) : undefined });
+ if (url.endsWith("/seats")) return { ok: true, json: async () => SEATS };
+ return { ok: true, json: async () => ({ team_id: "t9", members: [], entries: [] }) };
+ }));
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(<QueryClientProvider client={client}><TeamThreadDraft project={project} /></QueryClientProvider>);
+ return calls;
+}
+
+const pick = (testId: string, words: string) => fireEvent.click(within(screen.getByTestId(testId)).getByText(words, { exact: false }));
+const posted = (calls: ReturnType<typeof mount>) => calls.find((call) => call.method === "POST")?.body;
+
+it("lets the person set each member's seat, model and effort", async () => {
+ const calls = mount();
+ await screen.findByTestId("team-draft-member-1");
+
+ // Every row says what it is set to; the model starts on the seat's default.
+ expect(screen.getByTestId("team-draft-select-0").dataset.value).toBe("claude-api");
+ expect(screen.getByTestId("team-draft-model-0").dataset.value).toBe("");
+ // A seat without a model list keeps its default and offers no effort.
+ expect(screen.getByTestId("team-draft-model-1").dataset.disabled).toBe("true");
+ expect(screen.queryByTestId("team-draft-effort-1")).toBeNull();
+ // Coding agents and key providers are listed apart; a seat that is not ready is not offered.
+ expect(screen.getByTestId("team-draft-select-0-group-agents").textContent).toBe("ClaudeCodex");
+ expect(screen.getByTestId("team-draft-select-0-group-providers").textContent).toBe("Gemini");
+
+ pick("team-draft-model-0", "Claude Opus 5.5");
+ pick("team-draft-effort-0", "high");
+ // The second member becomes a provider reached with a key.
+ pick("team-draft-select-1", "Gemini");
+ expect(screen.getByTestId("team-draft-select-1").dataset.value).toBe("gemini");
+
+ fireEvent.change(screen.getByTestId("team-draft-task"), { target: { value: "Add a retry" } });
+ fireEvent.click(screen.getByTestId("team-draft-start"));
+ await waitFor(() => expect(posted(calls)).toEqual({
+ task: "Add a retry",
+ cwd: "/work/shop",
+ seats: [
+ { provider: "claude-api", model: "claude-opus-5-5", effort: "high" },
+ { provider: "gemini", model: "" },
+ ],
+ }));
+});
+
+it("asks which seat joins, and the same seat may join twice on another model", async () => {
+ const calls = mount();
+ await screen.findByTestId("team-draft-member-1");
+
+ // Nothing joins until the person picks it.
+ expect(screen.queryByTestId("team-draft-member-2")).toBeNull();
+ expect(screen.getByTestId("team-draft-add").dataset.label).toBe("team_threads.draft.add");
+ // The picker says how often a seat already sits in the team.
+ expect(within(screen.getByTestId("team-draft-add")).getByText(/Claude \(team_threads\.draft\.in_team \{"count":1\}\)/)).toBeTruthy();
+ pick("team-draft-add", "Claude");
+ expect(screen.getByTestId("team-draft-select-2").dataset.value).toBe("claude-api");
+ pick("team-draft-model-2", "Claude Sonnet 5.5");
+ // The new model's own levels apply.
+ expect(within(screen.getByTestId("team-draft-effort-2")).queryByText("high")).toBeNull();
+ pick("team-draft-effort-2", "medium");
+ pick("team-draft-model-0", "Claude Opus 5.5");
+
+ fireEvent.change(screen.getByTestId("team-draft-task"), { target: { value: "Add a retry" } });
+ fireEvent.click(screen.getByTestId("team-draft-start"));
+ await waitFor(() => expect(posted(calls)).toEqual({
+ task: "Add a retry",
+ cwd: "/work/shop",
+ seats: [
+ { provider: "claude-api", model: "claude-opus-5-5" },
+ { provider: "openai-codex", model: "" },
+ { provider: "claude-api", model: "claude-sonnet-5-5", effort: "medium" },
+ ],
+ }));
+});
+
+it("drops an effort the newly picked model does not offer", async () => {
+ mount();
+ await screen.findByTestId("team-draft-member-1");
+
+ pick("team-draft-effort-0", "high");
+ expect(screen.getByTestId("team-draft-effort-0").dataset.value).toBe("high");
+ pick("team-draft-model-0", "Claude Sonnet 5.5");
+ expect(screen.getByTestId("team-draft-effort-0").dataset.value).toBe("");
+});
+
+it("grows into a swarm of up to eight members and says what that costs", async () => {
+ mount();
+ await screen.findByTestId("team-draft-member-1");
+ expect(screen.getByText(/team_threads\.draft\.bounds \{"turns":40\}/)).toBeTruthy();
+ expect(screen.queryByTestId("team-draft-swarm")).toBeNull();
+
+ for (let count = 3; count <= 8; count += 1) pick("team-draft-add", count % 2 ? "Codex" : "Gemini");
+ expect(screen.getByTestId("team-draft-member-7")).toBeTruthy();
+ expect(screen.getByTestId("team-draft-count").textContent).toContain('{"count":8,"max":8}');
+ // Full: no picker, and the bound the server uses for eight.
+ expect(screen.queryByTestId("team-draft-add")).toBeNull();
+ expect(screen.getByTestId("team-draft-full")).toBeTruthy();
+ expect(screen.getByTestId("team-draft-swarm")).toBeTruthy();
+ expect(screen.getByText(/team_threads\.draft\.bounds \{"turns":80\}/)).toBeTruthy();
+
+ // Planner and builder: the first two by position, six reviewers.
+ fireEvent.click(screen.getByTestId("team-draft-mode-planner_builder"));
+ expect([0, 1, 2, 7].map((index) => screen.getByTestId(`team-draft-role-${index}`).dataset.value))
+ .toEqual(["planner", "builder", "reviewer", "reviewer"]);
+
+ // A member leaves; the team can grow again.
+ fireEvent.click(screen.getByTestId("team-draft-remove-7"));
+ expect(screen.queryByTestId("team-draft-member-7")).toBeNull();
+ expect(screen.getByTestId("team-draft-add")).toBeTruthy();
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.tsx
index 9588a069e2..f81f6a6465 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadDraft.tsx
@@ -1,7 +1,8 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, Loader2, Plus, Send, X } from "lucide-react";
import { AgentMark } from "@/components/agentic/AgentMark";
+import { Combobox, type ComboboxGroup, type ComboboxOption } from "@/components/ui/combobox";
import { BrandedSelect } from "@/components/ui/select";
import { fill, useT } from "@/i18n";
import type { IdeProject } from "@/lib/agenticIdeApi";
@@ -13,6 +14,7 @@ import {
teamThreadKey,
useTeamSeats,
type TeamRole,
+ type TeamSeat,
type TeamSeatPick,
type TeamThreadMode,
} from "@/lib/teamThreadsApi";
@@ -27,13 +29,25 @@ const roleAt = (index: number): TeamRole => (index === 0 ? "planner" : index ===
const rolesValid = (team: TeamSeatPick[]) =>
team.filter((pick) => pick.role === "planner").length === 1 && team.filter((pick) => pick.role === "builder").length === 1;
+/** The effort levels a pick can take: its model's own, else the seat's. */
+function effortsOf(seat: TeamSeat | undefined, model: string): string[] {
+ const own = (seat?.model_options ?? []).find((option) => option.id === model)?.efforts ?? [];
+ return own.length ? own : seat?.efforts ?? [];
+}
+
+/** A team over this size gets the note that every step waits for more members. */
+const SWARM = 4;
+
/**
* A team thread before it starts: how the team works, who sits in it, and the task.
*
* The team opens on the seats that are ready, one per model family where
- * there are several; the person can swap, add and remove members. As peers
- * everyone plans and reviews; as planner and builder each member gets a role.
- * One prompt starts everything that follows.
+ * there are several. Each member is a row the person sets: which coding agent
+ * or provider, which model and how much effort. The same seat may sit in the
+ * team several times (two Claude Code members on different models, a swarm of
+ * reviewers). "Add member" asks which seat joins. As peers everyone plans and
+ * reviews; as planner and builder each member gets a role. One prompt starts
+ * everything that follows.
*/
export function TeamThreadDraft({ project }: { project: IdeProject }) {
const t = useT();
@@ -45,6 +59,8 @@ export function TeamThreadDraft({ project }: { project: IdeProject }) {
const [task, setTask] = useState("");
const [mode, setMode] = useState<TeamThreadMode>("peers");
const [starting, setStarting] = useState(false);
+ const rows = useRef<HTMLOListElement | null>(null);
+ const [added, setAdded] = useState<number | null>(null);
// The suggested team, until the person changes it.
useEffect(() => {
@@ -55,20 +71,40 @@ export function TeamThreadDraft({ project }: { project: IdeProject }) {
const byId = useMemo(() => new Map((seats.data?.seats ?? []).map((seat) => [seat.provider, seat])), [seats.data]);
const team = picks ?? [];
const min = seats.data?.min_members ?? 2;
- const max = seats.data?.max_members ?? 4;
+ const max = seats.data?.max_members ?? 8;
const families = new Set(team.map((pick) => byId.get(pick.provider)?.family ?? pick.provider));
const planned = mode === "planner_builder";
// Roles follow the position until the person picks one.
const cast = team.map((pick, index) => ({ ...pick, role: pick.role ?? roleAt(index) }));
const rolesOk = !planned || rolesValid(cast);
const canStart = !starting && task.trim().length > 0 && team.length >= min && team.length <= max && rolesOk;
+ const turns = seats.data?.max_turns?.[String(Math.max(min, Math.min(max, team.length)))] ?? 40;
+
+ // A member that was just added gets the focus on its seat, so it is clearly the person's to set.
+ useEffect(() => {
+ if (added === null) return;
+ rows.current?.querySelector<HTMLElement>(`[data-testid="team-draft-select-${added}"]`)?.focus();
+ setAdded(null);
+ }, [added]);
- const setPick = (index: number, provider: string) => setPicks(team.map((pick, at) => at === index
- ? { provider, model: byId.get(provider)?.model ?? "", ...(pick.role ? { role: pick.role } : {}) } : pick));
+ const update = (index: number, change: (pick: TeamSeatPick) => TeamSeatPick) =>
+ setPicks(team.map((pick, at) => (at === index ? change(pick) : pick)));
+ // Another seat starts on its own default model and effort; the role stays.
+ const setSeat = (index: number, provider: string) => update(index, (pick) => ({
+ provider, model: byId.get(provider)?.model ?? "", ...(pick.role ? { role: pick.role } : {}),
+ }));
+ // An effort the new model does not offer goes back to the seat's own.
+ const setModel = (index: number, model: string) => update(index, ({ effort, ...pick }) => {
+ const efforts = effortsOf(byId.get(pick.provider), model);
+ return effort && efforts.includes(effort) ? { ...pick, model, effort } : { ...pick, model };
+ });
+ const setEffort = (index: number, effort: string) => update(index, ({ effort: _old, ...pick }) => (effort ? { ...pick, effort } : pick));
const setRole = (index: number, role: TeamRole) => setPicks(cast.map((pick, at) => (at === index ? { ...pick, role } : pick)));
- const add = () => {
- const unused = ready.find((seat) => !team.some((pick) => pick.provider === seat.provider)) ?? ready[0];
- if (unused) setPicks([...team, { provider: unused.provider, model: unused.model }]);
+ const add = (provider: string) => {
+ const seat = byId.get(provider);
+ if (!seat || team.length >= max) return;
+ setPicks([...team, { provider, model: seat.model }]);
+ setAdded(team.length);
};
const remove = (index: number) => setPicks(team.filter((_, at) => at !== index));
@@ -90,9 +126,25 @@ export function TeamThreadDraft({ project }: { project: IdeProject }) {
}
};
+ // Coding agents first, then providers reached with a key; how often each sits in the team already.
+ const seatGroups = (withCount: boolean): ComboboxGroup[] => {
+ const option = (seat: TeamSeat): ComboboxOption => {
+ const count = team.filter((pick) => pick.provider === seat.provider).length;
+ return {
+ value: seat.provider, label: seat.label,
+ icon: seat.agent ? <AgentMark agent={seat.agent} label={seat.label} variant="plain" size="sm" /> : undefined,
+ hint: withCount && count ? fill(t("team_threads.draft.in_team"), { count }) : undefined,
+ };
+ };
+ return [
+ { id: "agents", label: t("team_threads.draft.group_agents"), options: ready.filter((seat) => seat.agent).map(option) },
+ { id: "providers", label: t("team_threads.draft.group_providers"), options: ready.filter((seat) => !seat.agent).map(option) },
+ ].filter((group) => group.options.length > 0);
+ };
+
const [before, after = ""] = t("team_threads.draft.title").split("{project}");
- return <div className="flex h-full min-h-0 flex-col items-center justify-center overflow-y-auto px-5 pb-10" data-testid="team-thread-draft">
- <div className="flex w-full max-w-3xl flex-col gap-5">
+ return <div className="flex h-full min-h-0 flex-col items-center overflow-y-auto px-5 py-10" data-testid="team-thread-draft">
+ <div className="my-auto flex w-full max-w-3xl flex-col gap-5">
{/* The form is a step away from what was open, never a place without a way back. */}
<button type="button" onClick={() => useIdeThreadsStore.getState().cancelTeamDraft()} data-testid="team-draft-cancel"
className="-mb-2 flex items-center gap-1.5 self-start rounded-md px-2 py-1 text-sm text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
@@ -120,37 +172,70 @@ export function TeamThreadDraft({ project }: { project: IdeProject }) {
<section aria-label={t("team_threads.members")} className="flex flex-col gap-2">
{seats.isLoading && <Loader2 role="status" aria-label={t("team_threads.loading")} className="mx-auto h-4 w-4 animate-spin text-muted-foreground" />}
{seats.data && ready.length === 0 && <p role="alert" className="text-center text-sm text-warning">{t("team_threads.draft.none_ready")}</p>}
- {ready.length > 0 && <ul className="flex flex-wrap items-center justify-center gap-2">
- {cast.map((pick, index) => {
- const seat = byId.get(pick.provider);
- return <li key={index} className="flex items-center gap-1 rounded-full border border-border bg-secondary/40 py-1 pl-2 pr-1"
- data-testid={`team-draft-member-${index}`}>
- {seat?.agent ? <AgentMark agent={seat.agent} label={seat.label} variant="plain" size="sm" /> : null}
- <BrandedSelect ariaLabel={fill(t("team_threads.draft.member_n"), { number: index + 1 })}
- testId={`team-draft-select-${index}`} value={pick.provider} onValueChange={(value) => setPick(index, value)}
- className="min-w-[11rem]"
- options={ready.map((option) => ({ value: option.provider, label: option.label }))} />
- {planned && <BrandedSelect ariaLabel={fill(t("team_threads.draft.role_of"), { number: index + 1 })}
- testId={`team-draft-role-${index}`} value={pick.role} onValueChange={(value) => setRole(index, value as TeamRole)}
- className="min-w-[7.5rem]"
- options={TEAM_THREAD_ROLES.map((role) => ({ value: role, label: t(`team_threads.member_role.${role}`) }))} />}
- <button type="button" disabled={team.length <= min} onClick={() => remove(index)}
- aria-label={fill(t("team_threads.draft.remove_named"), { target: seat?.label ?? pick.provider })}
- className="rounded-full p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-30">
- <X className="h-3.5 w-3.5" />
- </button>
- </li>;
- })}
- {team.length < max && <li>
- <button type="button" onClick={add} data-testid="team-draft-add"
- className="flex items-center gap-1 rounded-full border border-dashed border-border px-3 py-1.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <Plus aria-hidden className="h-3.5 w-3.5" />{t("team_threads.draft.add")}
- </button>
- </li>}
- </ul>}
+ {ready.length > 0 && <>
+ <ol ref={rows} className="flex flex-col divide-y divide-border rounded-xl border border-border bg-secondary/30" data-testid="team-draft-members">
+ {cast.map((pick, index) => {
+ const seat = byId.get(pick.provider);
+ const number = index + 1;
+ const models = seat?.model_options ?? [];
+ const efforts = effortsOf(seat, pick.model ?? "");
+ // One column per setting, so the rows line up whatever each seat offers.
+ return <li key={index} data-testid={`team-draft-member-${index}`} className={cn(
+ "flex flex-wrap items-center gap-1.5 px-2 py-1.5 sm:grid",
+ planned ? "sm:grid-cols-[1.25rem_minmax(0,1fr)_minmax(0,1fr)_9rem_8rem_auto]" : "sm:grid-cols-[1.25rem_minmax(0,1fr)_minmax(0,1fr)_9rem_auto]",
+ )}>
+ <span aria-hidden className="w-5 shrink-0 text-right font-mono text-xs tabular-nums text-muted-foreground">{number}</span>
+ <Combobox ariaLabel={fill(t("team_threads.draft.member_n"), { number })} testId={`team-draft-select-${index}`}
+ value={pick.provider} onChange={(value) => setSeat(index, value)} groups={seatGroups(false)}
+ fallbackLabel={seat?.label ?? pick.provider} searchPlaceholder={t("team_threads.draft.search")}
+ className="min-w-[10rem] flex-1 basis-40 sm:min-w-0" />
+ <BrandedSelect ariaLabel={fill(t("team_threads.draft.model_of"), { number })} testId={`team-draft-model-${index}`}
+ value={pick.model ?? ""} onValueChange={(value) => setModel(index, value)}
+ disabled={models.length === 0}
+ className="min-w-[10rem] flex-1 basis-40 sm:min-w-0"
+ options={[
+ { value: "", label: t("team_threads.draft.model_default") },
+ // A model picked before the list was known stays visible as it is.
+ ...(pick.model && !models.some((option) => option.id === pick.model) ? [{ value: pick.model, label: pick.model }] : []),
+ ...models.map((option) => ({ value: option.id, label: option.label })),
+ ]} />
+ {efforts.length > 0 ? <BrandedSelect ariaLabel={fill(t("team_threads.draft.effort_of"), { number })}
+ testId={`team-draft-effort-${index}`} value={pick.effort ?? ""} onValueChange={(value) => setEffort(index, value)}
+ className="min-w-[7.5rem] sm:min-w-0"
+ options={[{ value: "", label: t("team_threads.draft.effort_default") }, ...efforts.map((level) => ({ value: level, label: level }))]} />
+ : <span aria-hidden className="hidden sm:block" />}
+ {planned && <BrandedSelect ariaLabel={fill(t("team_threads.draft.role_of"), { number })}
+ testId={`team-draft-role-${index}`} value={pick.role} onValueChange={(value) => setRole(index, value as TeamRole)}
+ className="min-w-[7.5rem] sm:min-w-0"
+ options={TEAM_THREAD_ROLES.map((role) => ({ value: role, label: t(`team_threads.member_role.${role}`) }))} />}
+ <button type="button" disabled={team.length <= min} onClick={() => remove(index)}
+ aria-label={fill(t("team_threads.draft.remove_named"), { target: `${number} · ${seat?.label ?? pick.provider}` })}
+ data-testid={`team-draft-remove-${index}`}
+ className="rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-30">
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </li>;
+ })}
+ </ol>
+ <div className="flex flex-wrap items-center justify-between gap-2 px-1">
+ {team.length < max
+ ? <Combobox ariaLabel={t("team_threads.draft.add_pick")} testId="team-draft-add" value=""
+ onChange={add} groups={seatGroups(true)} fallbackLabel={t("team_threads.draft.add")}
+ searchPlaceholder={t("team_threads.draft.search")} triggerIcon={false}
+ triggerPrefix={<Plus aria-hidden className="h-3.5 w-3.5 shrink-0" />}
+ className="w-auto border border-dashed border-border bg-transparent py-1.5 text-xs text-muted-foreground hover:text-foreground" />
+ : <p className="text-xs text-muted-foreground" data-testid="team-draft-full">{fill(t("team_threads.draft.full"), { max })}</p>}
+ <span className="text-xs tabular-nums text-muted-foreground" data-testid="team-draft-count">
+ {fill(t("team_threads.draft.count"), { count: team.length, max })}
+ </span>
+ </div>
+ </>}
{team.length >= min && families.size === 1 && <p className="text-center text-xs text-muted-foreground" data-testid="team-draft-same-family">
{t("team_threads.notice.same_family")}
</p>}
+ {team.length > SWARM && <p className="text-center text-xs text-muted-foreground" data-testid="team-draft-swarm">
+ {t("team_threads.draft.swarm")}
+ </p>}
{!rolesOk && <p role="alert" className="text-center text-xs text-warning" data-testid="team-draft-roles-invalid">
{t("team_threads.draft.roles_invalid")}
</p>}
@@ -174,7 +259,7 @@ export function TeamThreadDraft({ project }: { project: IdeProject }) {
{starting ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <Send className="h-3.5 w-3.5" aria-hidden />}
</button>
</form>
- <p className="text-center text-xs text-muted-foreground">{t(planned ? "team_threads.draft.bounds_planned" : "team_threads.draft.bounds")}</p>
+ <p className="text-center text-xs text-muted-foreground">{fill(t(planned ? "team_threads.draft.bounds_planned" : "team_threads.draft.bounds"), { turns })}</p>
</div>
</div>;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.test.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.test.ts
index 25ace1a960..4847aed26a 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import type { TeamThread } from "@/lib/teamThreadsApi";
import { plainCommand } from "./memberLive";
-import { buildGraph, canvasLines, exchangeLabel, exchangesBetween, latestExchange, withShortNames, YOU, type TeamGraph } from "./teamGraph";
+import {
+ buildGraph, canvasLines, exchangeLabel, exchangesBetween, latestExchange, MEMBER_NODE, memberSpots, nameParts, withShortNames, YOU, YOU_NODE,
+ type GraphNode, type TeamGraph,
+} from "./teamGraph";
type Member = TeamThread["members"][number];
const member = (id: string, name: string, extra: Partial<Member> = {}): Member => ({
@@ -184,6 +187,57 @@ describe("the team graph", () => {
expect(withShortNames(base)).toBe(base);
});
+ it("seats a swarm of five to eight on a ring under the person, every box clear of the others", () => {
+ const clear = (one: GraphNode, other: GraphNode) =>
+ Math.abs(one.x - other.x) >= (one.width + other.width) / 2 + 40 || Math.abs(one.y - other.y) >= (one.height + other.height) / 2 + 40;
+ for (let count = 2; count <= 8; count += 1) {
+ const members = Array.from({ length: count }, (_, index) => member(`m${index + 1}`, `Seat ${index + 1}`));
+ const graph = buildGraph({ ...base, members, entries: [] });
+ // Everyone is on the canvas, the person on top.
+ expect(graph.nodes.map((node) => node.id)).toEqual([YOU, ...members.map((item) => item.member_id)]);
+ expect(graph.nodes[0]).toMatchObject({ x: 0, y: 0, ...YOU_NODE });
+ for (const [index, node] of graph.nodes.entries()) {
+ if (index > 0) expect(node.y).toBeGreaterThan(0);
+ for (const other of graph.nodes.slice(index + 1)) expect(clear(node, other), `${count}: ${node.id} / ${other.id}`).toBe(true);
+ }
+ // The same team always sits the same way.
+ expect(buildGraph({ ...base, members, entries: [] }).nodes).toEqual(graph.nodes);
+ }
+ // Member 1 sits on the person's left, the last on the right, mirrored.
+ const ring = memberSpots(7);
+ expect(ring[0][0]).toBeLessThan(0);
+ expect(ring[6]).toEqual([-ring[0][0], ring[0][1]]);
+ expect(ring[3][0]).toBe(0);
+ expect(MEMBER_NODE.width).toBeGreaterThan(0);
+ });
+
+ it("draws every pair of a swarm and every line of the person", () => {
+ const members = Array.from({ length: 8 }, (_, index) => member(`m${index + 1}`, `Seat ${index + 1}`));
+ const graph = buildGraph({
+ ...base, phase: "challenge", members,
+ entries: [entry(1, "user", "user", { text: "x" }, "draft"),
+ ...members.map((item, index) => entry(index + 2, "draft", item.member_id, { text: "plan" }, "draft"))],
+ });
+ expect(graph.edges.length).toBe(8 + 8 * 7);
+ // Both directions of each pair carried a plan: one two-way line per pair.
+ expect(canvasLines(graph).filter((line) => line.partner !== null).length).toBe(28);
+ });
+
+ it("keeps the part of a name that tells two members on one seat apart", () => {
+ expect(nameParts("Anthropic Claude · Opus 5.5")).toEqual({ head: "Anthropic Claude", tail: " · Opus 5.5" });
+ expect(nameParts("Anthropic Claude 2")).toEqual({ head: "Anthropic Claude", tail: " 2" });
+ expect(nameParts("OpenAI Codex")).toEqual({ head: "OpenAI Codex", tail: "" });
+ const named = withShortNames({ ...base, members: [
+ member("m1", "Anthropic Claude · Opus 5.5", { model: "claude-opus-5-5" }),
+ member("m2", "Anthropic Claude · Sonnet 5.5", { model: "claude-sonnet-5-5" }),
+ member("m3", "Antigravity · Claude Opus 5.5", { model: "claude-opus-5-5" }),
+ member("m4", "Anthropic Claude 1"), member("m5", "Anthropic Claude 2"),
+ ] });
+ expect(named.members.map((item) => item.name)).toEqual([
+ "Anthropic Claude · Opus 5.5", "Anthropic Claude · Sonnet 5.5", "Antigravity", "Anthropic Claude 1", "Anthropic Claude 2",
+ ]);
+ });
+
it("reads a shell call without its shell", () => {
expect(plainCommand(String.raw`"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "pytest -q"`)).toBe("pytest -q");
expect(plainCommand("bash -lc 'ls -la'")).toBe("ls -la");
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.ts
index b8fd2e58f1..65be433fe2 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.ts
@@ -17,7 +17,7 @@ import { buildBoard, type StepBand } from "./board";
* when its newest exchange belongs to the step the team is in (or ended in),
* or the step before it (what the current step works from), and `past`
* otherwise. The layout is fixed per team size, so nothing moves
- * while the team works.
+ * while the team works; a swarm of five to eight sits on a ring.
*/
export const YOU = "you";
@@ -78,6 +78,24 @@ const SPOTS: Record<number, [number, number][]> = {
4: [[-340, 190], [340, 190], [-170, 430], [170, 430]],
};
+/**
+ * Member centres for a swarm (five members and more): evenly spread on an
+ * oval whose top is the person, member 1 on the person's left and on round
+ * the ring, so every pair of members has a line of its own that crosses the
+ * middle rather than another member. The oval grows with the team; no two
+ * boxes come closer than about 80 px.
+ */
+export function memberSpots(count: number): [number, number][] {
+ if (count <= 4) return SPOTS[Math.max(1, count)];
+ const rx = 200 + 40 * count;
+ const ry = 100 + 35 * count;
+ return Array.from({ length: count }, (_, index): [number, number] => {
+ const angle = ((index + 1) * 2 * Math.PI) / (count + 1);
+ // `|| 0`: the bottom of the ring is x 0, not -0.
+ return [Math.round(-rx * Math.sin(angle)) || 0, Math.round(ry - ry * Math.cos(angle))];
+ });
+}
+
export const edgeId = (from: string, to: string) => `${from}->${to}`;
function tone(entry: TeamEntry): Exchange["tone"] {
@@ -275,10 +293,10 @@ export function buildGraph(thread: TeamThread): TeamGraph {
? "current" : "past";
}
- const spots = SPOTS[Math.min(4, Math.max(1, members.length))] ?? SPOTS[4];
+ const spots = memberSpots(members.length);
const nodes: GraphNode[] = [
{ id: YOU, kind: "you", x: 0, y: 0, ...YOU_NODE },
- ...members.slice(0, 4).map((member, index): GraphNode => ({
+ ...members.map((member, index): GraphNode => ({
id: member.member_id, kind: "member", member, x: spots[index][0], y: spots[index][1], ...MEMBER_NODE,
})),
];
@@ -376,16 +394,30 @@ export function exchangeLabel(exchange: Exchange, t: Translate, lang: string): s
/**
* Member names as the room shows them: without the model the server appended
- * ("Anthropic Claude · claude-sonnet-5-5" reads "Anthropic Claude"; the model
- * has its own line); two members that would then share a name keep theirs.
+ * ("Anthropic Claude · Sonnet 5.5" reads "Anthropic Claude"; the model has its
+ * own line); members that would then share a name (two Claude Code members on
+ * different models) keep theirs, so every member reads apart everywhere.
*/
export function withShortNames(thread: TeamThread): TeamThread {
const short = thread.members.map((member) => {
- const suffix = member.model ? ` · ${member.model}` : "";
- return suffix && member.name.endsWith(suffix) ? member.name.slice(0, -suffix.length).trim() : member.name;
+ const cut = member.model ? member.name.lastIndexOf(" · ") : -1;
+ return cut > 0 ? member.name.slice(0, cut).trim() : member.name;
});
const shared = (name: string) => short.filter((other) => other === name).length > 1;
const names = thread.members.map((member, index) => (short[index] && !shared(short[index]) ? short[index] : member.name));
if (names.every((name, index) => name === thread.members[index].name)) return thread;
return { ...thread, members: thread.members.map((member, index) => ({ ...member, name: names[index] })) };
}
+
+/**
+ * A member's name as a head that may be shortened and a tail that tells it
+ * apart and must stay readable: "Anthropic Claude" + " · Opus 5.5", or
+ * "Anthropic Claude" + " 2". A name without either is all head.
+ */
+export function nameParts(name: string): { head: string; tail: string } {
+ const cut = name.indexOf(" · ");
+ if (cut > 0) return { head: name.slice(0, cut), tail: name.slice(cut) };
+ const number = /\s\d+$/.exec(name);
+ if (number) return { head: name.slice(0, number.index), tail: number[0] };
+ return { head: name, tail: "" };
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index a654171969..759fe8c9a1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -9696,13 +9696,25 @@
"add": "Mitglied hinzufügen",
"placeholder": "Beschreibe die Aufgabe für das Team",
"start": "Team starten",
- "bounds": "Hält an und fragt dich nach 90 Minuten, 40 Zügen oder drei Runden ohne Einigung.",
+ "bounds": "Hält an und fragt dich nach 90 Minuten, {turns} Zügen oder drei Runden ohne Einigung.",
"mode": "Wie das Team arbeitet",
"body_planned": "Ein Mitglied schreibt einen Plan aus kleinen Schritten, ein anderes prüft ihn. Der Umsetzer baut einen Schritt nach dem anderen, und jeder Schritt wird an seinem Ziel geprüft, bevor der nächste beginnt. Ein blockierter Schritt geht zurück an den Planer. Du kannst jederzeit eingreifen.",
"role_of": "Rolle von Mitglied {number}",
"roles_invalid": "Wähle genau einen Planer und einen Umsetzer.",
- "bounds_planned": "Hält an und fragt dich nach 90 Minuten, 40 Zügen, drei Planrunden ohne Einigung oder drei Review-Runden an einem Schritt.",
- "cancel": "Zurück"
+ "bounds_planned": "Hält an und fragt dich nach 90 Minuten, {turns} Zügen, drei Planrunden ohne Einigung oder drei Review-Runden an einem Schritt.",
+ "cancel": "Zurück",
+ "model_of": "Modell von Mitglied {number}",
+ "effort_of": "Aufwand von Mitglied {number}",
+ "model_default": "Standardmodell",
+ "effort_default": "Standardaufwand",
+ "add_pick": "Welcher Coding-Agent oder Anbieter kommt ins Team?",
+ "search": "Suchen",
+ "in_team": "{count} im Team",
+ "count": "{count} von {max} Mitgliedern",
+ "group_agents": "Coding-Agents",
+ "group_providers": "Anbieter",
+ "full": "Das Team ist mit {max} Mitgliedern voll.",
+ "swarm": "Ein großes Team braucht mehr Züge: Jeder Schritt wartet, bis alle Mitglieder sich geäußert haben."
},
"meter_time": "{minutes} von {max_minutes} Min.",
"meter_turns": "{turns} von {max_turns} Zügen",
@@ -9767,7 +9779,9 @@
"exchange_count_one": "{count} Übergabe",
"exchange_count_other": "{count} Übergaben",
"members_count": "{count} Mitglieder",
- "to_all": "alle"
+ "to_all": "alle",
+ "tabs_prev": "Tabs zurückblättern",
+ "tabs_next": "Tabs weiterblättern"
},
"graph": {
"task": "Aufgabe",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 91a104d2e7..5b91438ba5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -9696,13 +9696,25 @@
"add": "Add member",
"placeholder": "Describe the task for the team",
"start": "Start the team",
- "bounds": "Stops and asks you after 90 minutes, 40 turns, or three rounds without agreement.",
+ "bounds": "Stops and asks you after 90 minutes, {turns} turns, or three rounds without agreement.",
"mode": "How the team works",
"body_planned": "One member writes a plan of small steps and another reviews it. The builder builds one step at a time, and each step is checked against its goal before the next one starts. A blocked step goes back to the planner. You can step in at any time.",
"role_of": "Role of member {number}",
"roles_invalid": "Pick exactly one planner and one builder.",
- "bounds_planned": "Stops and asks you after 90 minutes, 40 turns, three plan rounds without agreement or three review rounds on one step.",
- "cancel": "Back"
+ "bounds_planned": "Stops and asks you after 90 minutes, {turns} turns, three plan rounds without agreement or three review rounds on one step.",
+ "cancel": "Back",
+ "model_of": "Model of member {number}",
+ "effort_of": "Effort of member {number}",
+ "model_default": "Default model",
+ "effort_default": "Default effort",
+ "add_pick": "Which coding agent or provider joins the team?",
+ "search": "Search",
+ "in_team": "{count} in the team",
+ "count": "{count} of {max} members",
+ "group_agents": "Coding agents",
+ "group_providers": "Providers",
+ "full": "The team is full at {max} members.",
+ "swarm": "A big team takes more turns: each step waits until every member has had its say."
},
"meter_time": "{minutes} of {max_minutes} min",
"meter_turns": "{turns} of {max_turns} turns",
@@ -9767,7 +9779,9 @@
"exchange_count_one": "{count} exchange",
"exchange_count_other": "{count} exchanges",
"members_count": "{count} members",
- "to_all": "everyone"
+ "to_all": "everyone",
+ "tabs_prev": "Scroll the tabs back",
+ "tabs_next": "Scroll the tabs on"
},
"graph": {
"task": "Task",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 5070a88e3e..f41ef947e9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -9696,13 +9696,25 @@
"add": "Añadir miembro",
"placeholder": "Describe la tarea para el equipo",
"start": "Iniciar el equipo",
- "bounds": "Se detiene y te pregunta tras 90 minutos, 40 turnos o tres rondas sin acuerdo.",
+ "bounds": "Se detiene y te pregunta tras 90 minutos, {turns} turnos o tres rondas sin acuerdo.",
"mode": "Cómo trabaja el equipo",
"body_planned": "Un miembro escribe un plan de pasos pequeños y otro lo revisa. El constructor construye un paso cada vez, y cada paso se comprueba contra su objetivo antes de empezar el siguiente. Un paso bloqueado vuelve al planificador. Puedes intervenir en cualquier momento.",
"role_of": "Papel del miembro {number}",
"roles_invalid": "Elige exactamente un planificador y un constructor.",
- "bounds_planned": "Se detiene y te pregunta tras 90 minutos, 40 turnos, tres rondas de plan sin acuerdo o tres rondas de revisión en un paso.",
- "cancel": "Volver"
+ "bounds_planned": "Se detiene y te pregunta tras 90 minutos, {turns} turnos, tres rondas de plan sin acuerdo o tres rondas de revisión en un paso.",
+ "cancel": "Volver",
+ "model_of": "Modelo del miembro {number}",
+ "effort_of": "Esfuerzo del miembro {number}",
+ "model_default": "Modelo predeterminado",
+ "effort_default": "Esfuerzo predeterminado",
+ "add_pick": "¿Qué agente de código o proveedor se une al equipo?",
+ "search": "Buscar",
+ "in_team": "{count} en el equipo",
+ "count": "{count} de {max} miembros",
+ "group_agents": "Agentes de código",
+ "group_providers": "Proveedores",
+ "full": "El equipo está completo con {max} miembros.",
+ "swarm": "Un equipo grande necesita más turnos: cada paso espera a que todos los miembros hayan opinado."
},
"meter_time": "{minutes} de {max_minutes} min",
"meter_turns": "{turns} de {max_turns} turnos",
@@ -9767,7 +9779,9 @@
"exchange_count_one": "{count} intercambio",
"exchange_count_other": "{count} intercambios",
"members_count": "{count} miembros",
- "to_all": "todos"
+ "to_all": "todos",
+ "tabs_prev": "Desplazar las pestañas hacia atrás",
+ "tabs_next": "Desplazar las pestañas hacia delante"
},
"graph": {
"task": "Tarea",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
index 0a5a4e3004..efc060710f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -9696,13 +9696,25 @@
"add": "Adicionar membro",
"placeholder": "Descreva a tarefa para a equipa",
"start": "Iniciar a equipa",
- "bounds": "Para e pergunta-lhe após 90 minutos, 40 turnos ou três rondas sem acordo.",
+ "bounds": "Para e pergunta-lhe após 90 minutos, {turns} turnos ou três rondas sem acordo.",
"mode": "Como a equipa trabalha",
"body_planned": "Um membro escreve um plano de pequenos passos e outro revê-o. O construtor constrói um passo de cada vez, e cada passo é verificado face ao seu objetivo antes de começar o seguinte. Um passo bloqueado volta ao planeador. Pode intervir a qualquer momento.",
"role_of": "Papel do membro {number}",
"roles_invalid": "Escolha exatamente um planeador e um construtor.",
- "bounds_planned": "Para e pergunta-lhe após 90 minutos, 40 turnos, três rondas de plano sem acordo ou três rondas de revisão num passo.",
- "cancel": "Voltar"
+ "bounds_planned": "Para e pergunta-lhe após 90 minutos, {turns} turnos, três rondas de plano sem acordo ou três rondas de revisão num passo.",
+ "cancel": "Voltar",
+ "model_of": "Modelo do membro {number}",
+ "effort_of": "Esforço do membro {number}",
+ "model_default": "Modelo predefinido",
+ "effort_default": "Esforço predefinido",
+ "add_pick": "Que agente de código ou fornecedor entra na equipa?",
+ "search": "Pesquisar",
+ "in_team": "{count} na equipa",
+ "count": "{count} de {max} membros",
+ "group_agents": "Agentes de código",
+ "group_providers": "Fornecedores",
+ "full": "A equipa está completa com {max} membros.",
+ "swarm": "Uma equipa grande precisa de mais turnos: cada passo espera até todos os membros darem a sua opinião."
},
"meter_time": "{minutes} de {max_minutes} min",
"meter_turns": "{turns} de {max_turns} turnos",
@@ -9767,7 +9779,9 @@
"exchange_count_one": "{count} troca",
"exchange_count_other": "{count} trocas",
"members_count": "{count} membros",
- "to_all": "todos"
+ "to_all": "todos",
+ "tabs_prev": "Deslocar os separadores para trás",
+ "tabs_next": "Deslocar os separadores para a frente"
},
"graph": {
"task": "Tarefa",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index a220f5e24f..f91b82eb3d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -9696,13 +9696,25 @@
"add": "添加成员",
"placeholder": "描述交给团队的任务",
"start": "启动团队",
- "bounds": "在 90 分钟、40 轮或三轮未达成一致后停止并询问你。",
+ "bounds": "在 90 分钟、{turns} 轮或三轮未达成一致后停止并询问你。",
"mode": "团队工作方式",
"body_planned": "一位成员撰写由小步骤组成的方案,另一位评审它。实现者一次实现一个步骤,每个步骤都会按其目标检查通过后再开始下一个。受阻的步骤会退回给规划者。你可以随时介入。",
"role_of": "成员 {number} 的角色",
"roles_invalid": "请恰好选择一位规划者和一位实现者。",
- "bounds_planned": "在 90 分钟、40 轮、三轮方案未达成一致或同一步骤三轮评审后停止并询问你。",
- "cancel": "返回"
+ "bounds_planned": "在 90 分钟、{turns} 轮、三轮方案未达成一致或同一步骤三轮评审后停止并询问你。",
+ "cancel": "返回",
+ "model_of": "成员 {number} 的模型",
+ "effort_of": "成员 {number} 的推理强度",
+ "model_default": "默认模型",
+ "effort_default": "默认强度",
+ "add_pick": "哪个编程智能体或提供方加入团队?",
+ "search": "搜索",
+ "in_team": "团队中已有 {count} 个",
+ "count": "{count}/{max} 名成员",
+ "group_agents": "编程智能体",
+ "group_providers": "提供方",
+ "full": "团队已满,最多 {max} 名成员。",
+ "swarm": "大团队需要更多轮次:每一步都要等所有成员发表意见。"
},
"meter_time": "{minutes} / {max_minutes} 分钟",
"meter_turns": "{turns} / {max_turns} 轮",
@@ -9767,7 +9779,9 @@
"exchange_count_one": "{count} 次传递",
"exchange_count_other": "{count} 次传递",
"members_count": "{count} 名成员",
- "to_all": "所有人"
+ "to_all": "所有人",
+ "tabs_prev": "向前滚动标签",
+ "tabs_next": "向后滚动标签"
},
"graph": {
"task": "任务",
diff --git a/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts b/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts
index f43b3d2fd7..36d99ed187 100644
--- a/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts
@@ -47,10 +47,21 @@ export interface TeamSeat {
agent: string;
model: string;
models: string[];
+ /** The models a member on this seat can run, with the effort levels each offers. */
+ model_options: TeamModelOption[];
+ /** The seat's effort levels; empty where it has none to pick. */
+ efforts: string[];
ready: boolean;
local: boolean;
}
+export interface TeamModelOption {
+ id: string;
+ label: string;
+ /** Empty: the seat's own levels apply. */
+ efforts: string[];
+}
+
export interface TeamSeatPick {
provider: string;
model?: string;
@@ -64,6 +75,8 @@ export interface TeamSeats {
default: TeamSeatPick[];
min_members: number;
max_members: number;
+ /** The default turn bound by team size ("2" .. "8"). */
+ max_turns: Record<string, number>;
}
export interface TeamMember {
diff --git a/jarvis/ui/web/team_thread_routes.py b/jarvis/ui/web/team_thread_routes.py
index b37279e96c..cc9860d6a3 100644
--- a/jarvis/ui/web/team_thread_routes.py
+++ b/jarvis/ui/web/team_thread_routes.py
@@ -27,7 +27,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel, Field, field_validator
-from jarvis.agent_chat.team import SeatPick, TeamError, TeamThreads, TeamThreadStore
+from jarvis.agent_chat.team import Limits, SeatPick, TeamError, TeamThreads, TeamThreadStore
from jarvis.agent_chat.team.engine import MAX_MEMBERS, MIN_MEMBERS
from jarvis.agent_chat.team.store import MODES, ROLES
@@ -199,6 +199,7 @@ def _seat_rows(live: dict[str, list[dict[str, Any]]]) -> list[dict[str, Any]]:
ready = bool(row.get("keyless")) or any(get_secret(key) for key in keys)
else:
ready = bool(installed)
+ options = _model_options(row)
seats.append(
{
"provider": row["id"],
@@ -208,7 +209,9 @@ def _seat_rows(live: dict[str, list[dict[str, Any]]]) -> list[dict[str, Any]]:
"agent": row.get("agent", ""),
"model": row.get("default_model", ""),
"fallback": _seat_fallback(row, live),
- "models": [m["id"] for m in row.get("curated_models") or []],
+ "models": [option["id"] for option in options],
+ "model_options": options,
+ "efforts": _efforts(row.get("effort_levels")),
"ready": ready,
"local": bool(row.get("keyless")),
}
@@ -216,6 +219,49 @@ def _seat_rows(live: dict[str, list[dict[str, Any]]]) -> list[dict[str, Any]]:
return seats
+def _efforts(levels: Any) -> list[str]:
+ """Effort levels a member can be given; "" (the seat's own) is always there too."""
+ return [str(level) for level in levels or [] if str(level or "").strip()]
+
+
+def _model_options(row: dict[str, Any]) -> list[dict[str, Any]]:
+ """The models a member on this seat can run, as every model picker lists them.
+
+ Models hidden on the API Keys page stay out, as in the composer.
+ """
+ hidden = set(row.get("hidden_models") or [])
+ options = []
+ for model in row.get("curated_models") or []:
+ model_id = str(model.get("id") or "")
+ if not model_id or model_id in hidden:
+ continue
+ options.append(
+ {
+ "id": model_id,
+ "label": str(model.get("label") or model_id),
+ "efforts": _efforts(model.get("efforts")),
+ }
+ )
+ return options
+
+
+def short_model_label(seat_label: str, model_label: str) -> str:
+ """The model's name without the words the seat's name already says.
+
+ "Anthropic Claude" with "Claude Opus 5.5" reads "Opus 5.5". A model name
+ that would then start with a bare number ("Grok 4.7" on "Grok Build")
+ keeps its words.
+ """
+ seat_words = {word.lower() for word in seat_label.split()}
+ words = model_label.split()
+ rest = list(words)
+ while rest and rest[0].lower() in seat_words:
+ rest.pop(0)
+ if not rest or rest == words or rest[0][:1].isdigit():
+ return model_label.strip()
+ return " ".join(rest)
+
+
def _seat_fallback(row: dict[str, Any], live: dict[str, list[dict[str, Any]]]) -> str:
"""A model to fall back on when the seat's own default is refused.
@@ -227,6 +273,14 @@ def _seat_fallback(row: dict[str, Any], live: dict[str, list[dict[str, Any]]]) -
return str(listed[0].get("id") or "") if listed else ""
+def _efforts_for(row: dict[str, Any], model: str) -> list[str]:
+ """The effort levels the picked model (or else the seat) offers; [] = any."""
+ for option in row.get("model_options") or []:
+ if option["id"] == model and option.get("efforts"):
+ return list(option["efforts"])
+ return list(row.get("efforts") or [])
+
+
def default_team(seats: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Up to three ready seats from different families; a coding CLI before an API row.
@@ -275,6 +329,11 @@ async def get_seats() -> dict[str, Any]:
"default": [{"provider": s["provider"], "model": s["model"]} for s in default_team(seats)],
"min_members": MIN_MEMBERS,
"max_members": MAX_MEMBERS,
+ # The default turn bound by team size, so the start form can say it.
+ "max_turns": {
+ str(size): Limits.for_team(size).max_turns
+ for size in range(MIN_MEMBERS, MAX_MEMBERS + 1)
+ },
}
@@ -323,14 +382,27 @@ async def start_team_thread(body: StartBody, request: Request) -> dict[str, Any]
raise HTTPException(
status_code=409, detail=f"{row['label']} is not connected on this machine."
)
+ model = (seat.get("model") or "").strip()
+ effort = (seat.get("effort") or "").strip()
+ offered = _efforts_for(row, model)
+ if effort and offered and effort not in offered:
+ raise HTTPException(
+ status_code=422,
+ detail=f"{row['label']} runs with effort {', '.join(offered)}, not {effort}.",
+ )
+ labels = {option["id"]: option["label"] for option in row.get("model_options") or []}
picks.append(
SeatPick(
provider=row["provider"],
- model=seat.get("model") or row["model"],
+ model=model or row["model"],
# Only where the person left the model to the seat.
- fallback_model="" if seat.get("model") else row.get("fallback", ""),
- effort=seat.get("effort") or "",
- name=row["label"] if not seat.get("model") else f"{row['label']} · {seat['model']}",
+ fallback_model="" if model else row.get("fallback", ""),
+ effort=effort,
+ name=row["label"],
+ # Two members on one seat read apart by the model the person picked.
+ model_label=short_model_label(row["label"], labels.get(model, model))
+ if model
+ else "",
family=row["family"],
)
)
diff --git a/tests/unit/agent_chat/test_team_thread_routes.py b/tests/unit/agent_chat/test_team_thread_routes.py
index 808c03db2a..dc32890ea2 100644
--- a/tests/unit/agent_chat/test_team_thread_routes.py
+++ b/tests/unit/agent_chat/test_team_thread_routes.py
@@ -113,7 +113,7 @@ def test_seats_lists_what_can_sit_in_a_team(client: TestClient) -> None:
"claude-api", "openai-codex", "antigravity",
]
assert body["min_members"] == 2
- assert body["max_members"] == 4
+ assert body["max_members"] == 8
assert len(body["seats"]) == len(ROWS)
diff --git a/tests/unit/agent_chat/test_team_thread_swarm.py b/tests/unit/agent_chat/test_team_thread_swarm.py
new file mode 100644
index 0000000000..e373a07580
--- /dev/null
+++ b/tests/unit/agent_chat/test_team_thread_swarm.py
@@ -0,0 +1,364 @@
+"""Teams the person sets member by member: one seat twice, and swarms of up to eight."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat.team import SeatPick, TeamError, TeamThreads, TeamThreadStore, prompts
+from jarvis.agent_chat.team.engine import MAX_MEMBERS
+from jarvis.ui.web import team_thread_routes
+from jarvis.ui.web.team_thread_routes import router, short_model_label
+from tests.fakes.fake_team_turns import FakeTurns, FakeWorkspace, changes
+
+CLAUDE_MODELS = [
+ {"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "efforts": []},
+ {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "efforts": []},
+]
+
+SWARM = [
+ SeatPick(f"seat{n}", name=f"Seat {n}", family=f"family{n}") for n in range(1, MAX_MEMBERS + 1)
+]
+
+
+def _engine(turns: FakeTurns) -> TeamThreads:
+ return TeamThreads(TeamThreadStore(":memory:"), turns, workspace=FakeWorkspace())
+
+
+async def _run(engine: TeamThreads, tmp_path: Path, **kwargs) -> dict:
+ snap = await engine.start(task="Add a retry to the uploader", cwd=str(tmp_path), **kwargs)
+ await engine.settled(snap["team_id"])
+ return engine.snapshot(snap["team_id"])
+
+
+def _authors(snap: dict, kind: str) -> list[str]:
+ return [e["author"] for e in snap["entries"] if e["kind"] == kind]
+
+
+# ------------------------------------------------------------------ engine
+
+
+async def test_one_seat_can_sit_in_the_team_twice_as_separate_members(tmp_path: Path) -> None:
+ turns = FakeTurns()
+ seats = [
+ SeatPick(
+ "claude", name="Anthropic Claude", family="claude", model="opus", model_label="Opus 5.5"
+ ),
+ SeatPick(
+ "claude",
+ name="Anthropic Claude",
+ family="claude",
+ model="sonnet",
+ model_label="Sonnet 5.5",
+ ),
+ SeatPick("codex", name="OpenAI Codex", family="openai"),
+ ]
+ snap = await _run(_engine(turns), tmp_path, seats=seats)
+
+ assert snap["state"] == "done"
+ assert [m["name"] for m in snap["members"]] == [
+ "Anthropic Claude · Opus 5.5",
+ "Anthropic Claude · Sonnet 5.5",
+ "OpenAI Codex",
+ ]
+ # Each member is a session of its own, on its own model.
+ assert len({m["session_id"] for m in snap["members"]}) == 3
+ assert [m["model"] for m in snap["members"]] == ["opus", "sonnet", ""]
+ assert sorted(_authors(snap, "draft")) == ["m1", "m2", "m3"]
+ # Each member reads the other's plan under the other's name.
+ challenge = next(
+ p for p in turns.prompts("claude", "critique") if "You are Anthropic Claude · Opus 5.5" in p
+ )
+ assert "<plan by Anthropic Claude · Sonnet 5.5>" in challenge
+ assert "<plan by Anthropic Claude · Opus 5.5>" not in challenge
+
+
+async def test_members_on_one_seat_and_one_model_are_numbered(tmp_path: Path) -> None:
+ seats = [
+ SeatPick("claude", name="Anthropic Claude", family="claude"),
+ SeatPick("claude", name="Anthropic Claude", family="claude"),
+ SeatPick(
+ "claude", name="Anthropic Claude", family="claude", model="opus", model_label="Opus 5.5"
+ ),
+ SeatPick(
+ "claude", name="Anthropic Claude", family="claude", model="opus", model_label="Opus 5.5"
+ ),
+ ]
+ snap = await _run(_engine(FakeTurns()), tmp_path, seats=seats)
+
+ assert [m["name"] for m in snap["members"]] == [
+ "Anthropic Claude 1",
+ "Anthropic Claude 2",
+ "Anthropic Claude · Opus 5.5 1",
+ "Anthropic Claude · Opus 5.5 2",
+ ]
+ assert "same_family" in [e["payload"]["code"] for e in snap["entries"] if e["kind"] == "notice"]
+
+
+async def test_a_swarm_of_eight_peers_plans_builds_and_reviews(tmp_path: Path) -> None:
+ turns = FakeTurns()
+ snap = await _run(_engine(turns), tmp_path, seats=SWARM)
+
+ assert snap["state"] == "done"
+ assert len(snap["members"]) == 8
+ assert len(_authors(snap, "draft")) == 8
+ assert len(_authors(snap, "critique")) == 8
+ assert len(_authors(snap, "vote")) == 7
+ assert len(_authors(snap, "review")) == 7
+ # A bigger team gets a bigger default turn bound.
+ assert snap["limits"]["max_turns"] == 80
+ assert snap["usage"]["turns"] == 8 + 8 + 1 + 7 + 1 + 7
+
+
+async def test_more_members_than_the_cap_are_refused(tmp_path: Path) -> None:
+ extra = [*SWARM, SeatPick("seat9", name="Seat 9", family="family9")]
+ with pytest.raises(TeamError):
+ await _engine(FakeTurns()).start(task="x", cwd=str(tmp_path), seats=extra)
+
+
+async def test_a_swarm_reviews_every_step_and_converges(tmp_path: Path) -> None:
+ def script(provider: str, step: str, nth: int):
+ # One of six reviewers holds the first step back once.
+ if provider == "seat5" and step == "step_review" and nth == 0:
+ return changes("The retry never stops.")
+ return None
+
+ turns = FakeTurns(script)
+ snap = await _run(_engine(turns), tmp_path, seats=SWARM, mode="planner_builder")
+
+ assert snap["state"] == "done"
+ roles = [m["role"] for m in snap["members"]]
+ assert roles == ["planner", "builder"] + ["reviewer"] * 6
+ reviews = [e for e in snap["entries"] if e["kind"] == "step_review"]
+ builds = [e for e in snap["entries"] if e["kind"] == "step_build"]
+ # Step 1 was built twice; each round of it was read by all six reviewers.
+ assert [b["payload"]["number"] for b in builds] == [1, 1, 2]
+ first = [r for r in reviews if r["payload"]["number"] == 1]
+ assert len(first) == 12
+ assert all(r["payload"]["approve"] for r in first[6:])
+ assert len([r for r in reviews if r["payload"]["number"] == 2]) == 6
+ # Every reviewer reads the plan.
+ assert _authors(snap, "plan_review") == ["m3", "m4", "m5", "m6", "m7", "m8"]
+ assert snap["plan"]["steps"][0]["rounds"] == 2
+
+
+# ------------------------------------------------------------------ prompts
+
+
+def test_a_few_contributions_are_passed_on_whole() -> None:
+ texts = [("plan by A", "a" * 9_000), ("plan by B", "b" * 11_000)]
+ assert prompts.share([len(text) for _, text in texts]) == prompts.MAX_QUOTE
+ assert [len(block) for block in prompts.quotes(texts)] == [
+ len(prompts.quote(label, text)) for label, text in texts
+ ]
+
+
+def test_many_contributions_share_one_budget_and_short_ones_stay_whole() -> None:
+ lengths = [500, 800] + [12_000] * 6
+ limit = prompts.share(lengths)
+ assert limit < prompts.MAX_QUOTE
+ assert 500 + 800 + 6 * limit <= prompts.MAX_MATERIAL
+ # Never below the floor, however many there are.
+ assert prompts.share([12_000] * 40) == prompts.MIN_QUOTE
+
+
+def test_a_swarm_challenge_stays_within_the_material_budget() -> None:
+ drafts = {f"Seat {n}": f"plan {n} " + "x" * 20_000 for n in range(2, 9)}
+ prompt = prompts.challenge(
+ name="Seat 1",
+ roster=[f"Seat {n}" for n in range(1, 9)],
+ cwd="/repo",
+ drafts=drafts,
+ notes=[],
+ )
+ assert len(prompt) < prompts.MAX_MATERIAL + 3_000
+ assert prompt.count("[shortened]") == 7
+ for n in range(2, 9):
+ assert f"<plan by Seat {n}>\nplan {n} " in prompt
+
+
+def test_a_swarm_master_plan_shares_the_budget_between_plans_and_challenges() -> None:
+ roster = [f"Seat {n}" for n in range(1, 9)]
+ long = "y" * 15_000
+ prompt = prompts.master_plan(
+ name="Seat 1",
+ roster=roster,
+ cwd="/repo",
+ drafts={name: long for name in roster},
+ critiques={name: long for name in roster},
+ previous="",
+ objections={},
+ notes=[],
+ )
+ assert len(prompt) < prompts.MAX_MATERIAL + 4_000
+ assert prompt.count("<plan by ") == 8
+ assert prompt.count("<challenge by ") == 8
+
+
+# ------------------------------------------------------------------ routes
+
+
+def _row(provider: str, label: str, family: str, **extra) -> dict:
+ return {
+ "provider": provider,
+ "label": label,
+ "family": family,
+ "runner": "api",
+ "agent": "",
+ "model": "",
+ "models": [],
+ "model_options": [],
+ "efforts": [],
+ "ready": True,
+ "local": False,
+ "fallback": "",
+ **extra,
+ }
+
+
+ROWS = [
+ _row(
+ "claude-api",
+ "Anthropic Claude",
+ "claude",
+ agent="claude",
+ runner="claude-cli",
+ models=[m["id"] for m in CLAUDE_MODELS],
+ model_options=CLAUDE_MODELS,
+ efforts=["low", "medium", "high"],
+ fallback="claude-sonnet-5-5",
+ ),
+ _row("openai-codex", "OpenAI Codex", "openai", agent="codex", runner="codex-cli"),
+ *[_row(f"api{n}", f"Api {n}", f"family{n}") for n in range(1, 8)],
+]
+
+
+def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ async def seats() -> list[dict]:
+ return [dict(row) for row in ROWS]
+
+ monkeypatch.setattr(team_thread_routes, "_seats", seats)
+ app = FastAPI()
+ app.include_router(router)
+ app.state.turns = FakeTurns()
+ app.state.team_threads = TeamThreads(
+ TeamThreadStore(":memory:"), app.state.turns, workspace=FakeWorkspace()
+ )
+ with TestClient(app) as test_client:
+ yield test_client
+
+
+def test_seats_offer_up_to_eight_members_and_the_turn_bound_per_size(client: TestClient) -> None:
+ body = client.get("/api/team-threads/seats").json()
+
+ assert body["max_members"] == 8
+ assert body["max_turns"] == {
+ "2": 40,
+ "3": 40,
+ "4": 40,
+ "5": 50,
+ "6": 60,
+ "7": 70,
+ "8": 80,
+ }
+
+
+def test_two_claude_members_on_different_models_start_over_the_api(
+ client: TestClient, tmp_path: Path
+) -> None:
+ started = client.post(
+ "/api/team-threads",
+ json={
+ "task": "Fix the flaky test",
+ "cwd": str(tmp_path),
+ "seats": [
+ {"provider": "claude-api", "model": "claude-opus-5-5", "effort": "high"},
+ {"provider": "claude-api", "model": "claude-sonnet-5-5"},
+ {"provider": "openai-codex"},
+ ],
+ },
+ )
+ assert started.status_code == 201, started.text
+ members = started.json()["members"]
+ assert [m["name"] for m in members] == [
+ "Anthropic Claude · Opus 5.5",
+ "Anthropic Claude · Sonnet 5.5",
+ "OpenAI Codex",
+ ]
+ assert [m["model"] for m in members] == ["claude-opus-5-5", "claude-sonnet-5-5", ""]
+ assert [m["effort"] for m in members] == ["high", "", ""]
+ assert len({m["session_id"] for m in members}) == 3
+
+
+def test_two_members_on_the_seats_default_are_numbered_over_the_api(
+ client: TestClient, tmp_path: Path
+) -> None:
+ started = client.post(
+ "/api/team-threads",
+ json={
+ "task": "Fix the flaky test",
+ "cwd": str(tmp_path),
+ "seats": [{"provider": "claude-api"}, {"provider": "claude-api"}],
+ },
+ ).json()
+ assert [m["name"] for m in started["members"]] == ["Anthropic Claude 1", "Anthropic Claude 2"]
+
+
+def test_a_team_of_eight_starts_and_a_ninth_member_is_refused(
+ client: TestClient, tmp_path: Path
+) -> None:
+ eight = [{"provider": "claude-api"}, {"provider": "openai-codex"}] + [
+ {"provider": f"api{n}"} for n in range(1, 7)
+ ]
+ started = client.post(
+ "/api/team-threads",
+ json={"task": "Swarm", "cwd": str(tmp_path), "seats": eight, "mode": "planner_builder"},
+ )
+ assert started.status_code == 201, started.text
+ assert len(started.json()["members"]) == 8
+
+ nine = client.post(
+ "/api/team-threads",
+ json={"task": "Swarm", "cwd": str(tmp_path), "seats": [*eight, {"provider": "api7"}]},
+ )
+ assert nine.status_code == 422
+
+
+def test_an_effort_the_seat_does_not_offer_is_refused(client: TestClient, tmp_path: Path) -> None:
+ refused = client.post(
+ "/api/team-threads",
+ json={
+ "task": "x",
+ "cwd": str(tmp_path),
+ "seats": [{"provider": "claude-api", "effort": "ludicrous"}, {"provider": "api1"}],
+ },
+ )
+ assert refused.status_code == 422
+ assert "ludicrous" in refused.json()["detail"]
+
+
+def test_a_seat_lists_its_models_without_the_hidden_ones() -> None:
+ row = {
+ "curated_models": [
+ {"id": "a", "label": "Model A", "efforts": ["low", "", "high"]},
+ {"id": "b", "label": "Model B"},
+ {"id": "", "label": "nameless"},
+ ],
+ "hidden_models": ["b"],
+ }
+ assert team_thread_routes._model_options(row) == [
+ {"id": "a", "label": "Model A", "efforts": ["low", "high"]},
+ ]
+
+
+def test_a_model_name_drops_what_the_seat_name_already_says() -> None:
+ assert short_model_label("Anthropic Claude", "Claude Opus 5.5") == "Opus 5.5"
+ assert short_model_label("OpenAI Codex", "GPT-6-Luna") == "GPT-6-Luna"
+ assert short_model_label("Antigravity", "Claude Opus 5.5") == "Claude Opus 5.5"
+ # A bare number would say nothing on its own.
+ assert short_model_label("Grok Build", "Grok 4.7 Fast") == "Grok 4.7 Fast"
+ assert short_model_label("Anthropic Claude", "Claude") == "Claude"