Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(team-threads): a team room with a live collaboration canvas and the chats beside it (#670)
Ruben Lütke8c9f1ff529ed
diff --git a/docs/agentic-ide-team-threads.md b/docs/agentic-ide-team-threads.mdindex 25cd86b4bd..2fdc41a981 100644--- a/docs/agentic-ide-team-threads.md+++ b/docs/agentic-ide-team-threads.md@@ -55,34 +55,50 @@ before the build must not change files; the coordinator compares snapshotsaround them and reports a change in the thread with the files' names, so acache that a check left behind can be told from an edit.-## The shared thread--The thread is a board on one page: a lane per member, a band per step.--- **Lanes.** Each member has a column. Its head stays in view while the board- scrolls and says what the member does right now: working, waiting for the- person, waiting for its turn, or gone (with the reason).-- **Bands.** Each step is a row across the lanes: the own plans side by side,- a master plan beside the votes on it, a build beside its reviews. A further- master-plan or review round is a band of its own. What belongs to nobody's- lane (the person's messages, notices, the outcome) spans the board between- the bands.-- **Live.** A member whose turn runs shows its newest steps as they happen:- the files it reads, the commands it runs, the edits it makes, its own words,- with the time and tokens spent so far. The board listens to a member's- thread only while that member works.-- **Cards.** A filed contribution is a card with its first lines, its verdict- and, for a review, its blocking finding. A click opens the whole text under- its band, starting at its top; nothing is navigated to.-- **Caught by the team** lists every objection and finding with who raised it,- where, and whether it is resolved.-- The header shows the five steps as one line, and time and turns as bars- against their limits, with the cost where a seat reports one. That amount is- the list price the coding agents report; a subscription seat is not billed- per turn.-- Each member is still an ordinary thread underneath. A click on a lane's head- opens it with every tool call and diff; the thread list shows the team once- and keeps the members out of it.+## The team room++A team thread opens as a room: the team on a canvas, their chats beside it,+the task, state, steps and bounds above. Below about 980 pixels of width the+canvas sits above the chats.++- **Canvas.** Each member is a node with its model's mark, its name, its role+ (planner and builder) and its state in one line: what it is doing right now+ (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.+- **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+ to its reviewers, findings back to the builder, a blocked step to the+ planner. A line's label says what went across last ("Master plan, round 2",+ "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.+- **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.+- **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.+- **Story.** The shared story is a tab: every contribution as one line (who,+ what, the verdict, to whom, a two-line gist) under a heading per step, the+ person's messages, notices and the outcome where they happened, and at the+ end what the team caught in each other's work, with who raised it, where,+ and whether it is resolved. A click unfolds a contribution in place.+- **Header.** The steps as one line, time and turns against their limits, the+ cost where a seat reports one (the list price the coding agents report; a+ subscription seat is not billed per turn), and for planner and builder the+ plan's progress, which opens the plan.+- **Ways back.** Nothing in the room navigates away except **Full thread** on+ a member's chat (or **Answer in its thread** when the member waits for an+ approval there). That thread shows **Back to the team** at its top, the team+ stays marked in the thread list meanwhile, and the room comes back on the+ same chat. The start form has **Back** to what was open before it.## Stepping in@@ -162,13 +178,13 @@ A plan the coordinator cannot read (no block, broken JSON, a step without`done_when`) is never taken for a plan: the planner is asked once more withthe reason, then the thread waits for the person.-The board puts the plan on top: the current version (marked while it is-still proposed), each step with its state (open, building, in review,-changes requested, accepted) and who holds it, and an open revision request.-Below it, a plan round is a band with the plan beside its reviews; each step-of the plan is a band with its builds in the builder's lane and the reviews-beside them, fixes stacked under them; the final review is a band of its-own. Lane heads show each member's role.+The room's **Plan** tab shows the current version (marked while it is still+proposed), each step with its state (open, building, in review, changes+requested, accepted) and who holds it, and an open revision request. In the+story, a plan round, each step of the plan and the final review have a+heading of their own; the canvas shows each member's role, the plan going to+its readers, each step going to its reviewer and a blocked step going back to+the planner.Bounds are those of the table above, with two differences: plan rounds countper version (a revision starts again at one), and review rounds count perdiff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsxindex b8a4cd35fa..a131743fae 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx@@ -429,7 +429,7 @@ function changedFiles(turn: TurnItem): { path: string; added: number; removed: n}/** The thread's project folder, so changed files read relative to it. */-const ThreadFolder = createContext("");+export const ThreadFolder = createContext("");function slashes(path: string): string {return path.replace(/\\/g, "/");diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsxindex b1c44a1745..b1dc2ded09 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTree.tsx@@ -207,7 +207,8 @@ export function ThreadTree() {<span className="min-w-0 flex-1 truncate">{t("team_threads.new")}</span></div>}{teamRows.map((team) => {- const selected = selection.team === team.team_id;+ // A member's own thread, opened from the team, keeps its team marked.+ const selected = selection.team === team.team_id || selection.fromTeam === team.team_id;return <button key={team.team_id} type="button" aria-current={selected ? "page" : undefined}data-testid={`team-thread-row-${team.team_id}`}onClick={() => openTeam(team.team_id, project.id)} title={team.title}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsxindex 135a39a9f0..8e4b09c9a3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.test.tsx@@ -1,4 +1,5 @@-import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { AgentChatCatalog, AgentChatSession } from "@/lib/agentChatApi";import type { IdeProject } from "@/lib/agenticIdeApi";@@ -210,6 +211,24 @@ describe("ThreadTree", () => {}});+ it("leads from a member's own thread back to its team, and keeps the team marked meanwhile", async () => {+ teams.rows = [{ team_id: "t1", title: "Add a retry", cwd: "/repo", mode: "peers", state: "running", phase: "review", reason: "", created_ms: 1, updated_ms: 2, members: [] }];+ const member = sessionRow({ session_id: "s2", cli_title: "Add a retry · Claude", team_id: "t1" });+ api.fetchAgentChatSessions.mockResolvedValue([member]);+ try {+ useIdeThreadsStore.getState().openMemberThread("s2", "p1", "t1");+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}><ThreadTree /><ThreadView onScreen /></QueryClientProvider>);+ const back = await screen.findByTestId("thread-back-to-team");+ expect(back.textContent).toContain("Add a retry");+ expect(screen.getByTestId("team-thread-row-t1").getAttribute("aria-current")).toBe("page");+ fireEvent.click(within(back).getByRole("button"));+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null, team: "t1" });+ } finally {+ teams.rows = [];+ }+ });+it("moves a thread with Alt and the arrow keys and keeps that order", async () => {api.fetchAgentChatSessions.mockResolvedValue([sessionRow({ session_id: "s1", cli_title: "Older", updated_ms: 1 }),diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsxindex 89e0c71be8..cafb402cbd 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadView.tsx@@ -1,9 +1,10 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Check, ChevronDown, FolderPlus } from "lucide-react";+import { ArrowLeft, Check, ChevronDown, FolderPlus } from "lucide-react";import { prepareGit } from "@/lib/gitApi";+import { useTeamThreads } from "@/lib/teamThreadsApi";import type { AgentChatSession } from "@/lib/agentChatApi";import { useEventStore } from "@/store/events";-import { translate, useT } from "@/i18n";+import { fill, translate, useT } from "@/i18n";import { useIdeProjectsStore } from "@/store/ideProjects";import { useIdeThreadsStore } from "@/store/ideThreads";import { useThreadTerminalsStore } from "@/store/threadTerminals";@@ -241,6 +242,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {return <TeamThreadView key={selection.team} team={selection.team} project={project} onScreen={onScreen} />;}+ const memberOf = selection.fromTeam || session?.team_id || "";const threadKey = selection.sessionId ?? `draft:${project.id}`;const [buildBefore, buildAfter = ""] = t("ide_threads.build_in").split("{project}");const empty = isDraft && timeline.items.length === 0;@@ -249,6 +251,7 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {base={base} onBase={setBase} locked={running} />;return <div className="relative flex h-full min-h-0 flex-col" data-testid="thread-view">+ {memberOf && <BackToTeam teamId={memberOf} projectId={project.id} />}{empty? <div className="flex min-h-0 flex-1 flex-col items-center justify-center px-5 pb-10"><h2 className="text-center text-2xl font-normal tracking-tight text-foreground sm:text-3xl">@@ -285,3 +288,20 @@ export function ThreadView({ onScreen }: { onScreen: boolean }) {</OpenSubagent.Provider>}</div>;}++/**+ * A team member's own thread leads back to its team: the members are kept out+ * of the thread list, so without this line the team could not be reached+ * from here again.+ */+function BackToTeam({ teamId, projectId }: { teamId: string; projectId: string }) {+ const t = useT();+ const title = useTeamThreads().data?.find((row) => row.team_id === teamId)?.title ?? "";+ return <div className="flex h-9 shrink-0 items-center border-b border-border px-3" data-testid="thread-back-to-team">+ <button type="button" onClick={() => useIdeThreadsStore.getState().openTeam(teamId, projectId)}+ className="flex min-w-0 items-center gap-1.5 rounded-md px-1.5 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">+ <ArrowLeft aria-hidden className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate">{title ? fill(t("team_threads.room.back_named"), { title }) : t("team_threads.room.back")}</span>+ </button>+ </div>;+}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.tsxnew file mode 100644index 0000000000..42ff2224a0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamCanvas.tsx@@ -0,0 +1,308 @@+import { memo, useEffect, useMemo, useRef, useState } from "react";+import {+ Background,+ BackgroundVariant,+ BaseEdge,+ Controls,+ EdgeLabelRenderer,+ Handle,+ Position,+ ReactFlow,+ ReactFlowProvider,+ useReactFlow,+ type Edge,+ type EdgeProps,+ type Node,+ type NodeProps,+} from "@xyflow/react";+import "@xyflow/react/dist/style.css";+import { ArrowLeftRight, ShieldAlert, UserRound, Users } from "lucide-react";+import { AgentMark } from "@/components/agentic/AgentMark";+import { plural } from "@/components/agentchat/traceEntries";+import { fill, useT } from "@/i18n";+import type { TeamMember, TeamThread } from "@/lib/teamThreadsApi";+import { cn } from "@/lib/utils";+import { clock, useMemberStatus } from "./memberLive";+import { canvasLines, exchangeLabel, latestExchange, YOU, type EdgeTier, type Exchange, type GraphEdge, type GraphNode, type TeamGraph } from "./teamGraph";++/**+ * The team room's canvas: the members and the person as nodes, every handoff+ * between them as a line labelled with what went across.+ *+ * Nothing on it is decoration. A line that a member is working on right now+ * 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.+ * A click on a member opens its chat beside the canvas; a click on a line+ * shows what the two exchanged.+ */++interface MemberData extends Record<string, unknown> {+ node: GraphNode;+ agent: string;+ selected: boolean;+ over: boolean;+ onOpen: (id: string) => void;+}++interface YouData extends Record<string, unknown> {+ needed: boolean;+ selected: boolean;+ onOpen: (id: string) => void;+}++interface LineData extends Record<string, unknown> {+ line: GraphEdge;+ /** Both directions as one two-way line. */+ both: boolean;+ tier: EdgeTier;+ count: number;+ from: GraphNode;+ to: GraphNode;+ label: string;+ selected: boolean;+ hovered: boolean;+ faded: boolean;+ onOpen: (id: string) => void;+}++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>>) {+ const t = useT();+ const { node, agent, selected, over, onOpen } = data;+ const member = node.member as TeamMember;+ const status = useMemberStatus(member, over);+ const role = member.role ? t(`team_threads.member_role.${member.role}`) : "";+ return <div style={{ width: node.width, height: node.height }}>+ <Handle type="target" position={Position.Top} className={hidden} isConnectable={false} />+ <button type="button" onClick={() => onOpen(member.member_id)} data-testid={`team-node-${member.member_id}`}+ data-state={status.tone} aria-pressed={selected}+ aria-label={`${member.name}${role ? ` · ${role}` : ""} · ${status.text}`}+ className={cn(+ "nodrag nopan flex h-full w-full flex-col justify-center gap-1 rounded-lg border bg-card px-3 text-left transition-[border-color,box-shadow] duration-200",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "border-accent shadow-[0_0_0_1px_hsl(var(--accent))]"+ : status.tone === "working" ? "border-accent/60"+ : status.tone === "waiting" ? "border-warning/70" : "border-border hover:border-border-strong",+ status.tone === "left" && "opacity-55",+ )}>+ <span className="flex min-w-0 items-center gap-2">+ <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>+ {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",+ status.tone === "working" ? "text-foreground" : status.tone === "waiting" ? "text-warning" : "text-muted-foreground")}>+ {status.tone === "waiting" ? <ShieldAlert aria-hidden className="h-3 w-3 shrink-0" />+ : <span aria-hidden className={cn("h-1.5 w-1.5 shrink-0 rounded-full",+ status.tone === "working" ? "team-pulse bg-accent" : "bg-border-strong")} />}+ <span className={cn("min-w-0 flex-1 truncate", status.call && "font-mono text-[11px]")}>{status.text}</span>+ {status.tone === "working" && status.seconds > 0 && <span className="shrink-0 tabular-nums text-muted-foreground">{clock(status.seconds)}</span>}+ </span>+ {member.model && !member.name.includes(member.model) && <span className="truncate pl-8 font-mono text-[10px] text-muted-foreground">{member.model}</span>}+ </button>+ <Handle type="source" position={Position.Bottom} className={hidden} isConnectable={false} />+ </div>;+});++const YouNode = memo(function YouNode({ data }: NodeProps<Node<YouData>>) {+ const t = useT();+ return <div className="h-12 w-44">+ <Handle type="target" position={Position.Top} className={hidden} isConnectable={false} />+ <button type="button" onClick={() => data.onOpen(YOU)} data-testid="team-node-you" aria-pressed={data.selected}+ className={cn(+ "nodrag nopan flex h-full w-full items-center justify-center gap-2 rounded-full border bg-card px-3 text-sm",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ data.needed ? "border-warning/70 text-foreground" : "border-border text-foreground hover:border-border-strong",+ data.selected && "border-accent",+ )}>+ <UserRound aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <span className="font-medium">{t("team_threads.room.you")}</span>+ {data.needed && <span className="flex items-center gap-1 text-xs text-warning"><span aria-hidden className="h-1.5 w-1.5 rounded-full bg-warning" />{t("team_threads.room.needs_you")}</span>}+ </button>+ <Handle type="source" position={Position.Bottom} className={hidden} isConnectable={false} />+ </div>;+});++/** Where the line from a node's centre towards `toward` leaves its box. */+function exit(node: GraphNode, toward: { x: number; y: number }, gap: number) {+ const dx = toward.x - node.x;+ const dy = toward.y - node.y;+ if (!dx && !dy) return { x: node.x, y: node.y };+ const scale = Math.min(dx ? (node.width / 2 + gap) / Math.abs(dx) : Infinity, dy ? (node.height / 2 + gap) / Math.abs(dy) : Infinity);+ return { x: node.x + dx * scale, y: node.y + dy * scale };+}++/** The bend of a line: both directions between two nodes bow to opposite sides. */+const BOW = 34;++/**+ * A line's path and where its label sits. The person's lines carry their label+ * near the member they reach, clear of the lines between the members.+ */+export function linePath(from: GraphNode, to: GraphNode, both = false) {+ const dx = to.x - from.x;+ const dy = to.y - from.y;+ const length = Math.hypot(dx, dy) || 1;+ const bow = both ? 0 : BOW;+ const control = { x: (from.x + to.x) / 2 - (dy / length) * bow, y: (from.y + to.y) / 2 + (dx / length) * bow };+ const start = exit(from, control, both ? 9 : 4);+ const end = exit(to, control, 9);+ // Two two-way lines crossing in the middle keep their labels apart.+ const at = from.kind === "you" ? 0.74 : both ? 0.4 : 0.5;+ const point = (a: number, b: number, c: number) => (1 - at) * (1 - at) * a + 2 * (1 - at) * at * b + at * at * c;+ const label = { x: point(start.x, control.x, end.x), y: point(start.y, control.y, end.y) };+ return { path: `M ${start.x} ${start.y} Q ${control.x} ${control.y} ${end.x} ${end.y}`, label };+}++const STROKE: Record<EdgeTier | "selected", string> = {+ selected: "stroke-[hsl(var(--accent))] [stroke-width:2]",+ live: "team-flow stroke-[hsl(var(--accent))] [stroke-width:1.75]",+ current: "stroke-[hsl(var(--foreground)/0.5)] [stroke-width:1.5]",+ past: "stroke-[hsl(var(--border-strong))] [stroke-width:1]",+};++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 { path, label: at } = linePath(from, to, both);+ const tier = selected ? "selected" : data.tier;+ const exchange = latestExchange(line);+ const showLabel = selected || hovered || data.tier !== "past";+ return <>+ <BaseEdge id={id} path={path} interactionWidth={18}+ className={cn("fill-none", STROKE[tier], faded && "opacity-40")}+ markerStart={both ? `url(#team-arrow-${tier})` : undefined}+ markerEnd={`url(#team-arrow-${tier})`} />+ {showLabel && label && <EdgeLabelRenderer>+ <button type="button" onClick={() => onOpen(line.id)} data-testid={`team-edge-${line.id}`} data-tier={data.tier}+ aria-label={fill(t("team_threads.room.exchange_open"), { label })}+ style={{ transform: `translate(-50%, -50%) translate(${at.x}px, ${at.y}px)` }}+ className={cn(+ "nodrag nopan pointer-events-auto absolute flex max-w-[200px] items-center gap-1.5 rounded-md border bg-card px-1.5 py-0.5 text-[11px] leading-4 shadow-sm",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "border-accent text-foreground" : data.tier === "live" ? "border-accent/50 text-foreground"+ : data.tier === "current" ? "border-border-strong text-foreground" : "border-border text-muted-foreground",+ faded && "opacity-60",+ )}>+ {exchange && exchange.tone !== "neutral" && <span aria-hidden className={cn("h-1.5 w-1.5 shrink-0 rounded-full",+ exchange.tone === "positive" ? "bg-success" : "bg-warning")} />}+ {both && <ArrowLeftRight aria-hidden className="h-3 w-3 shrink-0 text-muted-foreground" />}+ <span className="truncate">{label}</span>+ {count > 1 && <span className="shrink-0 tabular-nums text-muted-foreground"+ title={fill(t(`team_threads.room.exchange_count_${plural(lang, count)}`), { count })}>×{count}</span>}+ </button>+ </EdgeLabelRenderer>}+ </>;+});++const nodeTypes = { member: MemberNode, you: YouNode };+const edgeTypes = { line: LineEdge };++/** Arrowheads per line state; their ink follows the theme. */+function Arrows() {+ const head = (id: string, ink: string) => <marker key={id} id={`team-arrow-${id}`} viewBox="0 0 10 10" refX="8" refY="5"+ markerWidth="7" markerHeight="7" orient="auto-start-reverse">+ <path d="M 0 1 L 9 5 L 0 9 z" className={ink} />+ </marker>;+ return <svg aria-hidden width="0" height="0" className="absolute">+ <defs>+ {head("selected", "fill-[hsl(var(--accent))]")}+ {head("live", "fill-[hsl(var(--accent))]")}+ {head("current", "fill-[hsl(var(--foreground)/0.5)]")}+ {head("past", "fill-[hsl(var(--border-strong))]")}+ </defs>+ </svg>;+}++export interface TeamCanvasProps {+ thread: TeamThread;+ graph: TeamGraph;+ agentOf: (member: TeamMember) => string;+ selectedNode: string | null;+ selectedEdge: string | null;+ onOpenNode: (id: string) => void;+ onOpenEdge: (id: string) => void;+}++function Canvas({ thread, graph, agentOf, selectedNode, selectedEdge, onOpenNode, onOpenEdge }: TeamCanvasProps) {+ const t = useT();+ const lang = t("trace_report.locale");+ const flow = useReactFlow();+ const frame = useRef<HTMLDivElement | null>(null);+ const [hovered, setHovered] = useState<string | null>(null);+ const over = thread.state === "done" || thread.state === "stopped" || thread.state === "failed";+ const byId = useMemo(() => new Map(graph.nodes.map((node) => [node.id, node])), [graph.nodes]);++ const nodes = useMemo<Node[]>(() => graph.nodes.map((node) => node.kind === "you"+ ? {+ id: node.id, type: "you", position: { x: node.x - node.width / 2, y: node.y - node.height / 2 },+ width: node.width, height: node.height, draggable: false, selectable: false,+ data: { needed: thread.state === "needs_input", selected: selectedNode === YOU, onOpen: onOpenNode } satisfies YouData,+ }+ : {+ id: node.id, type: "member", position: { x: node.x - node.width / 2, y: node.y - node.height / 2 },+ width: node.width, height: node.height, draggable: false, selectable: false,+ data: {+ node, agent: agentOf(node.member as TeamMember), selected: selectedNode === node.id, over, onOpen: 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]);++ // The whole team stays in the frame when the frame or the team changes size.+ const count = graph.nodes.length;+ useEffect(() => {+ const box = frame.current;+ const fit = () => void flow.fitView({ padding: 0.12, maxZoom: 1.3, duration: 0 });+ fit();+ if (!box || typeof ResizeObserver === "undefined") return;+ let pending = 0;+ const observer = new ResizeObserver(() => {+ window.cancelAnimationFrame(pending);+ pending = window.requestAnimationFrame(fit);+ });+ observer.observe(box);+ return () => { observer.disconnect(); window.cancelAnimationFrame(pending); };+ }, [flow, count]);++ return <div ref={frame} className="team-canvas relative h-full w-full" data-testid="team-canvas"+ role="group" aria-label={t("team_threads.room.canvas")}>+ <Arrows />+ <ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={edgeTypes}+ fitView fitViewOptions={{ padding: 0.12, maxZoom: 1.3 }} minZoom={0.35} maxZoom={1.6}+ nodesDraggable={false} nodesConnectable={false} elementsSelectable={false} nodesFocusable={false} edgesFocusable={false}+ zoomOnScroll={false} zoomOnDoubleClick={false} panOnScroll={false} preventScrolling={false}+ onEdgeClick={(_, edge) => onOpenEdge(edge.id)}+ onEdgeMouseEnter={(_, edge) => setHovered(edge.id)} onEdgeMouseLeave={() => setHovered(null)}+ proOptions={{ hideAttribution: true }}>+ <Background variant={BackgroundVariant.Dots} gap={20} size={1} />+ <Controls position="bottom-right" showInteractive={false} fitViewOptions={{ padding: 0.12, maxZoom: 1.3 }} />+ </ReactFlow>+ </div>;+}++export default function TeamCanvas(props: TeamCanvasProps) {+ return <ReactFlowProvider><Canvas {...props} /></ReactFlowProvider>;+}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.tsxnew file mode 100644index 0000000000..ea07e232c7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamSide.tsx@@ -0,0 +1,304 @@+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 { AgentMark } from "@/components/agentic/AgentMark";+import type { TimelineItem, UserItem } from "@/components/agentchat/reduce";+import { plural } from "@/components/agentchat/traceEntries";+import { fill, useT } from "@/i18n";+import type { TeamMember, TeamThread } from "@/lib/teamThreadsApi";+import { cn } from "@/lib/utils";+import { ThreadFolder, ThreadTurn } from "../ThreadTimeline";+import { useMemberTimeline } from "./memberStreams";+import { useMemberStatus } from "./memberLive";+import { PlanPanel } from "./PlanPanel";+import { PROSE_COMPACT } from "./roomStyle";+import { exchangeLabel, YOU, type Exchange, type TeamGraph } from "./teamGraph";+import { EntryBody, kindLabel, leadOf, TeamStory, verdictOf, type RoomNames } from "./TeamStory";++/**+ * The team room's side column: the chats, right beside the canvas.+ *+ * A tab per member shows that member's own conversation as it streams in (its+ * turns, tool calls and words); the team's shared story and, for planner and+ * 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.+ */++export type RoomTab = { kind: "story" } | { kind: "plan" } | { kind: "member"; id: string };++export const tabKey = (tab: RoomTab) => (tab.kind === "member" ? `member:${tab.id}` : tab.kind);++interface SideProps {+ thread: TeamThread;+ graph: TeamGraph;+ names: RoomNames;+ folder: string;+ tab: RoomTab;+ onTab: (tab: RoomTab) => void;+ following: boolean;+ onFollow: () => void;+ edge: string | null;+ onCloseEdge: () => void;+ onOpenFull: (member: TeamMember) => void;+}++export function TeamSide({ thread, graph, names, folder, tab, onTab, following, onFollow, edge, onCloseEdge, onOpenFull }: SideProps) {+ const t = useT();+ const tabs: RoomTab[] = [+ { kind: "story" },+ ...(thread.mode === "planner_builder" ? [{ kind: "plan" } as RoomTab] : []),+ ...thread.members.map((member): RoomTab => ({ kind: "member", id: member.member_id })),+ ];+ const current = tabKey(tab);+ const refs = useRef(new Map<string, HTMLButtonElement | null>());+ // Arrow keys move along the tabs, as in any tab list.+ const onKey = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "ArrowRight" && event.key !== "ArrowLeft" && event.key !== "Home" && event.key !== "End") return;+ event.preventDefault();+ const at = tabs.findIndex((item) => tabKey(item) === current);+ const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1+ : (at + (event.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length;+ onTab(tabs[next]);+ refs.current.get(tabKey(tabs[next]))?.focus();+ };+ const member = tab.kind === "member" ? names.member(tab.id) : undefined;++ 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}+ 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);+ const selected = key === current && !edge;+ const person = item.kind === "member" ? names.member(item.id) : undefined;+ return <button key={key} ref={(node) => { refs.current.set(key, node); }} type="button" role="tab"+ aria-selected={selected} tabIndex={key === current ? 0 : -1} onClick={() => onTab(item)}+ title={person?.name}+ data-testid={`team-tab-${key}`}+ className={cn(+ "relative flex shrink-0 items-center gap-1.5 px-2.5 text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",+ selected ? "text-foreground after:absolute after:inset-x-2 after:bottom-0 after:h-0.5 after:bg-accent" : "text-muted-foreground hover:text-foreground",+ )}>+ {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}+ </button>;+ })}+ </div>+ <button type="button" onClick={onFollow} aria-pressed={following} data-testid="team-follow"+ title={t("team_threads.room.follow_hint")}+ className={cn(+ "my-1.5 flex shrink-0 items-center gap-1 rounded-md px-2 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ following ? "text-accent" : "text-muted-foreground hover:bg-secondary hover:text-foreground",+ )}>+ <Crosshair aria-hidden className="h-3.5 w-3.5" />{t("team_threads.room.follow")}+ </button>+ </div>+ <div className="flex min-h-0 flex-1 flex-col" role="tabpanel" aria-label={current}>+ {edge ? <ExchangeView graph={graph} edge={edge} names={names} onClose={onCloseEdge} />+ : tab.kind === "story" ? <TeamStory thread={thread} graph={graph} names={names} />+ : tab.kind === "plan" ? <div className="min-h-0 flex-1 overflow-y-auto p-3 scrollbar-jarvis"><PlanPanel thread={thread} names={new Map(thread.members.map((item) => [item.member_id, item.name]))} /></div>+ : member ? <MemberChat key={member.member_id} member={member} thread={thread} names={names} folder={folder} onOpenFull={() => onOpenFull(member)} />+ : null}+ </div>+ </section>;+}++function TabMember({ member, names }: { member: TeamMember; names: RoomNames }) {+ 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>+ {!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}+ </>;+}++/* ------------------------------------------------------------- member chat */++/** A brief the coordinator handed the member: folded to its first line, it is long. */+function Brief({ item }: { item: UserItem }) {+ const t = useT();+ const [open, setOpen] = useState(false);+ const first = item.text.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? "";+ return <div className="min-w-0 rounded-md border border-border" data-testid="team-chat-brief">+ <button type="button" onClick={() => setOpen(!open)} aria-expanded={open}+ className="flex w-full min-w-0 items-center gap-2 px-2.5 py-1.5 text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">+ <ArrowDown aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="shrink-0 font-medium text-foreground">{t("team_threads.room.brief")}</span>+ {!open && <span className="min-w-0 flex-1 truncate text-muted-foreground">{first.replace(/^#+\s*/, "")}</span>}+ <ChevronRight aria-hidden className={cn("ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")} />+ </button>+ {open && <div className="max-h-[50vh] overflow-y-auto whitespace-pre-wrap border-t border-border px-2.5 py-2 font-mono text-xs leading-5 text-foreground/85 scrollbar-jarvis [overflow-wrap:anywhere]">+ {item.text}+ </div>}+ </div>;+}++function ChatItem({ item }: { item: TimelineItem }) {+ if (item.type === "user") {+ if (item.author) return <Brief item={item} />;+ return <div className="flex justify-end"><div className="max-w-[85%] whitespace-pre-wrap rounded-2xl bg-secondary px-3.5 py-2 text-sm text-foreground [overflow-wrap:anywhere]">{item.text}</div></div>;+ }+ if (item.type === "turn") return <ThreadTurn turn={item} />;+ if (item.type === "error") return <p role="alert" className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">{item.text}</p>;+ if (item.type === "notice") return <p className="text-center text-xs text-muted-foreground">{item.text}</p>;+ return <div className={PROSE_COMPACT}>{item.message.text}</div>;+}++/** One member's own conversation, live, read-only: the team speaks to it, the person steps in below. */+function MemberChat({ member, thread, names, folder, onOpenFull }: {+ member: TeamMember; thread: TeamThread; names: RoomNames; folder: string; onOpenFull: () => void;+}) {+ const t = useT();+ const timeline = useMemberTimeline(member.session_id, true);+ const over = thread.state === "done" || thread.state === "stopped" || thread.state === "failed";+ const status = useMemberStatus(member, over);+ const agent = names.agent(member);+ const scroller = useRef<HTMLDivElement | null>(null);+ const pinned = useRef(true);+ const [away, setAway] = useState(false);+ useLayoutEffect(() => {+ const box = scroller.current;+ if (box && pinned.current) box.scrollTop = box.scrollHeight;+ });+ useEffect(() => {+ const box = scroller.current;+ if (!box || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => { if (pinned.current) box.scrollTop = box.scrollHeight; });+ const content = box.firstElementChild;+ if (content) observer.observe(content);+ return () => observer.disconnect();+ }, []);+ const items = timeline.items;+ return <div className="flex min-h-0 flex-1 flex-col" data-testid={`team-chat-${member.member_id}`}>+ <div className="flex min-h-11 shrink-0 items-center gap-2 border-b border-border px-3 py-1.5">+ <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" /> : null}+ </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>+ {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>+ <span className={cn("block truncate text-xs", status.tone === "waiting" ? "text-warning" : status.tone === "working" ? "text-foreground" : "text-muted-foreground")}>+ {status.text}+ </span>+ </span>+ <button type="button" onClick={onOpenFull} data-testid="team-chat-open-full"+ className={cn(+ "flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ member.waiting ? "bg-warning/15 font-medium text-foreground hover:bg-warning/25" : "text-muted-foreground hover:bg-secondary hover:text-foreground",+ )}>+ {member.waiting ? t("team_threads.room.answer_in_thread") : t("team_threads.room.open_full")}+ <ExternalLink aria-hidden className="h-3 w-3" />+ </button>+ </div>+ <ThreadFolder.Provider value={folder}>+ <div className="relative min-h-0 flex-1">+ <div ref={scroller} className="h-full overflow-y-auto scrollbar-jarvis" data-testid="team-chat-scroll"+ onScroll={(event) => {+ const box = event.currentTarget;+ const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 48;+ pinned.current = atBottom;+ setAway(!atBottom);+ }}>+ <div className="team-chat flex flex-col gap-4 px-4 pb-6 pt-4">+ {items.length === 0+ ? <p className="py-8 text-center text-sm text-muted-foreground">{fill(t("team_threads.room.chat_empty"), { member: member.name })}</p>+ : items.map((item) => <ChatItem key={item.id} item={item} />)}+ </div>+ </div>+ {away && <button type="button" aria-label={t("ide_threads.scroll_newest")}+ onClick={() => { const box = scroller.current; if (box) box.scrollTo({ top: box.scrollHeight, behavior: "smooth" }); }}+ className="absolute bottom-3 left-1/2 z-10 flex h-8 w-8 -translate-x-1/2 items-center justify-center rounded-full border border-border bg-popover text-muted-foreground shadow-float hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <ArrowDown className="h-4 w-4" />+ </button>}+ </div>+ </ThreadFolder.Provider>+ </div>;+}++/* ---------------------------------------------------------------- exchange */++function Who({ id, names }: { id: string; names: RoomNames }) {+ const t = useT();+ const member = names.member(id);+ 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>+ </span>;+}++/** What went across one line of the canvas, both ways, in order. */+function ExchangeView({ graph, edge, names, onClose }: { graph: TeamGraph; edge: string; names: RoomNames; onClose: () => void }) {+ const t = useT();+ const lang = t("trace_report.locale");+ const line = graph.edges.find((item) => item.id === edge);+ // Escape closes it, unless the person is typing.+ useEffect(() => {+ const onKey = (event: globalThis.KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ if (event.target instanceof Element && event.target.closest("textarea, input, [contenteditable=true]")) return;+ onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);+ if (!line) return null;+ const both = graph.edges+ .filter((item) => (item.from === line.from && item.to === line.to) || (item.from === line.to && item.to === line.from))+ .flatMap((item) => item.exchanges)+ .sort((left, right) => left.seq - right.seq);+ return <div className="flex min-h-0 flex-1 flex-col" data-testid="team-exchange">+ <div className="flex min-h-11 shrink-0 items-center gap-2 border-b border-border px-3 text-sm">+ <Who id={line.from} names={names} />+ {both.some((item) => item.from === line.to)+ ? <ArrowLeftRight aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ : <ArrowRight aria-hidden className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}+ <Who id={line.to} names={names} />+ <span className="ml-1 truncate text-xs text-muted-foreground">{fill(t(`team_threads.room.exchange_count_${plural(lang, both.length)}`), { count: both.length })}</span>+ <button type="button" onClick={onClose} aria-label={t("team_threads.close_reader")} title={t("team_threads.close_reader")}+ data-testid="team-exchange-close"+ className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <X className="h-3.5 w-3.5" />+ </button>+ </div>+ <ol className="min-h-0 flex-1 overflow-y-auto px-3 pb-6 pt-2 scrollbar-jarvis">+ {both.map((exchange, index) => <ExchangeItem key={`${exchange.seq}:${exchange.from}:${exchange.to}`} exchange={exchange} names={names}+ label={exchangeLabel(exchange, t, lang)} highlight={exchange.from === line.from} first={index === both.length - 1} />)}+ </ol>+ </div>;+}++/** One exchange: a line with who, what and the verdict; the newest opens to its whole text. */+function ExchangeItem({ exchange, names, label, highlight, first }: {+ exchange: Exchange; names: RoomNames; label: string; highlight: boolean; first: boolean;+}): ReactNode {+ const t = useT();+ const entry = exchange.entry;+ const verdict = verdictOf(entry, t);+ const [open, setOpen] = useState(first);+ return <li className={cn("border-l-[3px] py-1.5 pl-3 pr-1", highlight ? "border-accent/60" : "border-border")} data-testid="team-exchange-item">+ <button type="button" onClick={() => setOpen(!open)} aria-expanded={open}+ className="group flex w-full min-w-0 flex-col gap-0.5 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span className="flex w-full flex-wrap items-baseline gap-x-1.5 text-xs">+ <span className="font-medium text-foreground">{exchange.from === YOU ? t("team_threads.room.you") : names.name(exchange.from)}</span>+ <span className="text-muted-foreground">→ {exchange.to === YOU ? t("team_threads.room.you") : names.name(exchange.to)}</span>+ <span className="text-muted-foreground">· {entry.kind === "user" ? label : kindLabel(entry, t)}</span>+ {verdict && <span className={cn("font-medium", verdict.tone === "positive" ? "text-success" : "text-warning")}>{verdict.text}</span>}+ <ChevronRight aria-hidden className={cn("ml-auto h-3.5 w-3.5 shrink-0 self-center text-muted-foreground transition-transform", open && "rotate-90")} />+ </span>+ {!open && <span className="line-clamp-2 text-[13px] leading-5 text-muted-foreground [overflow-wrap:anywhere]">{leadOf(entry, t)}</span>}+ </button>+ {open && <div className="pt-1.5">+ {entry.kind === "user"+ ? <p className="whitespace-pre-wrap text-sm text-foreground [overflow-wrap:anywhere]">{entry.payload.text}</p>+ : <EntryBody entry={entry} />}+ </div>}+ </li>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamStory.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamStory.tsxnew file mode 100644index 0000000000..280c6ec065--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamStory.tsx@@ -0,0 +1,350 @@+import { useLayoutEffect, useMemo, useState } from "react";+import { ChevronRight, ShieldAlert } from "lucide-react";+import { AgentMark } from "@/components/agentic/AgentMark";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";+import { useStickToBottom } from "@/hooks/useStickToBottom";+import { fill, useT } from "@/i18n";+import type { TeamEntry, TeamFinding, TeamMember, TeamThread } from "@/lib/teamThreadsApi";+import { cn } from "@/lib/utils";+import { buildBoard, gist, type StepBand } from "./board";+import { clock, useMemberStatus } from "./memberLive";+import { PROSE_COMPACT } from "./roomStyle";+import type { TeamGraph } from "./teamGraph";++/**+ * The team's shared story: who contributed what, step by step, as one quiet+ * list. A step opens with a small heading; each contribution is one line with+ * its author, what it is, its verdict and to whom it went, plus a two-line+ * gist; a click unfolds the whole text in place. The person's words, notices+ * and the outcome sit where they happened. What the members caught in each+ * other's work closes the list.+ */++export interface RoomNames {+ name: (id: string) => string;+ agent: (member: TeamMember) => string;+ member: (id: string) => TeamMember | undefined;+}++/** The heading of a step in the story: "Master plan · round 2", "Step 3 · Add the setting". */+function stepHeading(band: StepBand, t: (key: string) => string): string {+ if (band.step === "step") return [fill(t("team_threads.plan.step"), { number: band.number ?? 0 }), band.title].filter(Boolean).join(" · ");+ const name = t(`team_threads.phase.${band.step}`);+ return band.round > 1 && band.step !== "planning" ? `${name} · ${fill(t("team_threads.round"), { round: band.round })}` : name;+}++export function verdictOf(entry: TeamEntry, t: (key: string) => string): { text: string; tone: "positive" | "negative" } | null {+ const payload = entry.payload;+ if (entry.kind === "vote" || entry.kind === "plan_review") {+ return { text: t(payload.agree ? "team_threads.vote.agree" : "team_threads.vote.object"), tone: payload.agree ? "positive" : "negative" };+ }+ if (entry.kind === "review" || entry.kind === "step_review") {+ return { text: t(payload.approve ? "team_threads.review.approve" : "team_threads.review.changes"), tone: payload.approve ? "positive" : "negative" };+ }+ if (entry.kind === "plan_version" && payload.valid === false) return { text: t("team_threads.plan.unreadable"), tone: "negative" };+ if (entry.kind === "step_build") {+ const blocked = payload.status === "blocked";+ return { text: t(blocked ? "team_threads.plan.blocked" : "team_threads.plan.done"), tone: blocked ? "negative" : "positive" };+ }+ return null;+}++/** What a contribution is called: "Own plan", "Plan v2", "Step 3". */+export function kindLabel(entry: TeamEntry, t: (key: string) => string): string {+ if (entry.kind === "plan_version" && entry.payload.valid !== false) return fill(t("team_threads.plan.title"), { version: entry.payload.version ?? 1 });+ if ((entry.kind === "step_build" || entry.kind === "step_review") && entry.payload.number) {+ return `${t(`team_threads.kind.${entry.kind}`)} ${entry.payload.number}`;+ }+ return t(`team_threads.kind.${entry.kind}`);+}++/** The first thing worth reading of a contribution, in one or two lines. */+export function leadOf(entry: TeamEntry, t: (key: string) => string): string {+ const payload = entry.payload;+ const objection = (payload.objections ?? [])[0];+ const finding = (payload.findings ?? []).find((item) => item.severity === "blocking") ?? (payload.findings ?? [])[0];+ if (objection) return objection;+ if (finding) return [finding.where, finding.issue].filter(Boolean).join(": ");+ if (entry.kind === "plan_version" && payload.valid === false) return payload.error ?? "";+ if (entry.kind === "step_build" && payload.status === "blocked" && payload.note) return payload.note;+ return gist(payload.text ?? "", 220) || t("team_threads.no_report");+}++/** The whole of one contribution: its text, plan steps, objections, findings, files. */+export function EntryBody({ entry }: { entry: TeamEntry }) {+ const t = useT();+ const payload = entry.payload;+ const points = entry.kind === "vote" || entry.kind === "plan_review" ? payload.objections ?? [] : [];+ return <div className="min-w-0" data-testid="team-entry-body">+ {payload.text ? <div className={PROSE_COMPACT}><ChatMarkdown text={payload.text} /></div>+ : <p className="text-sm text-muted-foreground">{t("team_threads.no_report")}</p>}+ {points.length > 0 && <ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-foreground">+ {points.map((point, index) => <li key={index} className="[overflow-wrap:anywhere]">{point}</li>)}+ </ul>}+ {entry.kind === "plan_version" && payload.valid === false && payload.error && <p className="mt-2 text-sm text-warning">{payload.error}</p>}+ {(payload.steps ?? []).length > 0 && <ol className="mt-3 flex flex-col divide-y divide-border border-y border-border" data-testid="team-entry-plan">+ {(payload.steps ?? []).map((step, index) => <li key={index} className="flex gap-3 py-2 text-sm">+ <span className="w-4 shrink-0 text-right font-mono text-xs leading-5 text-muted-foreground">{index + 1}</span>+ <span className="min-w-0">+ <span className="block font-medium text-foreground">{step.title}</span>+ {step.goal && <span className="block text-foreground/80 [overflow-wrap:anywhere]">{step.goal}</span>}+ <span className="block text-xs text-muted-foreground [overflow-wrap:anywhere]">{t("team_threads.plan.done_when")}: {step.done_when}</span>+ </span>+ </li>)}+ </ol>}+ {entry.kind === "step_build" && (payload.note || payload.plan_change) && <p className="mt-3 text-sm text-foreground [overflow-wrap:anywhere]">+ {[payload.note, payload.plan_change && fill(t("team_threads.plan.plan_change"), { text: payload.plan_change })].filter(Boolean).join(" · ")}+ </p>}+ {(payload.findings ?? []).length > 0 && <ul className="mt-3 flex flex-col gap-1">+ {(payload.findings ?? []).map((finding, index) => <FindingRow key={index} finding={finding} />)}+ </ul>}+ {(payload.files ?? []).length > 0 && <p className="mt-3 font-mono text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere]" title={payload.stat}>+ {(payload.files ?? []).join(" · ")}+ </p>}+ </div>;+}++export function FindingRow({ finding, by, resolved }: { finding: TeamFinding; by?: string; resolved?: boolean }) {+ const t = useT();+ const blocking = finding.severity === "blocking";+ return <li className={cn("border-l-[3px] py-1 pl-3 text-sm", blocking ? "border-destructive" : "border-border-strong")}+ data-severity={finding.severity}>+ <div className="flex flex-wrap items-baseline gap-x-2 text-xs">+ <span className={cn("font-medium", blocking ? "text-destructive" : "text-muted-foreground")}>{t(`team_threads.severity.${finding.severity}`)}</span>+ {by && <span className="text-foreground">{by}</span>}+ {finding.where && <code className="font-mono text-muted-foreground [overflow-wrap:anywhere]">{finding.where}</code>}+ {resolved !== undefined && <span className={cn("ml-auto", resolved ? "text-success" : "text-warning")}>+ {t(resolved ? "team_threads.issues.resolved" : "team_threads.issues.open")}+ </span>}+ </div>+ <p className="mt-0.5 text-foreground [overflow-wrap:anywhere]">{finding.issue}</p>+ {finding.fix && <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">{finding.fix}</p>}+ </li>;+}++function Mark({ member, names }: { member: TeamMember | undefined; names: RoomNames }) {+ const agent = member ? names.agent(member) : "";+ return <span className="grid h-5 w-5 shrink-0 place-items-center rounded bg-secondary">+ {agent && member ? <AgentMark agent={agent} label={member.name} variant="plain" size="sm" /> : null}+ </span>;+}++/** One contribution as a line; a click unfolds it in place. */+function StoryEntry({ entry, names, to, open, onToggle }: {+ entry: TeamEntry; names: RoomNames; to: string[]; open: boolean; onToggle: () => void;+}) {+ const t = useT();+ const verdict = verdictOf(entry, t);+ const member = names.member(entry.author);+ return <li className="min-w-0" data-testid={`team-story-${entry.kind}`} data-seq={entry.seq}>+ <button type="button" onClick={onToggle} aria-expanded={open}+ className="group flex w-full min-w-0 gap-2.5 rounded-md px-2 py-1.5 text-left hover:bg-secondary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Mark member={member} names={names} />+ <span className="min-w-0 flex-1">+ <span className="flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm">+ <span className="font-medium text-foreground">{names.name(entry.author)}</span>+ <span className="text-muted-foreground">{kindLabel(entry, t)}</span>+ {verdict && <span className={cn("text-xs font-medium", verdict.tone === "positive" ? "text-success" : "text-warning")}>{verdict.text}</span>}+ {to.length > 0 && <span className="min-w-0 truncate text-xs text-muted-foreground">→ {to.join(", ")}</span>}+ <span className="ml-auto shrink-0 pl-2 text-xs tabular-nums text-muted-foreground">{time(entry.ts_ms)}</span>+ </span>+ {!open && <span className="mt-0.5 line-clamp-2 text-[13px] leading-5 text-muted-foreground [overflow-wrap:anywhere]">{leadOf(entry, t)}</span>}+ </span>+ <ChevronRight aria-hidden className={cn("mt-1 h-3.5 w-3.5 shrink-0 text-muted-foreground opacity-0 transition group-hover:opacity-70", open && "rotate-90 opacity-70")} />+ </button>+ {open && <div className="pb-2 pl-[38px] pr-2 pt-1"><EntryBody entry={entry} /></div>}+ </li>;+}++const time = (ms: number) => {+ if (!ms || ms < 1e11) return "";+ const date = new Date(ms);+ return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;+};++function Notice({ entry, names }: { entry: TeamEntry; names: RoomNames }) {+ const t = useT();+ const payload = entry.payload;+ const code = payload.code ?? "";+ return <li className="flex items-center gap-3 px-2 py-1 text-xs text-muted-foreground" data-testid={`team-notice-${code}`}>+ <span aria-hidden className="h-px w-3 shrink-0 bg-border" />+ <span className="min-w-0 [overflow-wrap:anywhere]">+ {fill(t(`team_threads.notice.${code}`), {+ member: names.name(payload.member_id ?? payload.by ?? ""),+ error: payload.error ?? "", note: payload.note ?? "", rounds: payload.rounds ?? 0,+ step: payload.step ? t(`team_threads.kind.${payload.step}`) : "",+ files: (payload.files ?? []).join(", "), model: payload.model ?? "",+ number: payload.number ?? 0, version: payload.version ?? 0, count: payload.count ?? 0, title: payload.title ?? "",+ role: payload.role ? t(`team_threads.member_role.${payload.role}`) : "",+ })}+ </span>+ </li>;+}++export function Summary({ entry, names }: { entry: TeamEntry; names: RoomNames }) {+ const t = useT();+ const payload = entry.payload;+ const outcome = payload.outcome ?? "done";+ const finished = outcome === "done" || outcome === "accepted_by_user";+ return <li data-testid={`team-summary-${outcome}`}+ className={cn("my-2 border-l-[3px] py-1.5 pl-3 pr-2 text-sm", finished ? "border-success" : "border-warning")}>+ <p className="font-medium text-foreground">+ {finished && payload.mode === "planner_builder"+ ? fill(t(outcome === "done" ? "team_threads.summary.planned_done" : "team_threads.summary.planned_accepted"), {+ count: payload.step_count ?? 0, version: payload.version ?? 1, rounds: payload.step_rounds ?? 0,+ findings: payload.finding_count ?? 0, blocking: payload.blocking ?? 0,+ })+ : finished+ ? fill(t(`team_threads.summary.${outcome}`), {+ plan: payload.plan_rounds ?? 1, review: payload.review_rounds ?? 1,+ count: payload.finding_count ?? 0, blocking: payload.blocking ?? 0,+ builder: names.name(payload.builder ?? ""),+ })+ : fill(t(`team_threads.reason.${outcome}`), { rounds: payload.rounds ?? 0, note: "", number: payload.number ?? 0 })}+ </p>+ {finished && (payload.files ?? []).length > 0 && <p className="mt-1 text-xs text-muted-foreground" title={payload.stat}>+ {fill(t("team_threads.files_changed"), { count: (payload.files ?? []).length })}+ </p>}+ {(payload.open ?? []).length > 0 && <div className="mt-2 flex flex-col gap-2">+ <p className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">{t("team_threads.summary.open_points")}</p>+ {(payload.open ?? []).map((point) => <div key={point.member_id}>+ <p className="text-xs font-medium text-foreground">{point.name}</p>+ <ul className="list-disc space-y-0.5 pl-5 text-foreground">+ {point.items.map((item, index) => <li key={index} className="[overflow-wrap:anywhere]">{item}</li>)}+ </ul>+ </div>)}+ </div>}+ </li>;+}++/** A member at work, as a line under the step it works on. */+function WorkingLine({ member, names, over }: { member: TeamMember; names: RoomNames; over: boolean }) {+ const t = useT();+ const status = useMemberStatus(member, over);+ return <li className="flex min-w-0 items-center gap-2.5 px-2 py-1.5 text-sm" data-testid={`team-story-live-${member.member_id}`} role="status">+ <Mark member={member} names={names} />+ <span className="shrink-0 font-medium text-foreground">{member.name}</span>+ {status.tone === "waiting"+ ? <span className="flex min-w-0 items-center gap-1 text-warning"><ShieldAlert aria-hidden className="h-3.5 w-3.5 shrink-0" />{status.text}</span>+ : <span className="flex min-w-0 items-center gap-1.5 text-muted-foreground">+ <span aria-hidden className="team-pulse h-1.5 w-1.5 shrink-0 rounded-full bg-accent" />+ <span className={cn("truncate", status.call && "font-mono text-xs")}>{status.text}</span>+ </span>}+ {status.seconds > 0 && <span className="ml-auto shrink-0 text-xs tabular-nums text-muted-foreground">{clock(status.seconds)}</span>}+ <span className="sr-only">{t("team_threads.member.working")}</span>+ </li>;+}++type Row =+ | { type: "heading"; key: string; text: string; current: boolean }+ | { type: "entry"; key: string; entry: TeamEntry }+ | { type: "user"; key: string; entry: TeamEntry }+ | { type: "notice"; key: string; entry: TeamEntry }+ | { type: "summary"; key: string; entry: TeamEntry }+ | { type: "live"; key: string };++/** The story in reading order, with a heading wherever the step changes. */+export function storyRows(thread: TeamThread, t: (key: string) => string): Row[] {+ const bands = buildBoard(thread).filter((band): band is StepBand => band.type === "step");+ const bandOf = new Map<number, StepBand>();+ for (const band of bands) for (const cell of band.cells) for (const entry of cell.entries) bandOf.set(entry.seq, band);+ const rows: Row[] = [];+ let last: string | null = null;+ for (const entry of thread.entries) {+ const band = bandOf.get(entry.seq);+ if (band) {+ if (band.key !== last) {+ rows.push({ type: "heading", key: `h:${band.key}:${entry.seq}`, text: stepHeading(band, t), current: band.current });+ last = band.key;+ }+ rows.push({ type: "entry", key: `e:${entry.seq}`, entry });+ } else if (entry.kind === "user") rows.push({ type: "user", key: `u:${entry.seq}`, entry });+ else if (entry.kind === "summary") rows.push({ type: "summary", key: `s:${entry.seq}`, entry });+ else rows.push({ type: "notice", key: `n:${entry.seq}`, entry });+ }+ // The step being worked on shows from its first second, before anything is filed in it.+ const current = bands.find((band) => band.current);+ if (current && current.key !== last && thread.state === "running") {+ rows.push({ type: "heading", key: `h:${current.key}:now`, text: stepHeading(current, t), current: true });+ }+ if (thread.state === "running") rows.push({ type: "live", key: "live" });+ return rows;+}++export function TeamStory({ thread, graph, names }: { thread: TeamThread; graph: TeamGraph; names: RoomNames }) {+ const t = useT();+ const [open, setOpen] = useState<Set<number>>(() => new Set());+ const { rootRef, contentRef, atEnd, jumpToEnd, follow, release } = useStickToBottom();+ useLayoutEffect(follow, [follow, thread.entries.length, thread.state]);+ const rows = useMemo(() => storyRows(thread, t), [thread, t]);+ const recipients = useMemo(() => {+ const ids = new Map<number, { from: string; to: string[] }>();+ for (const line of graph.edges) {+ if (line.from === "you") continue;+ for (const exchange of line.exchanges) {+ const found = ids.get(exchange.seq) ?? { from: line.from, to: [] };+ found.to.push(line.to);+ ids.set(exchange.seq, found);+ }+ }+ // What went to every other member reads "everyone", not a list of names.+ const others = (from: string) => thread.members.filter((member) => member.member_id !== from && member.state === "active").length;+ return new Map([...ids].map(([seq, { from, to }]) => [seq,+ to.length > 1 && to.length >= others(from) ? [t("team_threads.room.to_all")] : to.map((id) => names.name(id))]));+ }, [graph.edges, names, thread.members, t]);+ const over = thread.state === "done" || thread.state === "stopped" || thread.state === "failed";+ const working = thread.members.filter((member) => member.state === "active" && (member.working || member.waiting));+ const unresolved = thread.issues.filter((issue) => !issue.resolved).length;+ const toggle = (seq: number) => {+ // The person reads here: the story stops following its newest line.+ release();+ setOpen((current) => {+ const next = new Set(current);+ if (next.has(seq)) next.delete(seq);+ else next.add(seq);+ return next;+ });+ };++ return <div className="relative flex min-h-0 flex-1 flex-col" data-testid="team-story">+ <div ref={rootRef} className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis" role="log" aria-label={t("team_threads.room.story")}>+ <ol ref={contentRef} className="flex flex-col px-3 pb-6 pt-2">+ {rows.map((row) => {+ if (row.type === "heading") {+ return <li key={row.key} className="flex items-center gap-2 px-2 pb-1 pt-4 first:pt-1">+ <span className={cn("font-mono text-[10px] uppercase tracking-[0.14em]", row.current ? "text-accent" : "text-muted-foreground")}>{row.text}</span>+ <span aria-hidden className="h-px flex-1 bg-border" />+ </li>;+ }+ if (row.type === "entry") {+ return <StoryEntry key={row.key} entry={row.entry} names={names} to={recipients.get(row.entry.seq) ?? []}+ open={open.has(row.entry.seq)} onToggle={() => toggle(row.entry.seq)} />;+ }+ if (row.type === "user") {+ return <li key={row.key} className="flex justify-end px-2 py-1.5">+ <div className="max-w-[85%] whitespace-pre-wrap rounded-2xl bg-secondary px-3.5 py-2 text-sm text-foreground [overflow-wrap:anywhere]"+ data-testid="team-entry-user">{row.entry.payload.text}</div>+ </li>;+ }+ if (row.type === "summary") return <Summary key={row.key} entry={row.entry} names={names} />;+ if (row.type === "notice") return <Notice key={row.key} entry={row.entry} names={names} />;+ return working.map((member) => <WorkingLine key={`live:${member.member_id}`} member={member} names={names} over={over} />);+ })}+ {thread.issues.length > 0 && <li className="mt-4" data-testid="team-thread-issues">+ <p className="flex items-center gap-2 px-2 pb-1.5">+ <span className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {fill(t("team_threads.issues.title"), { count: thread.issues.length, open: unresolved })}+ </span>+ <span aria-hidden className="h-px flex-1 bg-border" />+ </p>+ <ul className="flex flex-col gap-1.5 px-2">+ {thread.issues.map((issue, index) => <FindingRow key={`${issue.seq}-${index}`} finding={issue} resolved={issue.resolved}+ by={`${names.name(issue.by)} · ${fill(t(`team_threads.issues.${issue.stage}`), { number: issue.number ?? 0 })}`} />)}+ </ul>+ </li>}+ </ol>+ </div>+ {!atEnd && <ScrollToEndButton onClick={jumpToEnd} testId="team-story-scroll-end" className="top-auto bottom-3" />}+ </div>;+}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.tsxindex 632965eb42..9588a069e2 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,6 +1,6 @@import { useEffect, useMemo, useState } from "react";import { useQueryClient } from "@tanstack/react-query";-import { Loader2, Plus, Send, X } from "lucide-react";+import { ArrowLeft, Loader2, Plus, Send, X } from "lucide-react";import { AgentMark } from "@/components/agentic/AgentMark";import { BrandedSelect } from "@/components/ui/select";import { fill, useT } from "@/i18n";@@ -93,6 +93,11 @@ export function TeamThreadDraft({ project }: { project: IdeProject }) {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">+ {/* 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">+ <ArrowLeft aria-hidden className="h-3.5 w-3.5" />{t("team_threads.draft.cancel")}+ </button><div className="text-center"><h2 className="text-2xl font-normal tracking-tight text-foreground sm:text-3xl">{before}<span className="font-semibold text-foreground-strong">{project.name}</span>{after}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadPlanned.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadPlanned.test.tsxindex 6376acdd52..767fbc89c9 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadPlanned.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadPlanned.test.tsx@@ -5,6 +5,7 @@ import type { IdeProject } from "@/lib/agenticIdeApi";import type { TeamThread } from "@/lib/teamThreadsApi";import { TEAM_DRAFT } from "@/store/ideThreads";import { buildBoard, type StepBand } from "./board";+import { closeAllMemberStreams } from "./memberStreams";import { TeamThreadView } from "./TeamThreadView";vi.mock("@/i18n", async (importOriginal) => ({@@ -30,8 +31,31 @@ class QuietSocket {close() {}}-beforeEach(() => { vi.stubGlobal("WebSocket", QuietSocket); });-afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+/** jsdom lays nothing out; the canvas only needs to be told its size once. */+class StillResizeObserver {+ constructor(private readonly callback: ResizeObserverCallback) {}+ observe(target: Element) {+ this.callback([{ target, contentRect: { width: 1000, height: 600 } } as unknown as ResizeObserverEntry], this as unknown as ResizeObserver);+ }+ unobserve() {}+ disconnect() {}+}++/** The one matrix the canvas reads: its zoom. */+class ScaleMatrix {+ m22: number;+ constructor(transform?: string) {+ const scale = /scale\(([\d.]+)\)/.exec(transform ?? "")?.[1];+ this.m22 = scale ? Number(scale) : 1;+ }+}++beforeEach(() => {+ vi.stubGlobal("WebSocket", QuietSocket);+ vi.stubGlobal("ResizeObserver", StillResizeObserver);+ vi.stubGlobal("DOMMatrixReadOnly", ScaleMatrix);+});+afterEach(() => { cleanup(); closeAllMemberStreams(); vi.unstubAllGlobals(); });const project = { id: "p1", name: "Shop", path: "/work/shop", workspaces: [] } as unknown as IdeProject;@@ -114,54 +138,52 @@ function mount(team: string, data: unknown) {return calls;}-it("lays a planner-and-builder thread out as plan rounds, one band per step and the plan on top", async () => {+it("shows a planner-and-builder team as a room: roles on the canvas, the plan a tab away, the steps in the story", async () => {mount("t1", thread);- // The plan, with each step's state and who holds it.+ // The real canvas: each member with its role, the reviewer at work.+ // The canvas and its graph library load lazily; a busy machine takes a while.+ const canvas = await screen.findByTestId("team-canvas", {}, { timeout: 8000 });+ await waitFor(() => expect(within(canvas).getByTestId("team-node-m1")).toBeTruthy(), { timeout: 8000 });+ expect(within(screen.getByTestId("team-node-m1")).getByTestId("team-role-planner")).toBeTruthy();+ expect(within(screen.getByTestId("team-node-m2")).getByTestId("team-role-builder")).toBeTruthy();+ expect(screen.getByTestId("team-node-m3").dataset.state).toBe("working");+ // (jsdom measures no handles, so the canvas draws no lines here: teamGraph.test.ts covers them.)+ // The rail has the mode's three steps; the header says how far the plan is.+ expect(screen.getByLabelText("team_threads.steps").querySelectorAll("li")).toHaveLength(3);+ expect(screen.getByTestId("team-plan-progress").textContent).toContain('{"done":1,"total":2}');++ // Following the reviewer at work; the plan is a tab of its own.+ expect(await screen.findByTestId("team-chat-m3")).toBeTruthy();+ fireEvent.click(screen.getByTestId("team-plan-progress"));const panel = await screen.findByTestId("team-plan");expect(panel.textContent).toContain('team_threads.plan.title {"version":1}');- expect(panel.textContent).toContain('team_threads.plan.progress {"done":1,"total":2}');- expect(screen.queryByTestId("team-plan-proposed")).toBeNull();expect(screen.getByTestId("team-plan-step-1").dataset.status).toBe("accepted");const second = screen.getByTestId("team-plan-step-2");expect(second.dataset.status).toBe("in_review");expect(second.getAttribute("aria-current")).toBe("step");expect(second.textContent).toContain("Gemini");- expect(second.textContent).toContain("The uploader retries three times");- // Each member says what it does; the rail has the mode's three steps.- expect(within(screen.getByTestId("team-member-m1")).getByTestId("team-role-planner")).toBeTruthy();- expect(within(screen.getByTestId("team-member-m2")).getByTestId("team-role-builder")).toBeTruthy();- expect(screen.getByLabelText("team_threads.steps").querySelectorAll("li")).toHaveLength(3);+ // The story: a heading per step, the unreadable plan said plainly, the blocked step with its reason.+ fireEvent.click(screen.getByTestId("team-tab-story"));+ const story = screen.getByTestId("team-story");+ expect(story.textContent).toContain('team_threads.plan.step {"number":1} · Add the setting');+ expect(story.textContent).toContain("team_threads.plan.unreadable");+ expect(story.textContent).toContain("The reply has no team-plan block.");+ const builds = within(story).getAllByTestId("team-story-step_build");+ expect(builds).toHaveLength(3);+ expect(builds[2].textContent).toContain("No retry hook");+ expect(within(story).getByTestId("team-notice-step_accepted").textContent).toContain('"title":"Add the setting"');+ expect(within(story).getByTestId("team-thread-issues").textContent).toContain('team_threads.issues.step {"number":1}');+ expect(within(story).getByTestId("team-story-live-m3")).toBeTruthy();- // The plan round: the unreadable try and the plan beside its review.- const planning = screen.getByTestId("team-band-planning:1");- expect(within(screen.getByTestId("team-cell-planning:1-m1")).getAllByTestId("team-entry-plan_version")).toHaveLength(2);- expect(planning.textContent).toContain("team_threads.plan.unreadable");- expect(planning.textContent).toContain("The reply has no team-plan block.");- expect(screen.getByTestId("team-cell-planning:1-m3").textContent).toContain("team_threads.vote.agree");-- // A step's band: its builds stacked in the builder's lane, the reviews beside them.- const one = screen.getByTestId("team-band-step:1:1");- expect(one.textContent).toContain("Add the setting");- expect(one.textContent).toContain("team_threads.step_status.accepted");- expect(within(screen.getByTestId("team-cell-step:1:1-m2")).getAllByTestId("team-entry-step_build")).toHaveLength(2);- expect(screen.getByTestId("team-cell-step:1:1-m3").textContent).toContain("No test for the default");- // The current step: blocked, with the builder's reason on the card, and the reviewer live.- const two = screen.getByTestId("team-band-step:1:2");- expect(two.textContent).toContain("team_threads.step_status.in_review");- expect(screen.getByTestId("team-cell-step:1:2-m2").textContent).toContain("team_threads.plan.blocked");- expect(screen.getByTestId("team-cell-step:1:2-m2").textContent).toContain("No retry hook");- expect(await screen.findByTestId("team-live-m3")).toBeTruthy();- expect(screen.getByTestId("team-notice-step_accepted").textContent).toContain('"title":"Add the setting"');- expect(screen.getByTestId("team-thread-issues").textContent).toContain('team_threads.issues.step {"number":1}');-- // The whole plan opens under its band.- fireEvent.click(within(screen.getByTestId("team-cell-planning:1-m1")).getAllByTestId("team-entry-plan_version")[1]);- const plan = within(screen.getByTestId("team-reader")).getByTestId("team-reader-plan");+ // The whole plan unfolds in place.+ const [, readable] = within(story).getAllByTestId("team-story-plan_version");+ fireEvent.click(within(readable).getByRole("button"));+ const plan = within(readable).getByTestId("team-entry-plan");expect(plan.textContent).toContain("Use it in the uploader");expect(plan.textContent).toContain("pytest tests/test_config.py passes");-});+}, 20_000);it("asks the person about a step the reviewer never approves, and can take it as it is", async () => {const stuck: TeamThread = {@@ -174,6 +196,7 @@ it("asks the person about a step the reviewer never approves, and can take it asconst waiting = await screen.findByTestId("team-thread-waiting");expect(waiting.textContent).toContain('team_threads.reason.step_disagreement');expect(waiting.textContent).toContain('"number":2');+ fireEvent.click(screen.getByTestId("team-plan-progress"));expect(screen.getByTestId("team-plan-revision").textContent).toContain("No retry hook");fireEvent.click(screen.getByRole("button", { name: "team_threads.accept_step" }));await waitFor(() => expect(calls.some((call) => call.url === "/api/team-threads/t1/accept" && call.method === "POST")).toBe(true));diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsxindex 8fe3f5fcec..ac0c945e60 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx@@ -5,8 +5,23 @@ import type { IdeProject } from "@/lib/agenticIdeApi";import type { TeamThread } from "@/lib/teamThreadsApi";import { TEAM_DRAFT, useIdeThreadsStore } from "@/store/ideThreads";import { buildBoard, gist, type StepBand } from "./board";+import { closeAllMemberStreams } from "./memberStreams";import { TeamThreadView } from "./TeamThreadView";+// The canvas draws with a graph library that needs a real layout engine; this+// stand-in keeps its contract: a button per node and per line.+vi.mock("./TeamCanvas", () => ({+ default: ({ graph, onOpenNode, onOpenEdge, selectedNode, selectedEdge }: {+ graph: { nodes: { id: string }[]; edges: { id: string; tier: string }[] };+ onOpenNode: (id: string) => void; onOpenEdge: (id: string) => void; selectedNode: string | null; selectedEdge: string | null;+ }) => <div data-testid="team-canvas">+ {graph.nodes.map((node) => <button key={node.id} type="button" data-testid={`team-node-${node.id}`}+ aria-pressed={selectedNode === node.id} onClick={() => onOpenNode(node.id)}>{node.id}</button>)}+ {graph.edges.map((line) => <button key={line.id} type="button" data-testid={`team-edge-${line.id}`} data-tier={line.tier}+ aria-pressed={selectedEdge === line.id} onClick={() => onOpenEdge(line.id)}>{line.id}</button>)}+ </div>,+}));+vi.mock("@/i18n", async (importOriginal) => ({...(await importOriginal<typeof import("@/i18n")>()),useT: () => (key: string) => key,@@ -30,7 +45,7 @@ beforeEach(() => {FakeSocket.instances = [];vi.stubGlobal("WebSocket", FakeSocket);});-afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+afterEach(() => { cleanup(); closeAllMemberStreams(); vi.unstubAllGlobals(); });const project = { id: "p1", name: "Shop", path: "/work/shop", workspaces: [] } as unknown as IdeProject;@@ -99,28 +114,27 @@ function mount(team: string, data: unknown) {return calls;}-it("lays the work out as one board: a lane per member, a band per step", async () => {+it("opens as a room: the team on a canvas, the story beside it, the bounds above", async () => {const calls = mount("t1", thread);expect((await screen.findByTestId("team-thread-state")).textContent).toBe("team_threads.state.needs_input");- // The person's task and the outcome span the board; each step is a band.- expect(screen.getByTestId("team-entry-user").textContent).toBe("Add a retry");- for (const key of ["draft", "converge:1", "build", "review:3"]) expect(screen.getByTestId(`team-band-${key}`)).toBeTruthy();- // Both own plans sit side by side, each in its author's lane, as a gist without Markdown marks.- expect(screen.getByTestId("team-cell-draft-m1").textContent).toContain("Plan · Use backoff with jitter.");- expect(screen.getByTestId("team-cell-draft-m2").textContent).toContain("Retry three times.");- expect(screen.getByTestId("team-cell-draft-m3").textContent).toBe("");- // The plan is in its author's lane, the vote on it in the voter's.- expect(within(screen.getByTestId("team-cell-converge:1-m1")).getByTestId("team-entry-plan")).toBeTruthy();- expect(screen.getByTestId("team-cell-converge:1-m2").textContent).toContain("team_threads.vote.agree");- // A review shows its blocking finding right on the card.- expect(screen.getByTestId("team-cell-review:3-m2").textContent).toContain("Loops forever on a 404");- expect(screen.getByTestId("team-cell-build-m1").textContent).toContain('"count":2');- expect(screen.getByTestId("team-notice-plan_agreed").textContent).toContain('"member":"Claude"');- expect(screen.getByTestId("team-summary-review_disagreement").textContent).toContain("app.py:3: Loops forever on a 404");- expect(screen.getByTestId("team-thread-issues").textContent).toContain("team_threads.issues.open");- // Lanes: who is gone says why; the bounds are in the header.- expect(screen.getByTestId("team-member-m3").getAttribute("title")).toBe("not signed in");+ // Every member and the person are on the canvas, every handoff is a line.+ const canvas = await screen.findByTestId("team-canvas");+ for (const id of ["you", "m1", "m2", "m3"]) expect(within(canvas).getByTestId(`team-node-${id}`)).toBeTruthy();+ expect(within(canvas).getByTestId("team-edge-m2->m1").textContent).toBe("m2->m1");+ // Nobody works: the side column shows the shared story, step by step.+ const story = screen.getByTestId("team-story");+ expect(screen.getByTestId("team-tab-story").getAttribute("aria-selected")).toBe("true");+ expect(within(story).getByTestId("team-entry-user").textContent).toBe("Add a retry");+ expect(within(story).getAllByTestId("team-story-draft").map((row) => row.textContent)).toEqual([+ expect.stringContaining("Plan · Use backoff with jitter."), expect.stringContaining("Retry three times."),+ ]);+ // A contribution says to whom it went; a review shows its blocking finding.+ expect(within(story).getByTestId("team-story-plan").textContent).toContain("→ GPT");+ expect(within(story).getByTestId("team-story-review").textContent).toContain("app.py:3: Loops forever on a 404");+ expect(within(story).getByTestId("team-notice-plan_agreed").textContent).toContain('"member":"Claude"');+ expect(within(story).getByTestId("team-summary-review_disagreement").textContent).toContain("app.py:3: Loops forever on a 404");+ expect(within(story).getByTestId("team-thread-issues").textContent).toContain("team_threads.issues.open");expect(screen.getByTestId("team-thread-usage").textContent).toContain('"minutes":12');expect(screen.getByTestId("team-thread-usage").textContent).toContain('"turns":14');@@ -129,28 +143,23 @@ it("lays the work out as one board: a lane per member, a band per step", async (// The first read asks for everything; nothing was fetched twice.expect(calls.find((call) => call.url.startsWith("/api/team-threads/t1?"))?.url).toBe("/api/team-threads/t1?after=0");expect(screen.getAllByTestId("team-entry-user")).toHaveLength(1);- // Nobody works, so no member's thread is listened to.+ // Nobody works and no chat is open, so no member's thread is listened to.expect(FakeSocket.instances).toHaveLength(0);});-it("opens a whole contribution under its band, without leaving the board", async () => {+it("unfolds a contribution of the story in place", async () => {mount("t1", thread);- const card = within(await screen.findByTestId("team-cell-draft-m1")).getByTestId("team-entry-draft");- expect(screen.queryByTestId("team-reader")).toBeNull();- fireEvent.click(card);- const reader = within(screen.getByTestId("team-band-draft")).getByTestId("team-reader");- expect(within(reader).getByText("backoff").tagName).toBe("STRONG");- expect(reader.textContent).toContain("Claude");- // Another card of the band takes the reader over; the same card closes it.- fireEvent.click(within(screen.getByTestId("team-cell-draft-m2")).getByTestId("team-entry-draft"));- expect(screen.getAllByTestId("team-reader")).toHaveLength(1);- expect(screen.getByTestId("team-reader").textContent).toContain("Retry three times.");- fireEvent.click(within(screen.getByTestId("team-cell-draft-m2")).getByTestId("team-entry-draft"));- expect(screen.queryByTestId("team-reader")).toBeNull();+ const [first] = await screen.findAllByTestId("team-story-draft");+ expect(within(first).queryByTestId("team-entry-body")).toBeNull();+ fireEvent.click(within(first).getByRole("button"));+ const body = within(first).getByTestId("team-entry-body");+ expect(within(body).getByText("backoff").tagName).toBe("STRONG");+ fireEvent.click(within(first).getByRole("button"));+ expect(within(first).queryByTestId("team-entry-body")).toBeNull();});-it("shows a working member's newest steps as they happen", async () => {+it("follows the member at work: its chat streams in beside the canvas over one socket", async () => {const working: TeamThread = {...thread, state: "running", reason: "", phase: "challenge", builder: "", rounds: { plan: 0, review: 0 },members: [member("m1", "Claude", { working: true, since_ms: Date.now() - 65_000 }), member("m2", "GPT")],@@ -159,47 +168,81 @@ it("shows a working member's newest steps as they happen", async () => {};mount("t1", working);- // The step being worked on: one lane is done, the other is live.- expect((await screen.findByTestId("team-cell-challenge-m2")).textContent).toContain("Claude skips the timeout.");- const live = await screen.findByTestId("team-live-m1");- expect(live.textContent).toContain("team_threads.live_starting");- expect(live.textContent).toContain("1:05");- // Only the working member's thread is listened to.+ // Following is on: the working member's chat is open, its node marked.+ const chat = await screen.findByTestId("team-chat-m1");+ expect(screen.getByTestId("team-tab-member:m1").getAttribute("aria-selected")).toBe("true");+ expect(screen.getByTestId("team-node-m1").getAttribute("aria-pressed")).toBe("true");+ // What it works on flows on the canvas: the other member's plan.+ expect(screen.getByTestId("team-edge-m2->m1").dataset.tier).toBe("live");+ // The chat and the member's status share one socket.await waitFor(() => expect(FakeSocket.instances).toHaveLength(1));const socket = FakeSocket.instances[0];expect(socket.url).toContain("/api/agent-chat/sessions/session-m1/ws");+ expect(chat.textContent).toContain("team_threads.live_starting");vi.useFakeTimers();try {act(() => {socket.frame({ type: "snapshot", events: [- { seq: 1, ts_ms: 1, kind: "turn_started", payload: { turn_id: "t", provider: "claude-api", model: "", runner: "claude-cli" } },- { seq: 2, ts_ms: 2, kind: "tool_call", payload: { turn_id: "t", call_id: "c1", name: "Read", input: { file_path: "/work/shop/app.py" } } },+ { seq: 1, ts_ms: 1, kind: "user_message", payload: { text: "Team thread: challenge the other plans\n\nThe plan of GPT", author: { agent_id: "team", name: "Team" } } },+ { seq: 2, ts_ms: 2, kind: "turn_started", payload: { turn_id: "t", provider: "claude-api", model: "", runner: "claude-cli" } },+ { seq: 3, ts_ms: 3, kind: "tool_call", payload: { turn_id: "t", call_id: "c1", name: "Read", input: { file_path: "/work/shop/app.py" } } },] });- socket.frame({ type: "event", event: { seq: 3, ts_ms: 3, kind: "tool_call", payload: { turn_id: "t", call_id: "c2", name: "Bash", input: { command: "pytest -q" } } } });+ socket.frame({ type: "event", event: { seq: 4, ts_ms: 4, kind: "tool_call", payload: { turn_id: "t", call_id: "c2", name: "Bash", input: { command: "pytest -q" } } } });vi.advanceTimersByTime(400);});} finally {vi.useRealTimers();}- expect(live.textContent).not.toContain("team_threads.live_starting");- expect(live.textContent).toContain("app.py");- expect(live.textContent).toContain("pytest -q");+ // The coordinator's brief is folded to its first line; the turn shows its steps.+ expect(within(chat).getByTestId("team-chat-brief").textContent).toContain("Team thread: challenge the other plans");+ expect(chat.textContent).toContain("pytest -q");+ expect(chat.textContent).not.toContain("team_threads.live_starting");+ expect(FakeSocket.instances).toHaveLength(1);// A working thread offers pause and stop, never the waiting banner.expect(screen.getByRole("button", { name: "team_threads.pause" })).toBeTruthy();expect(screen.queryByTestId("team-thread-waiting")).toBeNull();});-it("sends what the person says to the team and opens a member's own thread", async () => {+it("switches chats and exchanges in place, and leaves for a member's full thread only with a way back", async () => {const calls = mount("t1", { ...thread, state: "running", reason: "" });- const field = await screen.findByTestId("team-thread-message");+ // A node opens that member's chat in the side column; nothing navigates.+ fireEvent.click(await screen.findByTestId("team-node-m2"));+ expect(screen.getByTestId("team-chat-m2")).toBeTruthy();+ expect(screen.getByTestId("team-follow").getAttribute("aria-pressed")).toBe("false");+ expect(useIdeThreadsStore.getState().selection.sessionId).not.toBe("session-m2");+ // A line shows what went across it, both ways, the newest open; Escape returns to the chat.+ fireEvent.click(screen.getByTestId("team-edge-m2->m1"));+ const exchange = screen.getByTestId("team-exchange");+ expect(within(exchange).getAllByTestId("team-exchange-item").length).toBeGreaterThan(2);+ expect(within(exchange).getAllByTestId("team-entry-body")).toHaveLength(1);+ expect(exchange.textContent).toContain("Loops forever on a 404");+ fireEvent.keyDown(window, { key: "Escape" });+ expect(screen.queryByTestId("team-exchange")).toBeNull();+ expect(screen.getByTestId("team-chat-m2")).toBeTruthy();+ // Arrow keys walk the tabs.+ fireEvent.keyDown(screen.getByTestId("team-tab-member:m2"), { key: "ArrowLeft" });+ expect(screen.getByTestId("team-chat-m1")).toBeTruthy();++ // The person steps in for the whole team.+ const field = screen.getByTestId("team-thread-message");fireEvent.change(field, { target: { value: "Keep the public API unchanged" } });fireEvent.keyDown(field, { key: "Enter" });await waitFor(() => expect(calls.find((call) => call.url.endsWith("/message"))?.body).toEqual({ text: "Keep the public API unchanged" }));- fireEvent.click(screen.getByTestId("team-member-m1"));- expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "session-m1" });+ // The full thread remembers the team it came from.+ fireEvent.click(screen.getByTestId("team-chat-open-full"));+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "session-m1", fromTeam: "t1" });+});++it("comes back to the chat it left for a member's full thread", async () => {+ mount("t1", { ...thread, state: "running", reason: "" });+ fireEvent.click(await screen.findByTestId("team-node-m2"));+ fireEvent.click(screen.getByTestId("team-chat-open-full"));+ cleanup();+ mount("t1", { ...thread, state: "running", reason: "" });+ expect(await screen.findByTestId("team-chat-m2")).toBeTruthy();});it("starts the suggested team with one prompt", async () => {@@ -221,6 +264,14 @@ it("starts the suggested team with one prompt", async () => {await waitFor(() => expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null, team: "t9" }));});+it("leaves the start form for what was open before it", async () => {+ useIdeThreadsStore.getState().openThread("s1", "p1");+ useIdeThreadsStore.getState().newTeam("p1");+ mount(TEAM_DRAFT, { ...thread, team_id: "t9" });+ fireEvent.click(await screen.findByTestId("team-draft-cancel"));+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s1" });+});+it("derives the board: roles in a step nobody has filed for, rounds as bands of their own", () => {const start: TeamThread = {...thread, state: "running", reason: "", phase: "draft", builder: "", rounds: { plan: 0, review: 0 },diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.tsxindex fe0e11ee59..8c7e9cbfec 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.tsx@@ -1,13 +1,6 @@-import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";-import {- Brain, Check, ChevronDown, ChevronRight, Eye, FileText, FolderOpen, Globe, Hammer, ListChecks, Loader2, MessageSquareText,- Pause, Pencil, Play, Search, Send, ShieldAlert, Square, Terminal, Trash2, Users, Wrench, X,-} from "lucide-react";-import { AgentMark } from "@/components/agentic/AgentMark";-import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";-import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";-import { useStickToBottom } from "@/hooks/useStickToBottom";+import { Check, Loader2, Pause, Play, Send, ShieldAlert, Square, Trash2, X } from "lucide-react";import { fill, useT } from "@/i18n";import type { IdeProject } from "@/lib/agenticIdeApi";import {@@ -21,64 +14,109 @@ import {useTeamSeats,useTeamThread,type TeamCommand,- type TeamEntry,- type TeamFinding,type TeamMember,- type TeamPlan,- type TeamRole,type TeamThread,} from "@/lib/teamThreadsApi";import { cn } from "@/lib/utils";import { useEventStore } from "@/store/events";import { TEAM_DRAFT, useIdeThreadsStore } from "@/store/ideThreads";-import { buildBoard, gist, stepsDone, type BandCell, type StepBand } from "./board";-import { liveLines, liveTokens, useMemberTurn, type LiveLine } from "./memberLive";-import { PlanPanel } from "./PlanPanel";+import { stepsDone } from "./board";+import { buildGraph, withShortNames, YOU } from "./teamGraph";+import { TeamSide, tabKey, type RoomTab } from "./TeamSide";+import type { RoomNames } from "./TeamStory";import { TeamThreadDraft } from "./TeamThreadDraft";-/** The board's width: wide enough for four lanes, never wider than reads well. */-const MEASURE = "mx-auto w-full max-w-6xl";-/** A lane never gets narrower than this; a team too wide for the window scrolls sideways. */-const LANE_MIN = 208;+// The canvas brings its graph library along; it loads with the first team room opened.+const TeamCanvas = lazy(() => import("./TeamCanvas"));-const lanes = (count: number) => ({ gridTemplateColumns: `repeat(${Math.max(1, count)}, minmax(${LANE_MIN}px, 1fr))` });+/** Side by side from this width of the room; stacked below it. */+const SPLIT_MIN = 980;/**- * One team thread as a board: a lane per member, a band per step.+ * One team thread as a room: the team on a canvas, their chats beside it.*- * Everything is on one page. A member whose turn runs shows its newest tool- * calls and words as they happen; a finished contribution is a card with its- * gist, and a click opens the whole text under its band. The models never- * read this page: a coordinator on the server passes contributions between- * them, and this view shows what it filed.+ * The canvas shows who works with whom right now: every member and the+ * person as a node, every handoff as a line labelled with what went across.+ * The side column shows the chats themselves, one tab per member, plus the+ * shared story and (planner and builder) the plan. Everything opens in place;+ * the one action that leaves the room, a member's full thread, leads back.+ * The models never read this page: a coordinator on the server passes+ * contributions between them, and this view shows what it filed.*/export function TeamThreadView({ team, project, onScreen }: { team: string; project: IdeProject; onScreen: boolean }) {if (team === TEAM_DRAFT) return <TeamThreadDraft project={project} />;return <OpenTeamThread teamId={team} project={project} onScreen={onScreen} />;}+/** Which tab each team room showed, so a visit to a member's full thread comes back to it. */+const rememberedTabs = new Map<string, { tab: RoomTab; following: boolean }>();++/** The member the room follows: the one already followed while it still works, else the first that works. */+export function followed(thread: TeamThread, current: RoomTab): RoomTab | null {+ const busy = thread.members.filter((member) => member.state === "active" && (member.working || member.waiting));+ if (current.kind === "member" && busy.some((member) => member.member_id === current.id)) return null;+ if (busy.length) return { kind: "member", id: busy[0].member_id };+ const over = thread.state === "done" || thread.state === "stopped" || thread.state === "failed";+ return over && current.kind !== "story" ? { kind: "story" } : null;+}+function OpenTeamThread({ teamId, project, onScreen }: { teamId: string; project: IdeProject; onScreen: boolean }) {const t = useT();const client = useQueryClient();const pushToast = useEventStore((state) => state.pushToast);const query = useTeamThread(teamId, onScreen);const seats = useTeamSeats(onScreen).data;- const thread = query.data;+ const thread = useMemo(() => (query.data ? withShortNames(query.data) : undefined), [query.data]);const [text, setText] = useState("");const [busy, setBusy] = useState(false);const [confirmDelete, setConfirmDelete] = useState(false);- const { rootRef, contentRef, atEnd, jumpToEnd, follow, release } = useStickToBottom();- useLayoutEffect(follow, [follow, thread?.entries.length, thread?.state]);+ const remembered = rememberedTabs.get(teamId);+ const [tab, setTabState] = useState<RoomTab>(remembered?.tab ?? { kind: "story" });+ const [following, setFollowing] = useState(remembered?.following ?? true);+ const [edge, setEdge] = useState<string | null>(null);+ const [wide, setWide] = useState(true);+ const room = useRef<HTMLDivElement | null>(null);++ useEffect(() => { rememberedTabs.set(teamId, { tab, following }); }, [teamId, tab, following]);- const names = useMemo(- () => new Map((thread?.members ?? []).map((member) => [member.member_id, member.name])),- [thread?.members],- );- const agentOf = useMemo(- () => new Map((seats?.seats ?? []).map((seat) => [seat.provider, seat.agent])),- [seats],- );- const bands = useMemo(() => (thread ? buildBoard(thread) : []), [thread]);+ // The room lays itself out by its own width, not the window's.+ useEffect(() => {+ const box = room.current;+ if (!box || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => setWide(box.clientWidth >= SPLIT_MIN));+ observer.observe(box);+ setWide(box.clientWidth === 0 || box.clientWidth >= SPLIT_MIN);+ return () => observer.disconnect();+ }, [thread !== undefined]);++ const graph = useMemo(() => (thread ? buildGraph(thread) : { nodes: [], edges: [] }), [thread]);+ const agentByProvider = useMemo(() => new Map((seats?.seats ?? []).map((seat) => [seat.provider, seat.agent])), [seats]);+ const members = thread?.members;+ const names = useMemo<RoomNames>(() => {+ const byId = new Map((members ?? []).map((member) => [member.member_id, member]));+ return {+ name: (id) => (id === YOU || id === "user" ? t("team_threads.room.you") : byId.get(id)?.name ?? id),+ agent: (member) => agentByProvider.get(member.provider) ?? "",+ member: (id) => byId.get(id),+ };+ }, [members, agentByProvider, t]);+ const agentOf = useCallback((member: TeamMember) => agentByProvider.get(member.provider) ?? "", [agentByProvider]);++ // While following, the side column shows whoever works right now.+ useEffect(() => {+ if (!thread || !following) return;+ const next = followed(thread, tab);+ if (next && tabKey(next) !== tabKey(tab)) setTabState(next);+ }, [thread, following, tab]);++ const pick = useCallback((next: RoomTab) => {+ setEdge(null);+ setFollowing(false);+ setTabState(next);+ }, []);+ const openNode = useCallback((id: string) => pick(id === YOU ? { kind: "story" } : { kind: "member", id }), [pick]);+ const openEdge = useCallback((id: string) => setEdge((current) => (current === id ? null : id)), []);+ const closeEdge = useCallback(() => setEdge(null), []);const run = async (work: () => Promise<TeamThread | { deleted: boolean }>) => {setBusy(true);@@ -101,7 +139,14 @@ function OpenTeamThread({ teamId, project, onScreen }: { teamId: string; projectif (await run(() => messageTeamThread(teamId, message))) setText("");};const remove = async () => {- if (await run(() => deleteTeamThread(teamId))) useIdeThreadsStore.getState().newThread(project.id);+ if (await run(() => deleteTeamThread(teamId))) {+ rememberedTabs.delete(teamId);+ useIdeThreadsStore.getState().newThread(project.id);+ }+ };+ const openFull = (member: TeamMember) => {+ rememberedTabs.set(teamId, { tab: { kind: "member", id: member.member_id }, following: false });+ useIdeThreadsStore.getState().openMemberThread(member.session_id, project.id, teamId);};if (query.isError && !thread) {@@ -121,58 +166,64 @@ function OpenTeamThread({ teamId, project, onScreen }: { teamId: string; projectconst waiting = thread.state === "needs_input" || thread.state === "paused";const disagreement = thread.state === "needs_input"&& (thread.reason === "plan_disagreement" || thread.reason === "review_disagreement" || thread.reason === "step_disagreement");- const count = thread.members.length;- const planned = thread.mode === "planner_builder";+ const selectedNode = edge ? null : tab.kind === "member" ? tab.id : null;++ const canvas = <Suspense fallback={<div className="flex h-full items-center justify-center" role="status" aria-label={t("team_threads.loading")}>+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />+ </div>}>+ <TeamCanvas thread={thread} graph={graph} agentOf={agentOf} selectedNode={selectedNode} selectedEdge={edge}+ onOpenNode={openNode} onOpenEdge={openEdge} />+ </Suspense>;return <div className="flex h-full min-h-0 flex-col" data-testid="team-thread-view">- <header className="shrink-0 border-b border-border px-5 pb-3 pt-3">- <div className={cn(MEASURE, "flex flex-col gap-3")}>- <div className="flex items-center gap-2">- <Users aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />- <h1 className="min-w-0 flex-1 truncate text-sm font-medium text-foreground" title={thread.title}>{thread.title}</h1>- <StateBadge state={thread.state} />- {thread.state === "running" && <>- <IconButton label={t("team_threads.pause")} onClick={() => command("pause")} disabled={busy}><Pause className="h-3.5 w-3.5" /></IconButton>- <IconButton label={t("team_threads.stop")} onClick={() => command("stop")} disabled={busy}><Square className="h-3.5 w-3.5" /></IconButton>- </>}- {over && (confirmDelete- ? <>- <span className="text-xs text-muted-foreground">{t("team_threads.delete_confirm")}</span>- <IconButton label={t("team_threads.delete")} onClick={() => void remove()} disabled={busy}><Check className="h-3.5 w-3.5" /></IconButton>- <IconButton label={t("ide_threads.cancel_renaming")} onClick={() => setConfirmDelete(false)}><X className="h-3.5 w-3.5" /></IconButton>- </>- : <IconButton label={t("team_threads.delete")} onClick={() => setConfirmDelete(true)}><Trash2 className="h-3.5 w-3.5" /></IconButton>)}+ <header className="shrink-0 border-b border-border px-4 py-2.5">+ <div className="flex min-w-0 items-center gap-3">+ <div className="min-w-0 flex-1">+ <p className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {t(`team_threads.mode.${thread.mode}`)} · {fill(t("team_threads.room.members_count"), { count: thread.members.length })}+ </p>+ <h1 className="truncate text-[15px] font-medium leading-6 text-foreground" title={thread.task}>{thread.title}</h1></div>- <div className="flex flex-wrap items-center gap-x-6 gap-y-2">- <StepRail thread={thread} />- <Meters thread={thread} />- </div>- {planned && <PlanPanel thread={thread} names={names} />}+ <StateLabel state={thread.state} />+ {thread.state === "running" && <>+ <IconButton label={t("team_threads.pause")} onClick={() => command("pause")} disabled={busy}><Pause className="h-3.5 w-3.5" /></IconButton>+ <IconButton label={t("team_threads.stop")} onClick={() => command("stop")} disabled={busy}><Square className="h-3.5 w-3.5" /></IconButton>+ </>}+ {over && (confirmDelete+ ? <span className="flex items-center gap-1">+ <span className="text-xs text-muted-foreground">{t("team_threads.delete_confirm")}</span>+ <IconButton label={t("team_threads.delete")} onClick={() => void remove()} disabled={busy}><Check className="h-3.5 w-3.5" /></IconButton>+ <IconButton label={t("ide_threads.cancel_renaming")} onClick={() => setConfirmDelete(false)}><X className="h-3.5 w-3.5" /></IconButton>+ </span>+ : <IconButton label={t("team_threads.delete")} onClick={() => setConfirmDelete(true)}><Trash2 className="h-3.5 w-3.5" /></IconButton>)}+ </div>+ <div className="mt-2 flex flex-wrap items-center gap-x-6 gap-y-2">+ <StepRail thread={thread} />+ {thread.plan && thread.plan.steps.length > 0 && <button type="button" onClick={() => pick({ kind: "plan" })} data-testid="team-plan-progress"+ className="shrink-0 rounded-md px-1 text-xs tabular-nums text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {fill(t("team_threads.plan.title"), { version: thread.plan.version })} · {fill(t("team_threads.plan.progress"), {+ done: thread.plan.steps.filter((step) => step.status === "accepted").length, total: thread.plan.steps.length,+ })}+ </button>}+ <Meters thread={thread} /></div></header>- <div className="relative flex min-h-0 flex-1 flex-col">- <div ref={rootRef} className="chat-scroller min-h-0 flex-1 overflow-auto px-5 pb-5" role="log" aria-label={thread.title}>- <div ref={contentRef} className={cn(MEASURE, "flex flex-col gap-4")} style={{ minWidth: count * LANE_MIN + (count - 1) * 12 }}>- {/* Who sits in which lane stays in view while the work scrolls under it. */}- <ul className="sticky top-0 z-10 grid gap-3 bg-background pb-2 pt-4" style={lanes(count)} aria-label={t("team_threads.members")}>- {thread.members.map((member) => <LaneHead key={member.member_id} member={member}- agent={agentOf.get(member.provider) ?? ""} builder={!planned && thread.builder === member.member_id} over={over}- onOpen={() => useIdeThreadsStore.getState().openThread(member.session_id, project.id)} />)}- </ul>- {bands.map((band) => band.type === "note"- ? <Note key={band.key} entry={band.entry} names={names} />- : <Band key={band.key} band={band} names={names} plan={thread.plan} onOpen={release} />)}- {thread.issues.length > 0 && <Issues thread={thread} names={names} />}- </div>+ <div ref={room} className={cn("flex min-h-0 flex-1", wide ? "flex-row" : "flex-col")} data-layout={wide ? "split" : "stacked"}>+ <div className={cn("relative min-w-0 bg-background", wide ? "min-h-0 flex-1" : "h-[min(320px,42%)] shrink-0 border-b border-border")}>+ {canvas}+ </div>+ <div className={cn("flex min-h-0 min-w-0 flex-col", wide ? "w-[clamp(380px,44%,640px)] shrink-0 border-l border-border" : "flex-1")}>+ <TeamSide thread={thread} graph={graph} names={names} folder={thread.cwd || project.path}+ tab={tab} onTab={pick} following={following} edge={edge} onCloseEdge={closeEdge} onOpenFull={openFull}+ onFollow={() => { setEdge(null); setFollowing(!following); }} /></div>- {!atEnd && <ScrollToEndButton onClick={jumpToEnd} testId="team-thread-scroll-end" className="top-auto bottom-3" />}</div>- <footer className="shrink-0 px-5 pb-4 pt-2">+ <footer className="shrink-0 border-t border-border px-4 pb-3 pt-2.5"><div className="mx-auto flex w-full max-w-3xl flex-col gap-2">{waiting && <div role="status" data-testid="team-thread-waiting"- className="flex flex-wrap items-center gap-2 rounded-xl border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-foreground">+ className="flex flex-wrap items-center gap-2 border-l-[3px] border-warning py-1 pl-3 text-sm text-foreground"><ShieldAlert aria-hidden className="h-4 w-4 shrink-0 text-warning" /><span className="min-w-0 flex-1">{fill(t(`team_threads.reason.${thread.reason || "user"}`), {@@ -190,11 +241,11 @@ function OpenTeamThread({ teamId, project, onScreen }: { teamId: string; project</TextButton><TextButton onClick={() => command("stop")} disabled={busy}>{t("team_threads.stop")}</TextButton></div>}- {thread.state === "failed" && <p role="alert" className="rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-foreground">+ {thread.state === "failed" && <p role="alert" className="border-l-[3px] border-destructive py-1 pl-3 text-sm text-foreground">{fill(t(`team_threads.reason.${thread.reason || "error"}`), { note: thread.note, rounds: 0 })}</p>}{!over && <form onSubmit={(event) => { event.preventDefault(); void send(); }}- className="flex items-end gap-1 rounded-[24px] border border-border bg-secondary px-2 py-1.5 focus-within:border-border-strong">+ className="flex items-end gap-1 rounded-[20px] border border-border bg-secondary px-2 py-1 focus-within:border-border-strong"><textarea value={text} rows={1} onChange={(event) => setText(event.target.value)}onKeyDown={(event) => {if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {@@ -204,9 +255,9 @@ function OpenTeamThread({ teamId, project, onScreen }: { teamId: string; project}}aria-label={t("team_threads.message")} placeholder={t(disagreement ? "team_threads.message_decide" : "team_threads.message")}data-testid="team-thread-message"- className="max-h-[180px] min-h-8 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm text-foreground outline-none placeholder:text-muted-foreground" />+ className="max-h-[160px] min-h-8 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm text-foreground outline-none placeholder:text-muted-foreground" /><button type="submit" disabled={busy || !text.trim()} aria-label={t("team_threads.send")} title={t("team_threads.send")}- className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground disabled:opacity-40">+ className="mb-0.5 flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground disabled:opacity-40"><Send className="h-3.5 w-3.5" aria-hidden /></button></form>}@@ -217,16 +268,16 @@ function OpenTeamThread({ teamId, project, onScreen }: { teamId: string; project/* ------------------------------------------------------------------ header */-function StateBadge({ state }: { state: TeamThread["state"] }) {+function StateLabel({ state }: { state: TeamThread["state"] }) {const t = useT();return <span data-testid="team-thread-state" className={cn(- "flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-xs",- state === "done" ? "border-success/40 text-success"- : state === "needs_input" || state === "paused" ? "border-warning/40 text-warning"- : state === "failed" ? "border-destructive/40 text-destructive"- : state === "running" ? "border-accent/40 text-accent" : "border-border text-muted-foreground",+ "flex shrink-0 items-center gap-1.5 text-xs font-medium",+ state === "done" ? "text-success"+ : state === "needs_input" || state === "paused" ? "text-warning"+ : state === "failed" ? "text-destructive"+ : state === "running" ? "text-accent" : "text-muted-foreground",)}>- {state === "running" && <Loader2 aria-hidden className="h-3 w-3 animate-spin" />}+ <span aria-hidden className={cn("h-1.5 w-1.5 rounded-full bg-current", state === "running" && "team-pulse")} />{t(`team_threads.state.${state}`)}</span>;}@@ -248,43 +299,43 @@ function TextButton({ onClick, disabled, primary, children }: { onClick: () => v</button>;}-/** The five steps as one line: done, now, still to come. */+/** The steps as one line: done, now, still to come. */function StepRail({ thread }: { thread: TeamThread }) {const t = useT();const done = stepsDone(thread);const active = thread.state === "running";const phases: readonly string[] = thread.mode === "planner_builder" ? PLANNED_PHASES : PEER_PHASES;- return <ol className="flex min-w-0 flex-1 items-center" aria-label={t("team_threads.steps")}>+ return <ol className="flex min-w-0 max-w-[720px] flex-1 items-center gap-1" aria-label={t("team_threads.steps")}>{phases.map((phase, index) => {const isDone = index < done;const now = index === done;- return <li key={phase} aria-current={now ? "step" : undefined} className="flex min-w-0 flex-1 items-center last:flex-none">- <span className={cn(- "flex h-5 w-5 shrink-0 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",- isDone ? "border-success bg-success text-background"+ return <li key={phase} aria-current={now ? "step" : undefined} className="flex min-w-0 flex-1 items-center gap-1.5 last:flex-none">+ <span aria-hidden className={cn(+ "flex h-4 w-4 shrink-0 items-center justify-center rounded-full border text-[9px] font-medium tabular-nums",+ isDone ? "border-foreground/40 bg-foreground/10 text-foreground": now ? "border-accent text-accent" : "border-border text-muted-foreground",now && active && "team-step-now",)}>- {isDone ? <Check aria-hidden className="h-3 w-3" strokeWidth={3} /> : index + 1}+ {isDone ? <Check className="h-2.5 w-2.5" strokeWidth={3} /> : index + 1}</span>- <span className={cn("ml-1.5 truncate text-xs", isDone || now ? "text-foreground" : "text-muted-foreground", now && "font-medium")}>+ <span className={cn("truncate text-xs", now ? "font-medium text-foreground" : isDone ? "text-foreground/80" : "text-muted-foreground")}>{t(`team_threads.phase.${phase}`)}</span>- {index < phases.length - 1 && <span aria-hidden className={cn("mx-2 h-px min-w-3 flex-1", isDone ? "bg-success" : "bg-border")} />}+ {index < phases.length - 1 && <span aria-hidden className={cn("mx-1 h-px min-w-2 flex-1", isDone ? "bg-foreground/30" : "bg-border")} />}</li>;})}</ol>;}-/** Time and turns against their bounds, as two thin bars with their numbers. */+/** Time and turns against their bounds. */function Meters({ thread }: { thread: TeamThread }) {const t = useT();const minutes = Math.floor(thread.usage.elapsed_ms / 60_000);const meter = (value: number, max: number, label: string) => {const share = max > 0 ? Math.min(1, value / max) : 0;return <span className="flex items-center gap-1.5">- <span aria-hidden className="h-1 w-14 overflow-hidden rounded-full bg-secondary">- <span className={cn("block h-full rounded-full", share >= 0.9 ? "bg-warning" : "bg-foreground/50")} style={{ width: `${Math.max(share * 100, value > 0 ? 6 : 0)}%` }} />+ <span aria-hidden className="h-1 w-10 overflow-hidden rounded-full bg-secondary">+ <span className={cn("block h-full rounded-full", share >= 0.9 ? "bg-warning" : "bg-foreground/40")} style={{ width: `${Math.max(share * 100, value > 0 ? 6 : 0)}%` }} /></span><span className="tabular-nums">{label}</span></span>;@@ -298,368 +349,3 @@ function Meters({ thread }: { thread: TeamThread }) {{thread.usage.cost_usd > 0 && <span className="tabular-nums">≈ ${thread.usage.cost_usd.toFixed(2)}</span>}</div>;}--/* ------------------------------------------------------------------- lanes */--function LaneHead({ member, agent, builder, over, onOpen }: { member: TeamMember; agent: string; builder: boolean; over: boolean; onOpen: () => void }) {- const t = useT();- const left = member.state === "left";- const status = left ? t("team_threads.member.left")- : member.waiting ? t("team_threads.member.waiting")- : member.working ? t("team_threads.member.working")- : over ? "" : t("team_threads.member.idle");- return <li className="min-w-0">- <button type="button" onClick={onOpen} data-testid={`team-member-${member.member_id}`}- aria-label={fill(t("team_threads.open_member"), { member: member.name })}- title={left ? member.left_reason : fill(t("team_threads.open_member"), { member: member.name })}- className={cn(- "group flex w-full min-w-0 items-center gap-2.5 rounded-xl border px-3 py-2 text-left transition-colors hover:bg-secondary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- member.working && !left ? "border-accent/50 bg-accent/5" : "border-border bg-card",- left && "opacity-55",- )}>- <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-secondary">- {agent ? <AgentMark agent={agent} label={member.name} variant="plain" size="sm" /> : <Users aria-hidden className="h-4 w-4 text-muted-foreground" />}- </span>- <span className="min-w-0 flex-1">- <span className="flex items-center gap-1.5">- <span className={cn("truncate text-sm font-medium text-foreground", left && "line-through")}>{member.name}</span>- {builder && !left && <Hammer aria-label={t("team_threads.member.builder")} className="h-3 w-3 shrink-0 text-muted-foreground" />}- {member.role && <RoleChip role={member.role} />}- </span>- <span className={cn("flex items-center gap-1.5 truncate text-xs",- member.waiting ? "text-warning" : member.working && !left ? "text-accent" : "text-muted-foreground")}>- {member.waiting ? <ShieldAlert aria-hidden className="h-3 w-3 shrink-0" />- : member.working && !left ? <span aria-hidden className="team-pulse h-1.5 w-1.5 shrink-0 rounded-full bg-accent" /> : null}- <span className="truncate">{[status, member.model].filter(Boolean).join(" · ")}</span>- </span>- </span>- </button>- </li>;-}--/* ------------------------------------------------------------------- bands */--function Band({ band, names, plan, onOpen }: { band: StepBand; names: Map<string, string>; plan: TeamPlan | null; onOpen: () => void }) {- const t = useT();- // The contribution whose whole text is open under this band.- const [reading, setReading] = useState<number | null>(null);- const entries = band.cells.flatMap((cell) => cell.entries);- const open = entries.find((entry) => entry.seq === reading) ?? null;- const filed = band.cells.filter((cell) => cell.entries.length > 0).length;- const part = band.cells.filter((cell) => cell.role !== "none" || cell.entries.length > 0).length;- return <section className="flex flex-col gap-2" data-testid={`team-band-${band.key}`} aria-label={t(`team_threads.phase.${band.step}`)}>- <header className="flex min-w-0 items-center gap-2 text-xs">- <span className={cn("shrink-0 font-medium uppercase tracking-wide", band.current ? "text-foreground" : "text-muted-foreground")}>- {band.step === "step" ? fill(t("team_threads.plan.step"), { number: band.number ?? 0 }) : t(`team_threads.phase.${band.step}`)}- </span>- {band.step === "step" ? <StepBandHead band={band} plan={plan} />- : band.round > 1 && band.step !== "planning" && <span className="rounded-full border border-border px-1.5 py-px text-muted-foreground">{fill(t("team_threads.round"), { round: band.round })}</span>}- <span aria-hidden className="h-px min-w-4 flex-1 bg-border" />- <span className="tabular-nums text-muted-foreground">{fill(t("team_threads.band_count"), { done: filed, total: part })}</span>- </header>- <div className="grid items-start gap-3" style={lanes(band.cells.length)}>- {band.cells.map((cell) => <Cell key={cell.member.member_id} cell={cell} band={band} reading={reading}- onRead={(seq) => {- // The person wants to read here: the board stops following its newest entry.- if (reading !== seq) onOpen();- setReading(reading === seq ? null : seq);- }} />)}- </div>- {open && <Reader entry={open} name={names.get(open.author) ?? open.author} onClose={() => setReading(null)} />}- </section>;-}--function Cell({ cell, band, reading, onRead }: { cell: BandCell; band: StepBand; reading: number | null; onRead: (seq: number) => void }) {- const t = useT();- const empty = cell.entries.length === 0 && !cell.live;- return <div className="flex min-w-0 flex-col gap-2" data-testid={`team-cell-${band.key}-${cell.member.member_id}`}>- {cell.entries.map((entry) => <EntryCard key={entry.seq} entry={entry} open={reading === entry.seq} onRead={() => onRead(entry.seq)} />)}- {cell.live && <LiveCard member={cell.member} />}- {empty && band.current && cell.role !== "none" && <p className="rounded-xl border border-dashed border-border px-3 py-2.5 text-xs text-muted-foreground">- {t(`team_threads.role.${cell.role}`)}- </p>}- </div>;-}--/** A filed contribution at a glance: what it is, how it ended, its first lines. */-function EntryCard({ entry, open, onRead }: { entry: TeamEntry; open: boolean; onRead: () => void }) {- const t = useT();- const payload = entry.payload;- const votes = entry.kind === "vote" || entry.kind === "plan_review";- const reviews = entry.kind === "review" || entry.kind === "step_review";- const unreadable = entry.kind === "plan_version" && payload.valid === false;- const blocked = entry.kind === "step_build" && payload.status === "blocked";- const verdict = votes- ? t(payload.agree ? "team_threads.vote.agree" : "team_threads.vote.object")- : reviews ? t(payload.approve ? "team_threads.review.approve" : "team_threads.review.changes")- : unreadable ? t("team_threads.plan.unreadable")- : entry.kind === "plan_version" ? fill(t("team_threads.plan.version_tag"), { version: payload.version ?? 1 })- : entry.kind === "step_build" ? t(blocked ? "team_threads.plan.blocked" : "team_threads.plan.done") : "";- const positive = votes ? payload.agree : reviews ? payload.approve- : entry.kind === "plan_version" ? !unreadable : entry.kind === "step_build" ? !blocked : undefined;- const points = votes ? payload.objections ?? [] : [];- const findings = payload.findings ?? [];- const files = payload.files ?? [];- const lead = points[0] ?? findings.find((finding) => finding.severity === "blocking")?.issue ?? findings[0]?.issue- ?? (unreadable ? payload.error : blocked ? payload.note- : payload.plan_change ? fill(t("team_threads.plan.plan_change"), { text: payload.plan_change }) : "") ?? "";- const planSteps = entry.kind === "plan_version" ? payload.steps ?? [] : [];- return <button type="button" onClick={onRead} aria-expanded={open} data-testid={`team-entry-${entry.kind}`}- className={cn(- "flex w-full min-w-0 flex-col gap-1.5 rounded-xl border bg-card px-3 py-2.5 text-left transition-colors hover:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- open ? "border-border-strong" : "border-border",- )}>- <span className="flex items-center gap-1.5 text-xs">- <span className="font-medium text-foreground">{t(`team_threads.kind.${entry.kind}`)}</span>- {verdict && <span className={cn("rounded-full border px-1.5 py-px",- positive ? "border-success/40 text-success" : "border-warning/40 text-warning")}>{verdict}</span>}- {entry.kind === "step_build" && entry.round > 1 && <span className="rounded-full border border-border px-1.5 py-px text-muted-foreground">- {fill(t("team_threads.round"), { round: entry.round })}- </span>}- <span className="ml-auto text-muted-foreground">- {open ? <ChevronDown aria-hidden className="h-3.5 w-3.5" /> : <ChevronRight aria-hidden className="h-3.5 w-3.5" />}- </span>- </span>- {lead- ? <span className="line-clamp-3 text-xs text-foreground [overflow-wrap:anywhere]">{lead}</span>- : <span className="line-clamp-4 text-xs leading-relaxed text-muted-foreground [overflow-wrap:anywhere]">{gist(payload.text ?? "") || t("team_threads.no_report")}</span>}- {(files.length > 0 || findings.length > 1 || points.length > 1 || planSteps.length > 0) && <span className="flex flex-wrap gap-x-3 text-[11px] text-muted-foreground">- {planSteps.length > 0 && <span>{fill(t("team_threads.plan.steps_count"), { count: planSteps.length })}</span>}- {files.length > 0 && <span title={payload.stat}>{fill(t("team_threads.files_changed"), { count: files.length })}</span>}- {findings.length > 1 && <span>{fill(t("team_threads.findings_count"), { count: findings.length })}</span>}- {points.length > 1 && <span>{fill(t("team_threads.objections_count"), { count: points.length })}</span>}- </span>}- </button>;-}--/** The whole contribution, opened under its band: nothing to navigate to. */-function Reader({ entry, name, onClose }: { entry: TeamEntry; name: string; onClose: () => void }) {- const t = useT();- const payload = entry.payload;- const points = entry.kind === "vote" || entry.kind === "plan_review" ? payload.objections ?? [] : [];- const box = useRef<HTMLElement | null>(null);- // Reading starts at the top: the board follows its newest entry, and a long- // text opened at the end of the page would otherwise show its last lines.- useEffect(() => {- box.current?.scrollIntoView?.({ block: "start" });- }, [entry.seq]);- return <article ref={box} className="scroll-mt-20 rounded-xl border border-border-strong bg-card" data-testid="team-reader">- <header className="flex items-center gap-2 border-b border-border px-4 py-2 text-xs">- <span className="font-medium text-foreground">{name}</span>- <span className="text-muted-foreground">{t(`team_threads.kind.${entry.kind}`)}</span>- <button type="button" onClick={onClose} aria-label={t("team_threads.close_reader")} title={t("team_threads.close_reader")}- className="ml-auto rounded-md p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <X className="h-3.5 w-3.5" />- </button>- </header>- <div className="mx-auto max-w-3xl px-4 py-3">- {payload.text ? <ChatMarkdown text={payload.text} /> : <p className="text-sm text-muted-foreground">{t("team_threads.no_report")}</p>}- {points.length > 0 && <ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-foreground">- {points.map((point, index) => <li key={index}>{point}</li>)}- </ul>}- {entry.kind === "plan_version" && payload.valid === false && payload.error && <p className="mt-2 text-sm text-warning">{payload.error}</p>}- {(payload.steps ?? []).length > 0 && <ol className="mt-3 flex flex-col gap-1.5" data-testid="team-reader-plan">- {(payload.steps ?? []).map((step, index) => <li key={index} className="rounded-lg border border-border px-3 py-2 text-sm">- <p className="font-medium text-foreground"><span className="mr-1.5 tabular-nums text-muted-foreground">{index + 1}</span>{step.title}</p>- {step.goal && <p className="mt-0.5 text-foreground/80 [overflow-wrap:anywhere]">{step.goal}</p>}- <p className="mt-0.5 text-xs text-muted-foreground [overflow-wrap:anywhere]">{t("team_threads.plan.done_when")}: {step.done_when}</p>- </li>)}- </ol>}- {entry.kind === "step_build" && (payload.note || payload.plan_change) && <p className="mt-3 text-sm text-foreground [overflow-wrap:anywhere]">- {[payload.note, payload.plan_change && fill(t("team_threads.plan.plan_change"), { text: payload.plan_change })].filter(Boolean).join(" · ")}- </p>}- {(payload.findings ?? []).length > 0 && <ul className="mt-3 flex flex-col gap-1.5">- {(payload.findings ?? []).map((finding, index) => <FindingRow key={index} finding={finding} />)}- </ul>}- {(payload.files ?? []).length > 0 && <p className="mt-3 font-mono text-xs text-muted-foreground [overflow-wrap:anywhere]">- {(payload.files ?? []).join(" · ")}- </p>}- </div>- </article>;-}--const ROLE_GLYPH: Record<TeamRole, typeof Hammer> = { planner: ListChecks, builder: Hammer, reviewer: Eye };--/** What a member does in the planner-and-builder mode, beside its name. */-function RoleChip({ role }: { role: TeamRole }) {- const t = useT();- const Glyph = ROLE_GLYPH[role];- return <span className="flex shrink-0 items-center gap-1 rounded-full border border-border px-1.5 py-px text-[10px] font-medium text-muted-foreground"- data-testid={`team-role-${role}`}>- <Glyph aria-hidden className="h-2.5 w-2.5" />- {t(`team_threads.member_role.${role}`)}- </span>;-}--/** The band of one plan step: its title, and where it stands in the plan on the board. */-function StepBandHead({ band, plan }: { band: StepBand; plan: TeamPlan | null }) {- const t = useT();- const step = plan && band.version === plan.version ? plan.steps.find((item) => item.number === band.number) : undefined;- return <>- <span className={cn("min-w-0 truncate normal-case", band.current ? "text-foreground" : "text-muted-foreground")} title={band.title}>{band.title}</span>- {step- ? <span className={cn("shrink-0 rounded-full border px-1.5 py-px",- step.status === "accepted" ? (step.open_findings ? "border-warning/40 text-warning" : "border-success/40 text-success")- : step.status === "changes" ? "border-warning/40 text-warning"- : step.status === "open" ? "border-border text-muted-foreground" : "border-accent/40 text-accent")}>- {t(`team_threads.step_status.${step.status}`)}- </span>- : plan && band.version ? <span className="shrink-0 rounded-full border border-border px-1.5 py-px text-muted-foreground">- {fill(t("team_threads.plan.version_tag"), { version: band.version })}- </span> : null}- </>;-}--/* -------------------------------------------------------------------- live */--const CALL_GLYPH: Record<string, typeof Terminal> = {- command: Terminal, read: FileText, list: FolderOpen, search: Search, edit: Pencil, write: Pencil, web: Globe,-};--function useSeconds(sinceMs: number): number {- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- const timer = window.setInterval(() => setNow(Date.now()), 1000);- return () => window.clearInterval(timer);- }, []);- return sinceMs > 0 ? Math.max(0, Math.floor((now - sinceMs) / 1000)) : 0;-}--const clock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;--/** A member at work: its newest steps as they happen, in a few lines. */-function LiveCard({ member }: { member: TeamMember }) {- const t = useT();- const turn = useMemberTurn(member.session_id, true);- const seconds = useSeconds(member.since_ms);- const lang = t("trace_report.locale");- const lines = useMemo(() => liveLines(turn, { t, lang, max: 6 }), [turn, t, lang]);- const tokens = liveTokens(turn);- return <div role="status" data-testid={`team-live-${member.member_id}`}- className={cn("team-live flex min-w-0 flex-col gap-1.5 overflow-hidden rounded-xl border bg-card px-3 py-2.5",- member.waiting ? "border-warning/50" : "border-accent/50")}>- <div className="flex items-center gap-1.5 text-xs">- {member.waiting- ? <><ShieldAlert aria-hidden className="h-3.5 w-3.5 text-warning" /><span className="font-medium text-warning">{t("team_threads.member.waiting")}</span></>- : <><span aria-hidden className="team-pulse h-1.5 w-1.5 rounded-full bg-accent" /><span className="font-medium text-accent">{t("team_threads.member.working")}</span></>}- <span className="ml-auto tabular-nums text-muted-foreground">- {tokens > 0 ? `${fill(t("team_threads.live_tokens"), { count: tokens.toLocaleString() })} · ` : ""}{clock(seconds)}- </span>- </div>- {lines.length === 0- ? <p className="text-xs text-muted-foreground">{t("team_threads.live_starting")}</p>- : <ol className="flex flex-col gap-1">- {lines.map((line, index) => <LiveRow key={line.id} line={line} newest={index === lines.length - 1} />)}- </ol>}- </div>;-}--function LiveRow({ line, newest }: { line: LiveLine; newest: boolean }) {- const t = useT();- const Glyph = line.kind === "call" ? CALL_GLYPH[line.call ?? ""] ?? Wrench : line.kind === "thought" ? Brain : MessageSquareText;- return <li className={cn("team-live-line flex min-w-0 items-start gap-1.5 text-xs", newest ? "text-foreground" : "text-muted-foreground")}>- {line.running && line.kind === "call"- ? <Loader2 aria-hidden className="mt-0.5 h-3 w-3 shrink-0 animate-spin" />- : <Glyph aria-hidden className={cn("mt-0.5 h-3 w-3 shrink-0", line.failed && "text-destructive")} />}- <span className={cn("min-w-0 [overflow-wrap:anywhere]", line.kind === "call" ? "truncate font-mono text-[11px]" : "line-clamp-2")}>- {line.text || t("team_threads.live_thinking")}- </span>- </li>;-}--/* ------------------------------------------------------------------- notes */--/** What belongs to nobody's lane: the person's words, a notice, the outcome. */-function Note({ entry, names }: { entry: TeamEntry; names: Map<string, string> }) {- const t = useT();- const payload = entry.payload;- if (entry.kind === "user") {- return <div className="jarvis-chat-tinted jarvis-chat-out max-w-[min(85%,46rem)] self-end whitespace-pre-wrap rounded-[20px] px-4 py-2.5 text-sm [overflow-wrap:anywhere]"- data-testid="team-entry-user">{payload.text}</div>;- }- if (entry.kind === "summary") return <Summary entry={entry} names={names} />;- const code = payload.code ?? "";- return <p className="self-center px-2 text-center text-xs text-muted-foreground" data-testid={`team-notice-${code}`}>- {fill(t(`team_threads.notice.${code}`), {- member: names.get(payload.member_id ?? payload.by ?? "") ?? "",- error: payload.error ?? "", note: payload.note ?? "", rounds: payload.rounds ?? 0,- step: payload.step ? t(`team_threads.kind.${payload.step}`) : "",- files: (payload.files ?? []).join(", "), model: payload.model ?? "",- number: payload.number ?? 0, version: payload.version ?? 0, count: payload.count ?? 0, title: payload.title ?? "",- role: payload.role ? t(`team_threads.member_role.${payload.role}`) : "",- })}- </p>;-}--function FindingRow({ finding, by, resolved }: { finding: TeamFinding; by?: string; resolved?: boolean }) {- const t = useT();- return <li className="rounded-lg border border-border px-3 py-2 text-sm">- <div className="flex flex-wrap items-center gap-1.5 text-xs">- <span className={cn("rounded-full border px-1.5 py-px",- finding.severity === "blocking" ? "border-destructive/40 text-destructive" : "border-border text-muted-foreground")}>- {t(`team_threads.severity.${finding.severity}`)}- </span>- {by && <span className="font-medium text-foreground">{by}</span>}- {finding.where && <code className="font-mono text-muted-foreground [overflow-wrap:anywhere]">{finding.where}</code>}- {resolved !== undefined && <span className={cn("ml-auto", resolved ? "text-success" : "text-warning")}>- {t(resolved ? "team_threads.issues.resolved" : "team_threads.issues.open")}- </span>}- </div>- <p className="mt-1 text-foreground [overflow-wrap:anywhere]">{finding.issue}</p>- {finding.fix && <p className="mt-0.5 text-xs text-muted-foreground [overflow-wrap:anywhere]">{finding.fix}</p>}- </li>;-}--function Summary({ entry, names }: { entry: TeamEntry; names: Map<string, string> }) {- const t = useT();- const payload = entry.payload;- const outcome = payload.outcome ?? "done";- const finished = outcome === "done" || outcome === "accepted_by_user";- return <section data-testid={`team-summary-${outcome}`}- className={cn("rounded-xl border px-4 py-3 text-sm", finished ? "border-success/40 bg-success/10" : "border-warning/40 bg-warning/10")}>- <p className="font-medium text-foreground">- {finished && payload.mode === "planner_builder"- ? fill(t(outcome === "done" ? "team_threads.summary.planned_done" : "team_threads.summary.planned_accepted"), {- count: payload.step_count ?? 0, version: payload.version ?? 1, rounds: payload.step_rounds ?? 0,- findings: payload.finding_count ?? 0, blocking: payload.blocking ?? 0,- })- : finished- ? fill(t(`team_threads.summary.${outcome}`), {- plan: payload.plan_rounds ?? 1, review: payload.review_rounds ?? 1,- count: payload.finding_count ?? 0, blocking: payload.blocking ?? 0,- builder: names.get(payload.builder ?? "") ?? "",- })- : fill(t(`team_threads.reason.${outcome}`), { rounds: payload.rounds ?? 0, note: "", number: payload.number ?? 0 })}- </p>- {finished && (payload.files ?? []).length > 0 && <p className="mt-1 text-xs text-muted-foreground" title={payload.stat}>- {fill(t("team_threads.files_changed"), { count: (payload.files ?? []).length })}- </p>}- {(payload.open ?? []).length > 0 && <div className="mt-2 flex flex-col gap-2">- <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t("team_threads.summary.open_points")}</p>- {(payload.open ?? []).map((point) => <div key={point.member_id}>- <p className="text-xs font-medium text-foreground">{point.name}</p>- <ul className="list-disc space-y-0.5 pl-5 text-foreground">- {point.items.map((item, index) => <li key={index} className="[overflow-wrap:anywhere]">{item}</li>)}- </ul>- </div>)}- </div>}- </section>;-}--/** The record of what the members caught in each other's plan and work. */-function Issues({ thread, names }: { thread: TeamThread; names: Map<string, string> }) {- const t = useT();- const [open, setOpen] = useState(true);- const unresolved = thread.issues.filter((issue) => !issue.resolved).length;- return <section className="mt-1 flex flex-col gap-2" data-testid="team-thread-issues">- <button type="button" aria-expanded={open} onClick={() => setOpen(!open)}- className="flex items-center gap-1.5 self-start rounded-md px-1 text-xs font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- {open ? <ChevronDown aria-hidden className="h-3.5 w-3.5 text-muted-foreground" /> : <ChevronRight aria-hidden className="h-3.5 w-3.5 text-muted-foreground" />}- {fill(t("team_threads.issues.title"), { count: thread.issues.length, open: unresolved })}- </button>- {open && <ul className="grid gap-1.5 md:grid-cols-2">- {thread.issues.map((issue, index) => <FindingRow key={`${issue.seq}-${index}`} finding={issue} resolved={issue.resolved}- by={`${names.get(issue.by) ?? issue.by} · ${fill(t(`team_threads.issues.${issue.stage}`), { number: issue.number ?? 0 })}`} />)}- </ul>}- </section>;-}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberLive.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberLive.tsindex e99f9a146e..064f7f8400 100644--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberLive.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberLive.ts@@ -1,96 +1,19 @@-import { useEffect, useState } from "react";-import { EMPTY_TIMELINE, reduceEvent, reduceEvents, type Timeline, type TurnItem } from "@/components/agentchat/reduce";+import { useEffect, useMemo, useState } from "react";+import type { TurnItem } from "@/components/agentchat/reduce";+import { fill, useT } from "@/i18n";+import type { TeamMember } from "@/lib/teamThreadsApi";import type { Translate } from "@/components/agentchat/traceEntries";-import { agentChatSocketUrl, type AgentChatEvent } from "@/lib/agentChatApi";-import { jitteredDelay, requestConnect } from "@/lib/connectBudget";import { buildThreadRows, thoughtGist } from "../threadWork";+import { runningTurnOf, useMemberTimeline } from "./memberStreams";/**- * What a member is doing right now, read from its own thread's event stream.- *- * A member of a team thread is an ordinary thread session, so its tool calls- * and its text arrive on that session's socket as they happen. The board- * listens only while the member's turn runs and shows the newest steps; the- * whole conversation stays one click away in the member's thread.+ * What a member is doing right now, in a few lines: its newest tool calls and+ * words, read from its own thread's stream (`memberStreams`).*/-const RECONNECT_MS = 1500;-const RECONNECT_MAX_MS = 20_000;-/** Text streams in many small events; the board repaints at most this often. */-const PAINT_MS = 200;-/** The turn a member is in, or `null` while it has none running. */export function useMemberTurn(sessionId: string, enabled: boolean): TurnItem | null {- const [turn, setTurn] = useState<TurnItem | null>(null);-- useEffect(() => {- if (!enabled || !sessionId || typeof WebSocket === "undefined") {- setTurn(null);- return;- }- let timeline: Timeline = EMPTY_TIMELINE;- let socket: WebSocket | null = null;- let cancelConnect: (() => void) | null = null;- let paint: ReturnType<typeof setTimeout> | null = null;- let attempt = 0;- let closed = false;-- const publish = () => {- paint = null;- if (closed) return;- const last = [...timeline.items].reverse().find((item): item is TurnItem => item.type === "turn");- setTurn(last && last.status === "running" ? last : null);- };- const schedule = () => {- if (paint === null) paint = setTimeout(publish, PAINT_MS);- };-- const connect = () => {- cancelConnect = null;- if (closed) return;- const afterSeq = timeline.lastSeq;- const ws = new WebSocket(agentChatSocketUrl(sessionId, afterSeq));- socket = ws;- ws.onopen = () => { attempt = 0; };- ws.onmessage = (message) => {- if (socket !== ws) return;- let frame: { type?: string; events?: AgentChatEvent[]; event?: AgentChatEvent };- try {- frame = JSON.parse(String(message.data));- } catch {- return; // not a frame of this protocol- }- if (frame.type === "snapshot") {- // After a reconnect the snapshot only carries what was missed.- timeline = reduceEvents(afterSeq > 0 ? timeline : EMPTY_TIMELINE, frame.events ?? []);- schedule();- } else if (frame.type === "event" && frame.event) {- timeline = reduceEvent(timeline, frame.event);- schedule();- }- };- ws.onclose = () => {- if (socket !== ws || closed) return;- socket = null;- // Jittered, escalating and paid for out of the shared connect budget (AP-33).- attempt += 1;- cancelConnect = requestConnect(connect, jitteredDelay(attempt - 1, RECONNECT_MS, RECONNECT_MAX_MS));- };- ws.onerror = () => { /* onclose follows and schedules the reconnect */ };- };-- cancelConnect = requestConnect(connect, 0);- return () => {- closed = true;- cancelConnect?.();- if (paint !== null) clearTimeout(paint);- const ws = socket;- socket = null;- ws?.close();- };- }, [sessionId, enabled]);-- return turn;+ return runningTurnOf(useMemberTimeline(sessionId, enabled));}/** One line of a member's live feed. */@@ -136,9 +59,46 @@ export function liveLines(turn: TurnItem | null, options: { t: Translate; lang:return lines.slice(-(options.max ?? 6));}-/** Tokens a running turn has produced so far, when its runner reports them. */-export function liveTokens(turn: TurnItem | null): number {- const usage = turn?.liveUsage;- if (!usage) return 0;- return Number(usage.output_tokens ?? usage.output ?? 0) || 0;+function useSeconds(sinceMs: number, on: boolean): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!on) return;+ const timer = window.setInterval(() => setNow(Date.now()), 1000);+ return () => window.clearInterval(timer);+ }, [on]);+ return sinceMs > 0 ? Math.max(0, Math.floor((now - sinceMs) / 1000)) : 0;+}++export const clock = (seconds: number) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;++/** A member's state in one line: what it does right now, or why it does nothing. */+export function useMemberStatus(member: TeamMember, over: boolean) {+ const t = useT();+ const lang = t("trace_report.locale");+ const left = member.state === "left";+ const working = member.working && !left;+ const turn = useMemberTurn(member.session_id, working);+ const seconds = useSeconds(member.since_ms, working);+ const action = useMemo(() => liveLines(turn, { t, lang, max: 1 })[0] ?? null, [turn, t, lang]);+ const doing = action?.kind === "call" ? plainCommand(action.text) : action?.text ?? "";+ const text = left ? (member.left_reason ? fill(t("team_threads.room.left_because"), { reason: member.left_reason }) : t("team_threads.room.left"))+ : member.waiting ? t("team_threads.room.waits")+ : working ? (doing || t(action ? "team_threads.live_thinking" : "team_threads.live_starting"))+ : over ? t("team_threads.room.finished") : t("team_threads.room.idle");+ const tone: "working" | "waiting" | "idle" | "left" = left ? "left" : member.waiting ? "waiting" : working ? "working" : "idle";+ return { text, tone, seconds, call: action?.kind === "call" };+}++/**+ * A shell call without its shell: `"C:\…\powershell.exe" -Command "pytest -q"`+ * reads as `pytest -q`. Anything else comes back as it was.+ */+export function plainCommand(text: string): string {+ const match = /^(?:"[^"]*?|[^"\s]*?)(?:powershell|pwsh|bash|sh|cmd)(?:\.exe)?"?\s+(?:-NoProfile\s+)?(?:-Command|-lc|-c|\/c)\s+([\s\S]+)$/i.exec(text.trim());+ if (!match) return text;+ const inner = match[1].trim();+ const quote = /^["']/.exec(inner)?.[0];+ if (!quote) return inner;+ // A long call is cut short with an ellipsis, so its closing quote may be gone.+ return inner.slice(1).replace(new RegExp(`${quote}(…?)$`), "$1");}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberStreams.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberStreams.tsnew file mode 100644index 0000000000..2e9c6aeaca--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/memberStreams.ts@@ -0,0 +1,149 @@+import { useCallback, useSyncExternalStore } from "react";+import { EMPTY_TIMELINE, reduceEvent, reduceEvents, type Timeline, type TurnItem } from "@/components/agentchat/reduce";+import { agentChatSocketUrl, type AgentChatEvent } from "@/lib/agentChatApi";+import { jitteredDelay, requestConnect } from "@/lib/connectBudget";++/**+ * Each team member's own conversation, read from its thread's event stream.+ *+ * A member is an ordinary thread session, so its turns, tool calls and text+ * arrive on that session's socket as they happen. The team room reads one+ * member from several places at once (its node on the canvas, its chat in the+ * side column), and they all share ONE socket per member: the stream opens+ * with its first reader and closes a moment after its last one leaves, so a+ * tab switch does not reconnect. Every (re)connect is jittered and paid for+ * out of the shared connect budget (AP-33).+ */++const RECONNECT_MS = 1500;+const RECONNECT_MAX_MS = 20_000;+/** Text streams in many small events; readers repaint at most this often. */+const PAINT_MS = 200;+/** How long a stream nobody reads stays open, so switching back does not reconnect. */+const LINGER_MS = 4000;++interface Stream {+ /** What the readers see; replaced at most every PAINT_MS. */+ shown: Timeline;+ readers: Set<() => void>;+ stop: () => void;+ linger: ReturnType<typeof setTimeout> | null;+}++const streams = new Map<string, Stream>();++function open(sessionId: string): Stream {+ let timeline: Timeline = EMPTY_TIMELINE;+ let socket: WebSocket | null = null;+ let cancelConnect: (() => void) | null = null;+ let paint: ReturnType<typeof setTimeout> | null = null;+ let attempt = 0;+ let closed = false;++ const stream: Stream = { shown: EMPTY_TIMELINE, readers: new Set(), stop: () => {}, linger: null };+ const publish = () => {+ paint = null;+ if (closed) return;+ stream.shown = timeline;+ for (const reader of [...stream.readers]) reader();+ };+ const schedule = () => {+ if (paint === null) paint = setTimeout(publish, PAINT_MS);+ };++ const connect = () => {+ cancelConnect = null;+ if (closed) return;+ const afterSeq = timeline.lastSeq;+ const ws = new WebSocket(agentChatSocketUrl(sessionId, afterSeq));+ socket = ws;+ ws.onopen = () => { attempt = 0; };+ ws.onmessage = (message) => {+ if (socket !== ws) return;+ let frame: { type?: string; events?: AgentChatEvent[]; event?: AgentChatEvent };+ try {+ frame = JSON.parse(String(message.data));+ } catch {+ return; // not a frame of this protocol+ }+ if (frame.type === "snapshot") {+ // After a reconnect the snapshot only carries what was missed.+ timeline = reduceEvents(afterSeq > 0 ? timeline : EMPTY_TIMELINE, frame.events ?? []);+ schedule();+ } else if (frame.type === "event" && frame.event) {+ timeline = reduceEvent(timeline, frame.event);+ schedule();+ }+ };+ ws.onclose = () => {+ if (socket !== ws || closed) return;+ socket = null;+ attempt += 1;+ cancelConnect = requestConnect(connect, jitteredDelay(attempt - 1, RECONNECT_MS, RECONNECT_MAX_MS));+ };+ ws.onerror = () => { /* onclose follows and schedules the reconnect */ };+ };++ cancelConnect = requestConnect(connect, 0);+ stream.stop = () => {+ closed = true;+ cancelConnect?.();+ if (paint !== null) clearTimeout(paint);+ const ws = socket;+ socket = null;+ ws?.close();+ };+ return stream;+}++function subscribe(sessionId: string, reader: () => void): () => void {+ let stream = streams.get(sessionId);+ if (!stream) {+ stream = open(sessionId);+ streams.set(sessionId, stream);+ }+ if (stream.linger !== null) {+ clearTimeout(stream.linger);+ stream.linger = null;+ }+ stream.readers.add(reader);+ const mine = stream;+ return () => {+ mine.readers.delete(reader);+ if (mine.readers.size > 0 || mine.linger !== null) return;+ mine.linger = setTimeout(() => {+ mine.linger = null;+ if (mine.readers.size > 0 || streams.get(sessionId) !== mine) return;+ streams.delete(sessionId);+ mine.stop();+ }, LINGER_MS);+ };+}++const noop = () => () => {};++/** A member's whole conversation as it streams in; empty while `enabled` is false. */+export function useMemberTimeline(sessionId: string, enabled: boolean): Timeline {+ const on = enabled && Boolean(sessionId) && typeof WebSocket !== "undefined";+ const listen = useCallback((reader: () => void) => (on ? subscribe(sessionId, reader) : noop()), [sessionId, on]);+ const read = useCallback(() => (on ? streams.get(sessionId)?.shown ?? EMPTY_TIMELINE : EMPTY_TIMELINE), [sessionId, on]);+ return useSyncExternalStore(listen, read, read);+}++/** The turn a member is in, or `null` while it has none running. */+export function runningTurnOf(timeline: Timeline): TurnItem | null {+ for (let index = timeline.items.length - 1; index >= 0; index -= 1) {+ const item = timeline.items[index];+ if (item.type === "turn") return item.status === "running" ? item : null;+ }+ return null;+}++/** For tests: drop every open stream at once. */+export function closeAllMemberStreams(): void {+ for (const stream of streams.values()) {+ if (stream.linger !== null) clearTimeout(stream.linger);+ stream.stop();+ }+ streams.clear();+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/roomStyle.ts b/jarvis/ui/web/frontend/src/components/agentic/threads/team/roomStyle.tsnew file mode 100644index 0000000000..daa58a5516--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/roomStyle.ts@@ -0,0 +1,12 @@+import { cn } from "@/lib/utils";++/** Reading text in the team room's side column: the thread's prose, a size smaller. */+export const PROSE_COMPACT = cn(+ "prose prose-neutral max-w-none text-sm leading-6 text-foreground dark:prose-invert dark:text-foreground [overflow-wrap:anywhere]",+ "[&>div>:first-child]:mt-0 [&>div>:last-child]:mb-0",+ "prose-p:my-1.5 prose-p:text-foreground prose-li:text-foreground prose-strong:text-foreground-strong",+ "prose-headings:mb-1 prose-headings:mt-3 prose-headings:text-sm prose-headings:font-semibold prose-headings:text-foreground-strong",+ "prose-code:rounded prose-code:bg-secondary prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[12px] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",+ "prose-pre:my-2 prose-pre:rounded-md prose-pre:border prose-pre:border-border prose-pre:bg-card prose-pre:text-xs",+ "prose-li:my-0.5 prose-ul:my-1.5 prose-ol:my-1.5 prose-ul:pl-5 prose-ol:pl-5",+);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.tsnew file mode 100644index 0000000000..25ace1a960--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.test.ts@@ -0,0 +1,193 @@+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";++type Member = TeamThread["members"][number];+const member = (id: string, name: string, extra: Partial<Member> = {}): Member => ({+ member_id: id, name, provider: name.toLowerCase(), model: "", effort: "", family: name.toLowerCase(),+ session_id: `session-${id}`, state: "active", left_reason: "", working: false, since_ms: 0, waiting: false, role: "",+ ...extra,+});++const entry = (seq: number, kind: string, author: string, payload: object, phase: string, round = 0) =>+ ({ seq, ts_ms: seq, kind, author, phase, round, payload }) as TeamThread["entries"][number];++const base: TeamThread = {+ team_id: "t1", title: "Add a retry", task: "Add a retry", cwd: "/work", mode: "peers", plan: null,+ state: "running", phase: "draft", reason: "", note: "",+ limits: { max_minutes: 90, max_turns: 40, plan_rounds: 3, review_rounds: 3, turn_minutes: 30, max_cost_usd: 0 },+ usage: { elapsed_ms: 0, turns: 0, cost_usd: 0, cost_partial: false },+ rounds: { plan: 0, review: 0 }, builder: "",+ members: [member("m1", "Claude"), member("m2", "GPT"), member("m3", "Gemini")],+ entries: [], issues: [], created_ms: 1, updated_ms: 1,+};++/** The lines as `from->to: kinds (tier)`, sorted, for a readable comparison. */+const lines = (graph: TeamGraph) => graph.edges+ .map((line) => `${line.id}: ${line.exchanges.map((item) => item.kind).join(",")} (${line.tier})`)+ .sort();++const t = (key: string) => key;++/** A peers thread through a whole run: own plans, challenge, a master plan, a build and one review round. */+const peers: TeamThread = {+ ...base, phase: "review", builder: "m1", rounds: { plan: 1, review: 1 },+ entries: [+ entry(1, "user", "user", { text: "Add a retry" }, "draft"),+ entry(2, "draft", "m1", { text: "A" }, "draft"),+ entry(3, "draft", "m2", { text: "B" }, "draft"),+ entry(4, "draft", "m3", { text: "C" }, "draft"),+ entry(5, "critique", "m2", { text: "x" }, "challenge"),+ entry(6, "critique", "m3", { text: "y" }, "challenge"),+ entry(7, "critique", "m1", { text: "z" }, "challenge"),+ entry(8, "plan", "m1", { text: "The plan" }, "converge", 1),+ entry(9, "vote", "m2", { agree: true, objections: [], plan_seq: 8 }, "converge", 1),+ entry(10, "vote", "m3", { agree: false, objections: ["No tests", "No timeout"], plan_seq: 8 }, "converge", 1),+ entry(11, "build", "m1", { text: "Built", files: ["app.py", "test_app.py"] }, "build"),+ entry(12, "review", "m2", { approve: true, findings: [] }, "review", 1),+ ],+};++describe("the team graph", () => {+ it("draws every handoff of the peers mode as a line from who sent it to who read it", () => {+ const graph = buildGraph({ ...peers, members: [member("m1", "Claude"), member("m2", "GPT"), member("m3", "Gemini", { working: true })] });+ expect(lines(graph)).toEqual([+ // A build goes to every reviewer; the reviewer still at work is reading it now.+ "m1->m2: own_plan,master_plan,change (current)",+ "m1->m3: own_plan,master_plan,change (live)",+ // Votes and the review go back to the plan's author and builder.+ "m2->m1: own_plan,critique,vote,review (current)",+ "m2->m3: own_plan (past)",+ "m3->m1: own_plan,critique,vote (past)",+ "m3->m2: own_plan (past)",+ // The task reached everyone; it is an old line by now.+ "you->m1: task (past)",+ "you->m2: task (past)",+ "you->m3: task (past)",+ ]);+ // The nodes: the person, then each member in its place; nothing depends on the entries.+ expect(graph.nodes.map((node) => node.id)).toEqual([YOU, "m1", "m2", "m3"]);+ expect(buildGraph(base).nodes.map((node) => [node.x, node.y])).toEqual(graph.nodes.map((node) => [node.x, node.y]));+ });++ it("marks what a working member works on as live, in every step of the peers mode", () => {+ const working = (id: string) => base.members.map((item) => (item.member_id === id ? { ...item, working: true } : item));+ const live = (thread: TeamThread) => buildGraph(thread).edges.filter((line) => line.tier === "live").map((line) => line.id).sort();++ // Own plans: the task.+ expect(live({ ...base, members: working("m2"), entries: peers.entries.slice(0, 1) })).toEqual(["you->m2"]);+ // Challenge: the other members' plans.+ expect(live({ ...base, phase: "challenge", members: working("m3"), entries: peers.entries.slice(0, 4) })).toEqual(["m1->m3", "m2->m3"]);+ // Master plan: its author reads the challenges; a voter reads the plan.+ expect(live({ ...base, phase: "converge", rounds: { plan: 1, review: 0 }, members: working("m1"), entries: peers.entries.slice(0, 7) }))+ .toEqual(["m2->m1", "m3->m1"]);+ expect(live({ ...base, phase: "converge", rounds: { plan: 1, review: 0 }, members: working("m3"), entries: peers.entries.slice(0, 9) }))+ .toEqual(["m1->m3"]);+ // The builder answers the review that asked for changes.+ const changes = entry(13, "review", "m3", { approve: false, findings: [{ severity: "blocking", where: "app.py:3", issue: "Loops", fix: "Stop" }] }, "review", 1);+ expect(live({ ...peers, members: working("m1"), entries: [...peers.entries, changes] })).toEqual(["m3->m1"]);+ // A paused team has nothing in flight.+ expect(live({ ...peers, state: "paused", members: working("m3") })).toEqual([]);+ });++ it("follows the planner-and-builder mode: plan to its readers, steps to the reviewer, a blocked step back to the planner", () => {+ const steps = [{ title: "Setting", goal: "g", done_when: "d" }, { title: "Use it", goal: "g", done_when: "d" }];+ const planned: TeamThread = {+ ...base, mode: "planner_builder", phase: "steps", builder: "m2", rounds: { plan: 1, review: 1, step: 2, plan_round: 1, final: 0 },+ members: [member("m1", "Claude", { role: "planner" }), member("m2", "Codex", { role: "builder", working: true }), member("m3", "Gemini", { role: "reviewer" })],+ entries: [+ entry(1, "user", "user", { text: "Add a retry" }, "planning"),+ entry(2, "plan_version", "m1", { valid: false, error: "no block" }, "planning", 1),+ entry(3, "plan_version", "m1", { valid: true, version: 1, steps }, "planning", 1),+ entry(4, "plan_review", "m3", { agree: true, objections: [], plan_seq: 3, version: 1 }, "planning", 1),+ entry(5, "step_build", "m2", { version: 1, number: 1, title: "Setting", status: "done", files: ["config.py"] }, "steps", 1),+ entry(6, "step_review", "m3", { approve: true, findings: [], version: 1, number: 1 }, "steps", 1),+ entry(7, "step_build", "m2", { version: 1, number: 2, title: "Use it", status: "blocked", note: "No hook" }, "steps", 1),+ entry(8, "step_review", "m3", {+ approve: false, version: 1, number: 2,+ findings: [{ severity: "blocking", where: "a", issue: "b", fix: "c" }, { severity: "minor", where: "", issue: "d", fix: "" }],+ }, "steps", 1),+ ],+ };+ const graph = buildGraph(planned);+ expect(lines(graph)).toEqual([+ // An unreadable plan goes nowhere; the readable one reaches the reviewer and the builder.+ "m1->m2: plan_version (past)",+ "m1->m3: plan_version (past)",+ // The step the builder works on came back with findings: that line is live.+ "m2->m1: plan_change (current)",+ "m2->m3: step,step (current)",+ "m3->m1: plan_review (past)",+ "m3->m2: step_review,step_review (live)",+ "you->m1: task (past)",+ "you->m2: task (past)",+ "you->m3: task (past)",+ ]);+ const labels = graph.edges.map((line) => [line.id, exchangeLabel(latestExchange(line)!, t, "en")]);+ expect(Object.fromEntries(labels)).toMatchObject({+ "m1->m2": "team_threads.plan.version_tag",+ "m2->m3": "team_threads.plan.step · team_threads.plan.blocked",+ "m3->m2": "team_threads.plan.step · team_threads.graph.findings_other · team_threads.graph.blocking_one",+ "m2->m1": "team_threads.graph.plan_change",+ });+ // Both ways between two members, in order, for the exchange view.+ expect(exchangesBetween(graph, "m2", "m3").map((item) => [item.seq, item.from])).toEqual([[5, "m2"], [6, "m3"], [7, "m2"], [8, "m3"]]);++ // Once the review is answered by a new build, the plan step is what the builder reads next.+ const next = { ...planned, rounds: { ...planned.rounds, step: 3 } };+ expect(buildGraph(next).edges.filter((line) => line.tier === "live").map((line) => line.id)).toEqual(["m1->m2"]);+ });++ it("draws both directions as one two-way line where they carried the same", () => {+ const challenge: TeamThread = { ...base, phase: "challenge", members: base.members.slice(0, 2), entries: peers.entries.slice(0, 3) };+ const drawn = canvasLines(buildGraph(challenge));+ // The two own plans crossed: one line both ways, counted once per plan.+ expect(drawn.map((item) => [item.line.id, item.partner?.id ?? null, item.count])).toEqual(+ expect.arrayContaining([["m1->m2", "m2->m1", 2]]),+ );+ // A vote back is not the plan that went out: two lines.+ const voted = canvasLines(buildGraph({ ...peers, phase: "converge", rounds: { plan: 1, review: 0 }, entries: peers.entries.slice(0, 9) }));+ expect(voted.find((item) => item.line.id === "m2->m1")?.partner).toBeNull();+ expect(voted.find((item) => item.line.id === "m1->m2")?.partner).toBeNull();+ });++ it("puts what went across into words", () => {+ const say = (kind: string, payload: object, round = 0) => {+ const graph = buildGraph({ ...base, phase: "done", state: "done", entries: [entry(1, "user", "user", { text: "x" }, "draft"), entry(2, kind, "m1", payload, "review", round)] });+ const line = graph.edges.find((item) => item.from === "m1");+ return line ? exchangeLabel(latestExchange(line)!, t, "en") : "";+ };+ expect(say("plan", { text: "p" }, 2)).toBe("team_threads.graph.master_plan · team_threads.round");+ expect(say("build", { files: ["a.py"] })).toBe("team_threads.graph.change · team_threads.graph.files_one");+ expect(say("draft", { text: "d" })).toBe("team_threads.graph.own_plan");+ });++ it("shows a member that left only on the lines it could still read", () => {+ const left = buildGraph({+ ...base, phase: "challenge",+ members: [member("m1", "Claude"), member("m2", "GPT"), member("m3", "Gemini", { state: "left", left_reason: "not signed in" })],+ entries: [entry(1, "user", "user", { text: "x" }, "draft"), entry(2, "draft", "m1", { text: "a" }, "draft")],+ });+ expect(left.edges.map((line) => line.id).sort()).toEqual(["m1->m2", "you->m1", "you->m2"]);+ });++ it("drops the model from a name unless two members would then be called the same", () => {+ const named = withShortNames({ ...base, members: [+ member("m1", "Anthropic Claude · claude-sonnet-5-5", { model: "claude-sonnet-5-5" }),+ member("m2", "OpenAI Codex · gpt-6-luna", { model: "gpt-6-luna" }),+ member("m3", "Anthropic Claude · claude-haiku-5-5", { model: "claude-haiku-5-5" }),+ ] });+ expect(named.members.map((item) => item.name)).toEqual([+ "Anthropic Claude · claude-sonnet-5-5", "OpenAI Codex", "Anthropic Claude · claude-haiku-5-5",+ ]);+ expect(withShortNames(base)).toBe(base);+ });++ 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");+ expect(plainCommand("git status")).toBe("git status");+ expect(plainCommand(String.raw`"C:\pwsh.exe" -Command "Get-ChildItem -Force; Write-Output …`)).toBe("Get-ChildItem -Force; Write-Output …");+ });+});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.tsnew file mode 100644index 0000000000..b8fd2e58f1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/teamGraph.ts@@ -0,0 +1,391 @@+import type { Translate } from "@/components/agentchat/traceEntries";+import { plural } from "@/components/agentchat/traceEntries";+import { fill } from "@/i18n";+import type { TeamEntry, TeamMember, TeamThread } from "@/lib/teamThreadsApi";+import { buildBoard, type StepBand } from "./board";++/**+ * The team room's canvas as data: who works with whom, and what went across.+ *+ * Every line on the canvas is a real handoff the coordinator made, read from+ * the filed entries: a plan that went to the members who voted on it, a vote+ * back to the plan's author, a change to its reviewers, findings back to the+ * builder, the person's words to every member. One line per direction between+ * two nodes carries all of its exchanges; its label says the newest one.+ *+ * A line is `live` while a member is working on what came across it, `current`+ * 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.+ */++export const YOU = "you";++export type ExchangeKind =+ | "task" | "message" | "own_plan" | "critique" | "master_plan" | "vote" | "change" | "review" | "fix"+ | "plan_version" | "plan_review" | "step" | "step_review" | "plan_change";++export interface Exchange {+ seq: number;+ from: string;+ to: string;+ kind: ExchangeKind;+ entry: TeamEntry;+ /** A verdict reads as agreement (approves, agrees), as an objection, or as neither. */+ tone: "neutral" | "positive" | "negative";+}++export type EdgeTier = "live" | "current" | "past";++export interface GraphEdge {+ id: string;+ from: string;+ to: string;+ /** Oldest first. */+ exchanges: Exchange[];+ tier: EdgeTier;+}++export interface GraphNode {+ id: string;+ kind: "you" | "member";+ member?: TeamMember;+ /** The node's centre on the canvas. */+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface TeamGraph {+ nodes: GraphNode[];+ edges: GraphEdge[];+}++export const MEMBER_NODE = { width: 248, height: 88 } as const;+export const YOU_NODE = { width: 176, height: 48 } as const;++/**+ * Member centres per team size: a pair side by side, three as a triangle, four+ * as a trapezoid whose lower pair sits inside the upper one, so the person's+ * lines to it pass between the upper members rather than through them.+ */+const SPOTS: Record<number, [number, number][]> = {+ 1: [[0, 200]],+ 2: [[-200, 200], [200, 200]],+ 3: [[-230, 190], [230, 190], [0, 410]],+ 4: [[-340, 190], [340, 190], [-170, 430], [170, 430]],+};++export const edgeId = (from: string, to: string) => `${from}->${to}`;++function tone(entry: TeamEntry): Exchange["tone"] {+ const payload = entry.payload;+ if (entry.kind === "vote" || entry.kind === "plan_review") return payload.agree ? "positive" : "negative";+ if (entry.kind === "review" || entry.kind === "step_review") return payload.approve ? "positive" : "negative";+ if (entry.kind === "step_build" && payload.status === "blocked") return "negative";+ return "neutral";+}++export function buildGraph(thread: TeamThread): TeamGraph {+ const members = thread.members;+ const ids = new Set(members.map((member) => member.member_id));+ const entries = thread.entries;+ const edges = new Map<string, GraphEdge>();+ const firstTask = entries.find((entry) => entry.kind === "user");++ // A member that left only counts as a reader of what it could still have read.+ const lastFiled = new Map<string, number>();+ for (const entry of entries) lastFiled.set(entry.author, entry.seq);+ const reads = (member: TeamMember, seq: number) => member.state === "active" || (lastFiled.get(member.member_id) ?? 0) > seq;+ const othersAt = (author: string, seq: number) =>+ members.filter((member) => member.member_id !== author && reads(member, seq)).map((member) => member.member_id);++ const edge = (from: string, to: string): GraphEdge | null => {+ if (from === to || (from !== YOU && !ids.has(from)) || !ids.has(to)) return null;+ const id = edgeId(from, to);+ let found = edges.get(id);+ if (!found) {+ found = { id, from, to, exchanges: [], tier: "past" };+ edges.set(id, found);+ }+ return found;+ };+ const send = (from: string, to: string, kind: ExchangeKind, entry: TeamEntry) => {+ const line = edge(from, to);+ if (line && !line.exchanges.some((item) => item.seq === entry.seq && item.kind === kind)) {+ line.exchanges.push({ seq: entry.seq, from, to, kind, entry, tone: tone(entry) });+ }+ };+ const authorOf = (seq: number | undefined, kind: TeamEntry["kind"], before: number) => {+ const exact = seq ? entries.find((entry) => entry.seq === seq) : undefined;+ return (exact ?? [...entries].reverse().find((entry) => entry.kind === kind && entry.seq < before))?.author;+ };++ const planned = thread.mode === "planner_builder";+ const roleHolders = (role: TeamMember["role"]) =>+ members.filter((member) => member.role === role && member.state === "active").map((member) => member.member_id);+ const planner = roleHolders("planner")[0] ?? members.find((member) => member.role === "planner")?.member_id ?? "";+ const builder = thread.builder || roleHolders("builder")[0] || "";+ const reviewers = roleHolders("reviewer");+ // Without a reviewer the builder reads the plan and the planner checks each step.+ const planReaders = [...new Set([...(reviewers.length ? reviewers : []), builder])].filter(Boolean);+ const stepReaders = reviewers.length ? reviewers : [planner].filter(Boolean);+ const reviewersOf = (round: number, kind: TeamEntry["kind"], fallback: string) => {+ const found = entries.filter((entry) => entry.kind === kind && entry.round === round).map((entry) => entry.author);+ return found.length ? found : othersAt(fallback, 0);+ };++ for (const entry of entries) {+ const from = entry.author;+ const payload = entry.payload;+ switch (entry.kind) {+ case "user":+ for (const to of othersAt(YOU, entry.seq)) send(YOU, to, entry === firstTask ? "task" : "message", entry);+ break;+ case "draft":+ for (const to of othersAt(from, entry.seq)) send(from, to, "own_plan", entry);+ break;+ case "critique": {+ const author = entries.find((item) => item.kind === "plan" && item.round === 1)?.author;+ if (author) send(from, author, "critique", entry);+ break;+ }+ case "plan":+ for (const to of othersAt(from, entry.seq)) send(from, to, "master_plan", entry);+ break;+ case "vote": {+ const author = authorOf(payload.plan_seq, "plan", entry.seq);+ if (author) send(from, author, "vote", entry);+ break;+ }+ case "build":+ for (const to of othersAt(from, entry.seq)) send(from, to, "change", entry);+ break;+ case "review":+ send(from, builder || authorOf(undefined, "build", entry.seq) || "", "review", entry);+ break;+ case "fix":+ for (const to of reviewersOf(entry.round, "review", from)) send(from, to, "fix", entry);+ break;+ case "plan_version":+ if (payload.valid !== false) for (const to of planReaders) send(from, to, "plan_version", entry);+ break;+ case "plan_review": {+ const author = authorOf(payload.plan_seq, "plan_version", entry.seq) ?? planner;+ send(from, author, "plan_review", entry);+ break;+ }+ case "step_build":+ for (const to of stepReaders) send(from, to, "step", entry);+ if ((payload.status === "blocked" || payload.plan_change) && planner && !stepReaders.includes(planner)) {+ send(from, planner, "plan_change", entry);+ }+ break;+ case "step_review":+ send(from, builder, "step_review", entry);+ break;+ default:+ break;+ }+ }++ // What each working member is working on, as the lines it came across.+ const live = new Set<string>();+ const flow = (from: string, to: string, kind?: ExchangeKind, entry?: TeamEntry) => {+ if (kind && entry) send(from, to, kind, entry);+ const line = edges.get(edgeId(from, to));+ if (line && line.exchanges.length) live.add(line.id);+ };+ if (thread.state === "running") {+ for (const member of members) {+ if (!member.working || member.state !== "active") continue;+ const me = member.member_id;+ const lastOf = (kind: TeamEntry["kind"], test: (entry: TeamEntry) => boolean = () => true) =>+ [...entries].reverse().find((entry) => entry.kind === kind && test(entry));+ if (!planned) {+ if (thread.phase === "draft") {+ if (firstTask) flow(YOU, me, "task", firstTask);+ } else if (thread.phase === "challenge") {+ for (const draft of entries.filter((entry) => entry.kind === "draft" && entry.author !== me)) flow(draft.author, me, "own_plan", draft);+ } else if (thread.phase === "converge") {+ const plan = lastOf("plan", (entry) => entry.round === Math.max(1, thread.rounds.plan));+ if (plan && plan.author !== me) flow(plan.author, me);+ else {+ for (const critique of entries.filter((entry) => entry.kind === "critique" && entry.author !== me)) flow(critique.author, me, "critique", critique);+ const earlier = lastOf("plan", (entry) => entry.round === thread.rounds.plan - 1);+ for (const vote of entries.filter((entry) => entry.kind === "vote" && !entry.payload.agree && earlier && entry.payload.plan_seq === earlier.seq)) {+ flow(vote.author, me, "vote", vote);+ }+ }+ } else if (thread.phase === "review") {+ if (me !== builder) flow(builder, me);+ else {+ for (const review of entries.filter((entry) => entry.kind === "review" && entry.round === thread.rounds.review && !entry.payload.approve)) {+ flow(review.author, me);+ }+ }+ }+ continue;+ }+ if (thread.phase === "planning") {+ if (me === planner) {+ const version = lastOf("plan_version", (entry) => entry.payload.valid !== false);+ const since = version?.seq ?? 0;+ const asks = entries.filter((entry) => entry.seq > since && (+ (entry.kind === "plan_review" && !entry.payload.agree)+ || (entry.kind === "step_build" && (entry.payload.status === "blocked" || Boolean(entry.payload.plan_change)))));+ for (const ask of asks) flow(ask.author, me);+ if (!asks.length && firstTask) flow(YOU, me, "task", firstTask);+ } else if (planner) flow(planner, me);+ } else if (thread.phase === "steps") {+ if (me === builder) {+ const number = thread.rounds.step ?? 0;+ const review = lastOf("step_review", (entry) => entry.payload.number === number);+ const build = lastOf("step_build", (entry) => entry.payload.number === number);+ if (review && !review.payload.approve && (!build || review.seq > build.seq)) flow(review.author, me);+ else if (planner) flow(planner, me);+ } else flow(builder, me);+ } else if (thread.phase === "final") {+ if (me === builder) {+ for (const review of entries.filter((entry) => entry.kind === "review" && entry.round === (thread.rounds.final ?? 1) && !entry.payload.approve)) {+ flow(review.author, me);+ }+ } else flow(builder, me);+ }+ }+ }++ // What the step the team is in (or ended in) exchanged.+ const bands = buildBoard(thread).filter((band): band is StepBand => band.type === "step");+ const focus = bands.find((band) => band.current) ?? bands[bands.length - 1];+ const at = focus ? bands.indexOf(focus) : -1;+ // The step the team is in, and the step whose results it works from.+ const focusSeqs = new Set(bands.slice(Math.max(0, at - 1), at + 1)+ .flatMap((band) => band.cells.flatMap((cell) => cell.entries.map((entry) => entry.seq))));+ // The person's words count as current from the start of that earlier step on.+ const earlier = at > 0 ? bands[at - 1].cells.flatMap((cell) => cell.entries.map((entry) => entry.seq)) : [];+ const since = earlier.length ? Math.min(...earlier) : 0;+ for (const line of edges.values()) {+ line.exchanges.sort((left, right) => left.seq - right.seq);+ const latest = line.exchanges[line.exchanges.length - 1];+ line.tier = live.has(line.id) ? "live"+ : latest && (focusSeqs.has(latest.seq) || (line.from === YOU && latest.seq >= since))+ ? "current" : "past";+ }++ const spots = SPOTS[Math.min(4, Math.max(1, members.length))] ?? SPOTS[4];+ const nodes: GraphNode[] = [+ { id: YOU, kind: "you", x: 0, y: 0, ...YOU_NODE },+ ...members.slice(0, 4).map((member, index): GraphNode => ({+ id: member.member_id, kind: "member", member, x: spots[index][0], y: spots[index][1], ...MEMBER_NODE,+ })),+ ];+ return { nodes, edges: [...edges.values()].filter((line) => line.exchanges.length > 0) };+}++const TIER_RANK: Record<EdgeTier, number> = { past: 0, current: 1, live: 2 };++/** What the canvas draws: a line, or both directions of a pair as one. */+export interface CanvasLine {+ /** The line a click opens (its exchange view shows both directions anyway). */+ line: GraphEdge;+ /** The other direction, when this one line stands for both. */+ partner: GraphEdge | null;+ tier: EdgeTier;+ count: number;+}++/**+ * The lines to draw. When both directions between two nodes last carried the+ * same kind of thing at the same moment of the work (everyone sending everyone+ * their own plan), they are one straight two-way line with one label, instead+ * of two bows saying the same twice.+ */+export function canvasLines(graph: TeamGraph): CanvasLine[] {+ const byId = new Map(graph.edges.map((line) => [line.id, line]));+ const out: CanvasLine[] = [];+ const done = new Set<string>();+ for (const line of graph.edges) {+ if (done.has(line.id)) continue;+ done.add(line.id);+ const back = byId.get(edgeId(line.to, line.from));+ const mine = latestExchange(line);+ const theirs = back ? latestExchange(back) : null;+ if (back && mine && theirs && mine.kind === theirs.kind && mine.tone === theirs.tone && line.tier === back.tier) {+ done.add(back.id);+ out.push({ line, partner: back, tier: line.tier, count: line.exchanges.length + back.exchanges.length });+ } else {+ out.push({ line, partner: null, tier: line.tier, count: line.exchanges.length });+ }+ }+ return out.sort((left, right) => TIER_RANK[left.tier] - TIER_RANK[right.tier]);+}++/** The newest exchange of a line, which its label names. */+export const latestExchange = (line: GraphEdge): Exchange | null => line.exchanges[line.exchanges.length - 1] ?? null;++/** Every exchange between two nodes, both ways, oldest first. */+export function exchangesBetween(graph: TeamGraph, one: string, other: string): Exchange[] {+ return graph.edges+ .filter((line) => (line.from === one && line.to === other) || (line.from === other && line.to === one))+ .flatMap((line) => line.exchanges)+ .sort((left, right) => left.seq - right.seq);+}++const counted = (t: Translate, lang: string, key: string, count: number) =>+ fill(t(`team_threads.graph.${key}_${plural(lang, count)}`), { count });++/** What went across, in a few words: "Master plan · round 2", "3 findings · 1 blocking". */+export function exchangeLabel(exchange: Exchange, t: Translate, lang: string): string {+ const payload = exchange.entry.payload;+ const round = exchange.entry.round > 1 ? ` · ${fill(t("team_threads.round"), { round: exchange.entry.round })}` : "";+ const files = (payload.files ?? []).length;+ const withFiles = (text: string) => (files ? `${text} · ${counted(t, lang, "files", files)}` : text);+ const findings = payload.findings ?? [];+ const blocking = findings.filter((finding) => finding.severity === "blocking").length;+ const verdict = (approved: boolean | undefined) => approved+ ? t("team_threads.graph.approves")+ : findings.length+ ? [counted(t, lang, "findings", findings.length), blocking ? counted(t, lang, "blocking", blocking) : ""].filter(Boolean).join(" · ")+ : t("team_threads.graph.changes");+ const step = payload.number ? `${fill(t("team_threads.plan.step"), { number: payload.number })} · ` : "";+ switch (exchange.kind) {+ case "task": return t("team_threads.graph.task");+ case "message": return t("team_threads.graph.message");+ case "own_plan": return t("team_threads.graph.own_plan");+ case "critique": return t("team_threads.graph.critique");+ case "master_plan": return `${t("team_threads.graph.master_plan")}${round}`;+ case "vote":+ case "plan_review": {+ const objections = (payload.objections ?? []).length;+ return payload.agree ? t("team_threads.graph.agrees")+ : objections ? counted(t, lang, "objections", objections) : t("team_threads.graph.objects");+ }+ case "change": return withFiles(t("team_threads.graph.change"));+ case "fix": return withFiles(t("team_threads.graph.fix"));+ case "review": return verdict(payload.approve);+ case "plan_version": return fill(t("team_threads.plan.version_tag"), { version: payload.version ?? 1 });+ case "step": return `${step}${t(payload.status === "blocked" ? "team_threads.plan.blocked" : "team_threads.plan.done")}`;+ case "step_review": return `${step}${verdict(payload.approve)}`;+ case "plan_change": return t("team_threads.graph.plan_change");+ default: return "";+ }+}++/**+ * 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.+ */+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 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] })) };+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex f3977cd6e8..295b72c287 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -9580,7 +9580,6 @@"message": "Eingreifen: Jedes Mitglied liest das mit seinem nächsten Zug","message_decide": "Entscheide die offenen Punkte. Das Team geht mit deiner Antwort in eine weitere Runde","send": "Senden",- "open_member": "Thread von {member} öffnen","round": "Runde {round}","files_changed": "{count} Dateien geändert","state": {@@ -9627,11 +9626,7 @@"minor": "Gering"},"member": {- "working": "arbeitet",- "waiting": "wartet auf dich",- "left": "ausgeschieden",- "builder": "Baut den Plan",- "idle": "wartet"+ "working": "arbeitet"},"reason": {"user": "Du hast diesen Team-Thread pausiert.",@@ -9703,32 +9698,15 @@"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."+ "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"},"meter_time": "{minutes} von {max_minutes} Min.","meter_turns": "{turns} von {max_turns} Zügen",- "band_count": "{done} von {total}","no_report": "Es wurde kein Bericht geschrieben.",- "findings_count": "{count} Befunde",- "objections_count": "{count} Einwände","close_reader": "Schließen",- "live_tokens": "{count} Tokens","live_starting": "Startet…","live_thinking": "Denkt nach",- "role": {- "plans": "Schreibt den eigenen Plan",- "challenges": "Prüft die anderen Pläne",- "author": "Schreibt den Masterplan",- "voter": "Stimmt ab, sobald der Plan da ist",- "builder": "Baut den Plan",- "reviewer": "Prüft, sobald gebaut ist",- "answers": "Antwortet auf das Review",- "writes_plan": "Schreibt den Plan",- "reviews_plan": "Prüft den Plan, sobald er da ist",- "builds_step": "Setzt diesen Schritt um",- "reviews_step": "Prüft, sobald der Schritt umgesetzt ist",- "final_reviewer": "Prüft die gesamte Änderung"- },"accept_step": "Diesen Schritt so übernehmen","mode": {"peers": "Gleichrangig",@@ -9762,6 +9740,53 @@"done": "fertig","plan_change": "Planänderung: {text}","step": "Schritt {number}"+ },+ "room": {+ "back": "Zurück zum Team",+ "back_named": "Zurück zum Team: {title}",+ "you": "Du",+ "needs_you": "braucht dich",+ "left": "Hat das Team verlassen",+ "left_because": "Ausgestiegen: {reason}",+ "waits": "Wartet auf dich",+ "idle": "Wartet, bis es dran ist",+ "finished": "Fertig",+ "canvas": "Wie das Team zusammenarbeitet",+ "exchange_open": "Zeigen, was übergeben wurde: {label}",+ "story": "Verlauf",+ "chats": "Chats",+ "follow": "Folgen",+ "follow_hint": "Zeigt, wer gerade arbeitet",+ "brief": "Vom Team",+ "chat_empty": "{member} war noch nicht dran.",+ "open_full": "Ganzer Thread",+ "answer_in_thread": "Im Thread antworten",+ "exchange_count_one": "{count} Übergabe",+ "exchange_count_other": "{count} Übergaben",+ "members_count": "{count} Mitglieder",+ "to_all": "alle"+ },+ "graph": {+ "task": "Aufgabe",+ "message": "Deine Nachricht",+ "own_plan": "Eigener Plan",+ "critique": "Kritik",+ "master_plan": "Masterplan",+ "agrees": "Stimmt zu",+ "objects": "Widerspricht",+ "change": "Änderung",+ "fix": "Korrektur",+ "approves": "Gibt frei",+ "changes": "Änderungen verlangt",+ "plan_change": "Bittet um Planänderung",+ "files_one": "{count} Datei",+ "files_other": "{count} Dateien",+ "findings_one": "{count} Befund",+ "findings_other": "{count} Befunde",+ "blocking_one": "{count} blockierend",+ "blocking_other": "{count} blockierend",+ "objections_one": "{count} Einwand",+ "objections_other": "{count} Einwände"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 616764c171..fd42c2e1a8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -9580,7 +9580,6 @@"message": "Step in: every member reads this with its next turn","message_decide": "Decide the open points; the team goes one more round with your answer","send": "Send",- "open_member": "Open the thread of {member}","round": "round {round}","files_changed": "{count} files changed","state": {@@ -9627,11 +9626,7 @@"minor": "Minor"},"member": {- "working": "working",- "waiting": "waits for you",- "left": "left",- "builder": "Builds the plan",- "idle": "waiting"+ "working": "working"},"reason": {"user": "You paused this team thread.",@@ -9703,32 +9698,15 @@"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."+ "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"},"meter_time": "{minutes} of {max_minutes} min","meter_turns": "{turns} of {max_turns} turns",- "band_count": "{done} of {total}","no_report": "No report was written.",- "findings_count": "{count} findings",- "objections_count": "{count} objections","close_reader": "Close",- "live_tokens": "{count} tokens","live_starting": "Starting…","live_thinking": "Thinking",- "role": {- "plans": "Writes its own plan",- "challenges": "Challenges the other plans",- "author": "Writes the master plan",- "voter": "Votes once the plan is there",- "builder": "Builds the plan",- "reviewer": "Reviews once the build is there",- "answers": "Answers the review",- "writes_plan": "Writes the plan",- "reviews_plan": "Reviews the plan once it is there",- "builds_step": "Builds this step",- "reviews_step": "Reviews once the step is built",- "final_reviewer": "Reviews the whole change"- },"accept_step": "Accept this step as it is","mode": {"peers": "Peers",@@ -9762,6 +9740,53 @@"done": "done","plan_change": "Plan change: {text}","step": "Step {number}"+ },+ "room": {+ "back": "Back to the team",+ "back_named": "Back to the team: {title}",+ "you": "You",+ "needs_you": "needs you",+ "left": "Left the team",+ "left_because": "Left: {reason}",+ "waits": "Waits for you",+ "idle": "Waiting for its turn",+ "finished": "Finished",+ "canvas": "How the team works together",+ "exchange_open": "Show what went across: {label}",+ "story": "Story",+ "chats": "Chats",+ "follow": "Follow",+ "follow_hint": "Show whoever is working right now",+ "brief": "From the team",+ "chat_empty": "{member} has not had a turn yet.",+ "open_full": "Full thread",+ "answer_in_thread": "Answer in its thread",+ "exchange_count_one": "{count} exchange",+ "exchange_count_other": "{count} exchanges",+ "members_count": "{count} members",+ "to_all": "everyone"+ },+ "graph": {+ "task": "Task",+ "message": "Your message",+ "own_plan": "Own plan",+ "critique": "Critique",+ "master_plan": "Master plan",+ "agrees": "Agrees",+ "objects": "Objects",+ "change": "Change",+ "fix": "Fix",+ "approves": "Approves",+ "changes": "Changes requested",+ "plan_change": "Asks for a plan change",+ "files_one": "{count} file",+ "files_other": "{count} files",+ "findings_one": "{count} finding",+ "findings_other": "{count} findings",+ "blocking_one": "{count} blocking",+ "blocking_other": "{count} blocking",+ "objections_one": "{count} objection",+ "objections_other": "{count} objections"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex b2cfc4f68a..1dd70118d3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -9580,7 +9580,6 @@"message": "Intervenir: cada miembro lo lee en su próximo turno","message_decide": "Decide los puntos abiertos; el equipo hace una ronda más con tu respuesta","send": "Enviar",- "open_member": "Abrir el hilo de {member}","round": "ronda {round}","files_changed": "{count} archivos modificados","state": {@@ -9627,11 +9626,7 @@"minor": "Menor"},"member": {- "working": "trabajando",- "waiting": "te espera",- "left": "salió",- "builder": "Construye el plan",- "idle": "en espera"+ "working": "trabajando"},"reason": {"user": "Has pausado este hilo de equipo.",@@ -9703,32 +9698,15 @@"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."+ "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"},"meter_time": "{minutes} de {max_minutes} min","meter_turns": "{turns} de {max_turns} turnos",- "band_count": "{done} de {total}","no_report": "No se escribió ningún informe.",- "findings_count": "{count} hallazgos",- "objections_count": "{count} objeciones","close_reader": "Cerrar",- "live_tokens": "{count} tokens","live_starting": "Iniciando…","live_thinking": "Pensando",- "role": {- "plans": "Escribe su propio plan",- "challenges": "Contrasta los otros planes",- "author": "Escribe el plan maestro",- "voter": "Vota cuando esté el plan",- "builder": "Construye el plan",- "reviewer": "Revisa cuando esté construido",- "answers": "Responde a la revisión",- "writes_plan": "Escribe el plan",- "reviews_plan": "Revisa el plan cuando esté",- "builds_step": "Construye este paso",- "reviews_step": "Revisa cuando el paso esté construido",- "final_reviewer": "Revisa el cambio completo"- },"accept_step": "Aceptar este paso tal como está","mode": {"peers": "Iguales",@@ -9762,6 +9740,53 @@"done": "hecho","plan_change": "Cambio de plan: {text}","step": "Paso {number}"+ },+ "room": {+ "back": "Volver al equipo",+ "back_named": "Volver al equipo: {title}",+ "you": "Tú",+ "needs_you": "te necesita",+ "left": "Dejó el equipo",+ "left_because": "Salió: {reason}",+ "waits": "Te espera",+ "idle": "Esperando su turno",+ "finished": "Terminado",+ "canvas": "Cómo trabaja el equipo en conjunto",+ "exchange_open": "Ver lo que se pasó: {label}",+ "story": "Historia",+ "chats": "Chats",+ "follow": "Seguir",+ "follow_hint": "Muestra a quien está trabajando ahora",+ "brief": "Del equipo",+ "chat_empty": "{member} aún no ha tenido turno.",+ "open_full": "Hilo completo",+ "answer_in_thread": "Responder en su hilo",+ "exchange_count_one": "{count} intercambio",+ "exchange_count_other": "{count} intercambios",+ "members_count": "{count} miembros",+ "to_all": "todos"+ },+ "graph": {+ "task": "Tarea",+ "message": "Tu mensaje",+ "own_plan": "Plan propio",+ "critique": "Crítica",+ "master_plan": "Plan maestro",+ "agrees": "Está de acuerdo",+ "objects": "Objeta",+ "change": "Cambio",+ "fix": "Corrección",+ "approves": "Aprueba",+ "changes": "Pide cambios",+ "plan_change": "Pide un cambio de plan",+ "files_one": "{count} archivo",+ "files_other": "{count} archivos",+ "findings_one": "{count} hallazgo",+ "findings_other": "{count} hallazgos",+ "blocking_one": "{count} bloqueante",+ "blocking_other": "{count} bloqueantes",+ "objections_one": "{count} objeción",+ "objections_other": "{count} objeciones"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.jsonindex aec3fb6e88..8565c31b92 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json@@ -9580,7 +9580,6 @@"message": "Intervir: cada membro lê isto no seu próximo turno","message_decide": "Decida os pontos em aberto; a equipa faz mais uma ronda com a sua resposta","send": "Enviar",- "open_member": "Abrir o tópico de {member}","round": "ronda {round}","files_changed": "{count} ficheiros alterados","state": {@@ -9627,11 +9626,7 @@"minor": "Menor"},"member": {- "working": "a trabalhar",- "waiting": "à sua espera",- "left": "saiu",- "builder": "Constrói o plano",- "idle": "em espera"+ "working": "a trabalhar"},"reason": {"user": "Pausou este tópico de equipa.",@@ -9703,32 +9698,15 @@"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."+ "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"},"meter_time": "{minutes} de {max_minutes} min","meter_turns": "{turns} de {max_turns} turnos",- "band_count": "{done} de {total}","no_report": "Não foi escrito nenhum relatório.",- "findings_count": "{count} problemas",- "objections_count": "{count} objeções","close_reader": "Fechar",- "live_tokens": "{count} tokens","live_starting": "A iniciar…","live_thinking": "A pensar",- "role": {- "plans": "Escreve o seu próprio plano",- "challenges": "Contrasta os outros planos",- "author": "Escreve o plano principal",- "voter": "Vota quando o plano existir",- "builder": "Constrói o plano",- "reviewer": "Revê quando estiver construído",- "answers": "Responde à revisão",- "writes_plan": "Escreve o plano",- "reviews_plan": "Revê o plano quando existir",- "builds_step": "Constrói este passo",- "reviews_step": "Revê quando o passo estiver construído",- "final_reviewer": "Revê a alteração completa"- },"accept_step": "Aceitar este passo como está","mode": {"peers": "Iguais",@@ -9762,6 +9740,53 @@"done": "feito","plan_change": "Alteração do plano: {text}","step": "Passo {number}"+ },+ "room": {+ "back": "Voltar à equipe",+ "back_named": "Voltar à equipe: {title}",+ "you": "Você",+ "needs_you": "precisa de você",+ "left": "Saiu da equipe",+ "left_because": "Saiu: {reason}",+ "waits": "Aguarda você",+ "idle": "Aguardando a vez",+ "finished": "Concluído",+ "canvas": "Como a equipe trabalha em conjunto",+ "exchange_open": "Ver o que foi passado: {label}",+ "story": "História",+ "chats": "Chats",+ "follow": "Seguir",+ "follow_hint": "Mostra quem está trabalhando agora",+ "brief": "Da equipe",+ "chat_empty": "{member} ainda não teve a vez.",+ "open_full": "Thread completo",+ "answer_in_thread": "Responder no thread",+ "exchange_count_one": "{count} troca",+ "exchange_count_other": "{count} trocas",+ "members_count": "{count} membros",+ "to_all": "todos"+ },+ "graph": {+ "task": "Tarefa",+ "message": "Sua mensagem",+ "own_plan": "Plano próprio",+ "critique": "Crítica",+ "master_plan": "Plano mestre",+ "agrees": "Concorda",+ "objects": "Objeta",+ "change": "Mudança",+ "fix": "Correção",+ "approves": "Aprova",+ "changes": "Pede mudanças",+ "plan_change": "Pede uma mudança no plano",+ "files_one": "{count} arquivo",+ "files_other": "{count} arquivos",+ "findings_one": "{count} achado",+ "findings_other": "{count} achados",+ "blocking_one": "{count} bloqueante",+ "blocking_other": "{count} bloqueantes",+ "objections_one": "{count} objeção",+ "objections_other": "{count} objeções"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 0e29372e23..9e673c757b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -9580,7 +9580,6 @@"message": "介入:每位成员会在下一轮读到这条消息","message_decide": "请对未决事项作出决定;团队将带着你的答复再进行一轮","send": "发送",- "open_member": "打开 {member} 的会话","round": "第 {round} 轮","files_changed": "已更改 {count} 个文件","state": {@@ -9627,11 +9626,7 @@"minor": "次要"},"member": {- "working": "工作中",- "waiting": "等待你",- "left": "已退出",- "builder": "负责实现方案",- "idle": "等待中"+ "working": "工作中"},"reason": {"user": "你已暂停此团队会话。",@@ -9703,32 +9698,15 @@"body_planned": "一位成员撰写由小步骤组成的方案,另一位评审它。实现者一次实现一个步骤,每个步骤都会按其目标检查通过后再开始下一个。受阻的步骤会退回给规划者。你可以随时介入。","role_of": "成员 {number} 的角色","roles_invalid": "请恰好选择一位规划者和一位实现者。",- "bounds_planned": "在 90 分钟、40 轮、三轮方案未达成一致或同一步骤三轮评审后停止并询问你。"+ "bounds_planned": "在 90 分钟、40 轮、三轮方案未达成一致或同一步骤三轮评审后停止并询问你。",+ "cancel": "返回"},"meter_time": "{minutes} / {max_minutes} 分钟","meter_turns": "{turns} / {max_turns} 轮",- "band_count": "{done} / {total}","no_report": "未写报告。",- "findings_count": "{count} 项发现",- "objections_count": "{count} 条异议","close_reader": "关闭",- "live_tokens": "{count} tokens","live_starting": "正在启动…","live_thinking": "思考中",- "role": {- "plans": "撰写自己的方案",- "challenges": "质询其他方案",- "author": "撰写总方案",- "voter": "方案完成后表决",- "builder": "实现方案",- "reviewer": "实现完成后评审",- "answers": "答复评审",- "writes_plan": "撰写方案",- "reviews_plan": "方案完成后评审",- "builds_step": "实现此步骤",- "reviews_step": "步骤实现后评审",- "final_reviewer": "评审整体更改"- },"accept_step": "按现状接受此步骤","mode": {"peers": "平等协作",@@ -9762,6 +9740,53 @@"done": "完成","plan_change": "方案变更:{text}","step": "步骤 {number}"+ },+ "room": {+ "back": "返回团队",+ "back_named": "返回团队:{title}",+ "you": "你",+ "needs_you": "需要你",+ "left": "已离开团队",+ "left_because": "已离开:{reason}",+ "waits": "等待你处理",+ "idle": "等待轮到它",+ "finished": "已完成",+ "canvas": "团队如何协作",+ "exchange_open": "查看传递的内容:{label}",+ "story": "经过",+ "chats": "对话",+ "follow": "跟随",+ "follow_hint": "显示当前正在工作的成员",+ "brief": "来自团队",+ "chat_empty": "{member} 还没有轮到。",+ "open_full": "完整线程",+ "answer_in_thread": "在其线程中回答",+ "exchange_count_one": "{count} 次传递",+ "exchange_count_other": "{count} 次传递",+ "members_count": "{count} 名成员",+ "to_all": "所有人"+ },+ "graph": {+ "task": "任务",+ "message": "你的消息",+ "own_plan": "自己的计划",+ "critique": "评审意见",+ "master_plan": "总计划",+ "agrees": "同意",+ "objects": "反对",+ "change": "改动",+ "fix": "修正",+ "approves": "批准",+ "changes": "要求修改",+ "plan_change": "请求修改计划",+ "files_one": "{count} 个文件",+ "files_other": "{count} 个文件",+ "findings_one": "{count} 个问题",+ "findings_other": "{count} 个问题",+ "blocking_one": "{count} 个阻塞",+ "blocking_other": "{count} 个阻塞",+ "objections_one": "{count} 条异议",+ "objections_other": "{count} 条异议"}}}diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 0ebd636c40..b2a4f00644 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -2998,4 +2998,32 @@ body {0%, 100% { box-shadow: 0 0 0 0 hsl(var(--accent) / 0.45); }50% { box-shadow: 0 0 0 4px hsl(var(--accent) / 0); }}+ /* A canvas line a member is working on right now flows towards it. */+ .team-flow {+ stroke-dasharray: 6 5;+ animation: team-flow 0.9s linear infinite;+ }+ @keyframes team-flow {+ to { stroke-dashoffset: -11; }+ }+ /* The team room's canvas wears the app's theme: its ground, dots and controls. */+ .team-canvas .react-flow {+ --xy-background-color: transparent;+ --xy-background-pattern-dots-color-default: hsl(var(--border-strong) / 0.6);+ --xy-edge-label-background-color: hsl(var(--card));+ --xy-controls-button-background-color: hsl(var(--card));+ --xy-controls-button-background-color-hover: hsl(var(--secondary));+ --xy-controls-button-color: hsl(var(--muted-foreground));+ --xy-controls-button-color-hover: hsl(var(--foreground));+ --xy-controls-button-border-color: hsl(var(--border));+ --xy-controls-box-shadow: none;+ }+ .team-canvas .react-flow__controls {+ border: 1px solid hsl(var(--border));+ border-radius: 6px;+ overflow: hidden;+ }+ .team-canvas .react-flow__node {+ cursor: default;+ }}diff --git a/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts b/jarvis/ui/web/frontend/src/lib/teamThreadsApi.tsindex 0b3d38d899..f43b3d2fd7 100644--- a/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts+++ b/jarvis/ui/web/frontend/src/lib/teamThreadsApi.ts@@ -118,6 +118,8 @@ export interface TeamEntry {/** A vote. */agree?: boolean;objections?: string[];+ /** The plan a vote or a plan review is on, by its entry's seq. */+ plan_seq?: number;/** A review. */approve?: boolean;findings?: TeamFinding[];diff --git a/jarvis/ui/web/frontend/src/store/ideThreads.test.ts b/jarvis/ui/web/frontend/src/store/ideThreads.test.tsindex 348ee0e0ce..1fff694126 100644--- a/jarvis/ui/web/frontend/src/store/ideThreads.test.ts+++ b/jarvis/ui/web/frontend/src/store/ideThreads.test.ts@@ -4,7 +4,29 @@ import { useIdeThreadsStore } from "./ideThreads";describe("ideThreads store", () => {beforeEach(() => {localStorage.clear();- useIdeThreadsStore.setState({ layout: "grid", selection: { projectId: "", sessionId: null }, projectOf: {}, seen: {}, focusNonce: 0 });+ useIdeThreadsStore.setState({ layout: "grid", selection: { projectId: "", sessionId: null }, projectOf: {}, seen: {}, focusNonce: 0, beforeTeamDraft: null });+ });++ it("leaves the team start form for what was open before it", () => {+ const store = useIdeThreadsStore.getState();+ store.openThread("s1", "p1");+ store.newTeam("p1");+ store.newTeam("p1"); // a second click on the people icon keeps the way back+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: null, team: "new" });+ store.cancelTeamDraft();+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s1" });+ // Nothing to cancel once the form is gone.+ store.cancelTeamDraft();+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s1" });+ });++ it("opens a member's own thread with the team it leads back to, across a reload", () => {+ useIdeThreadsStore.getState().openMemberThread("s7", "p1", "t1");+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s7", fromTeam: "t1" });+ expect(JSON.parse(localStorage.getItem("jarvis.agenticIde.threadSelection.v1") ?? "null")).toEqual({ projectId: "p1", sessionId: "s7", fromTeam: "t1" });+ // An ordinary thread opened afterwards carries no way back.+ useIdeThreadsStore.getState().openThread("s8", "p1");+ expect(useIdeThreadsStore.getState().selection).toEqual({ projectId: "p1", sessionId: "s8" });});it("remembers the layout across a reload", () => {diff --git a/jarvis/ui/web/frontend/src/store/ideThreads.ts b/jarvis/ui/web/frontend/src/store/ideThreads.tsindex e431fde893..2d72b2d956 100644--- a/jarvis/ui/web/frontend/src/store/ideThreads.ts+++ b/jarvis/ui/web/frontend/src/store/ideThreads.ts@@ -30,6 +30,11 @@ export interface ThreadSelection {* still picks the members and writes the task. Absent for an ordinary thread.*/team?: string;+ /**+ * A team member's own thread opened from its team: the team it belongs to,+ * so the thread view can lead back to it.+ */+ fromTeam?: string;}/** `ThreadSelection.team` of a team thread that has not started yet. */@@ -77,7 +82,9 @@ const parseSelection = (raw: unknown): ThreadSelection | null => {const sessionId = typeof row.sessionId === "string" && row.sessionId ? row.sessionId : null;// A stored draft is not worth restoring; an open team thread is.const team = typeof row.team === "string" && row.team && row.team !== TEAM_DRAFT ? row.team : undefined;- return team ? { projectId, sessionId: null, team } : { projectId, sessionId };+ if (team) return { projectId, sessionId: null, team };+ const fromTeam = sessionId && typeof row.fromTeam === "string" && row.fromTeam ? row.fromTeam : undefined;+ return fromTeam ? { projectId, sessionId, fromTeam } : { projectId, sessionId };};const parseStringMap = (raw: unknown): Record<string, string> | null => {@@ -128,6 +135,8 @@ interface IdeThreadsState {order: Record<string, string[]>;/** Bumped to ask the thread view to focus its composer. */focusNonce: number;+ /** What was on screen before the team start form opened; its cancel goes back there. */+ beforeTeamDraft: ThreadSelection | null;setLayout: (layout: IdeLayout) => void;/** Open an existing thread. */@@ -138,6 +147,10 @@ interface IdeThreadsState {openTeam: (teamId: string, projectId: string) => void;/** Open the form that starts a team thread in a project. */newTeam: (projectId: string) => void;+ /** Leave the start form for what was on screen before it. */+ cancelTeamDraft: () => void;+ /** Open a team member's own thread, remembering the team to come back to. */+ openMemberThread: (sessionId: string, projectId: string, teamId: string) => void;/** The draft became a session: remember where it belongs and show it. */adoptThread: (sessionId: string, projectId: string) => void;/** A session started in `projectId` while another thread was picked: file it, show nothing new. */@@ -161,6 +174,7 @@ export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({archived: read(ARCHIVED_KEY, parseNumberMap, {}),order: read(ORDER_KEY, parseOrder, {}),focusNonce: 0,+ beforeTeamDraft: null,setLayout: (layout) => {if (get().layout === layout) return;@@ -184,7 +198,21 @@ export const useIdeThreadsStore = create<IdeThreadsState>((set, get) => ({},newTeam: (projectId) => {const selection = { projectId, sessionId: null, team: TEAM_DRAFT };- set((state) => ({ selection, focusNonce: state.focusNonce + 1 }));+ const current = get().selection;+ const beforeTeamDraft = current.team === TEAM_DRAFT ? get().beforeTeamDraft : current;+ set((state) => ({ selection, beforeTeamDraft, focusNonce: state.focusNonce + 1 }));+ },+ cancelTeamDraft: () => {+ if (get().selection.team !== TEAM_DRAFT) return;+ const back = get().beforeTeamDraft;+ const selection = back ?? { projectId: get().selection.projectId, sessionId: null };+ write(SELECTION_KEY, selection);+ set({ selection, beforeTeamDraft: null });+ },+ openMemberThread: (sessionId, projectId, teamId) => {+ const selection = { projectId, sessionId, fromTeam: teamId };+ write(SELECTION_KEY, selection);+ set({ selection });},adoptThread: (sessionId, projectId) => {const selection = { projectId, sessionId };