Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): enable local drag teams and split chats
rubenluetke10-beep5c28af98357e
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 4d69d80280..42f2482e2b 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -479,8 +479,11 @@ implementations, not stubs.| Data / agents (wiki, contacts, telephony, sessions, missions, skills, self-mod, channels, MCP) | Clean; mission workers run on POSIX with a real process-group reaper || Agent society hands (own shell, browser via browser-use, learned skills) | Shell: local subprocess in the agent's workspace on every OS (Git Bash/PowerShell/bash/sh pick as the chat's folder tools), no container by decision. Browser: browser-use lives in a managed venv under the data dir (its pins collide with the app's), installed on demand — `uv`/`venv`, a 3.11–3.13 interpreter preferred, Chromium downloaded once; headless runs need no display, so a headless Linux box runs agents' browsers; the headed login session needs a display (409 without one is the follow-up); attach mode needs a running Chrome with `--remote-debugging-port`. Learning is pure files + the brain, OS-neutral || Agent society substrate (roster, typed board, scheduler, rooms, mission bridge, `/api/society`) | Clean; pure asyncio + SQLite (`data/society.db`, WAL) and FastAPI, no OS API, no GPU, no audio. Full REST parity from a headless `python:3.11-slim` (`tests/contract/test_society_substrate.py` covers messages, rename with stable agent/chat IDs, and archive). The agent sidebar's hide choice is a browser-local display preference on every desktop OS; it does not change roster state. The dynamic `jarvis api society …` CLI layer covers every route. FTS5 over knowledge summaries is optional — a SQLite without it degrades to plain reads (same class as P-05). Per-agent screens (`agent_screen`) are M6 and keep their own per-OS probes |+| Typed chat on the Jarvis surface (brain runner, folder tools, approval card, CLI seats as Jarvis) | Clean; pure asyncio + SQLite, no OS API. Every CLI spawn keeps `NO_WINDOW_CREATIONFLAGS` and UTF-8 stdio. The identity for a Claude Code seat travels as a FILE under the app data dir (`jarvis_harness.write_identity_file`, removed after the turn) because Windows caps a command line at 32 767 characters; Codex and agy take it on stdin (no limit), Grok Build a compact cut on argv (`COMPACT_MAX_CHARS`). The MCP session header and the approval bridge are transport-level and OS-neutral |+Persistent Society agent teams use the same SQLite and FastAPI capability on Windows, macOS, and Linux. Membership lives in `society.db`; the frontend opens two existing canonical agent chats side by side with separate socket stores. Grouping never changes agent permissions, routing, or chat history. Headless membership persistence is covered by `tests/contract/test_society_substrate.py::test_persistent_group_membership_headless`.+## Open parity gapsOrdered by user impact. "Behavior" describes what a macOS/Linux user actuallydiff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sqlindex d13ea399a4..8b84b21ea1 100644--- a/jarvis/society/society_schema.sql+++ b/jarvis/society/society_schema.sql@@ -71,6 +71,15 @@ CREATE INDEX IF NOT EXISTS idx_society_events_inbox ON society_events(to_agent,CREATE INDEX IF NOT EXISTS idx_society_events_trace ON society_events(trace_id, seq);CREATE INDEX IF NOT EXISTS idx_society_events_from ON society_events(from_agent, seq);+-- Persistent, user-owned groups of existing canonical agent chats.+CREATE TABLE IF NOT EXISTS society_chat_groups (+ group_id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ members_json TEXT NOT NULL,+ created_ms INTEGER NOT NULL,+ updated_ms INTEGER NOT NULL+);+-- Bounded group discussions: state lives here, history in society_events-- (msg_type ROOM_OPEN / SAY / ROOM_SETTLE sharing the room's trace_id).CREATE TABLE IF NOT EXISTS society_rooms (diff --git a/jarvis/society/store.py b/jarvis/society/store.pyindex 95a3acf47e..ade2581973 100644--- a/jarvis/society/store.py+++ b/jarvis/society/store.py@@ -371,6 +371,65 @@ class SocietyStore:await cur.close()return [_row_to_envelope(r) for r in rows]+ # ------------------------------------------------------- persistent groups++ async def list_chat_groups(self) -> list[dict[str, Any]]:+ async with self.conn.execute(+ "SELECT group_id, name, members_json, created_ms, updated_ms "+ "FROM society_chat_groups ORDER BY created_ms ASC"+ ) as cur:+ rows = await cur.fetchall()+ return [+ {+ "group_id": row[0],+ "name": row[1],+ "members": json.loads(row[2]),+ "created_ms": row[3],+ "updated_ms": row[4],+ }+ for row in rows+ ]++ async def get_chat_group(self, group_id: str) -> dict[str, Any] | None:+ async with self.conn.execute(+ "SELECT group_id, name, members_json, created_ms, updated_ms "+ "FROM society_chat_groups WHERE group_id = ?",+ (group_id,),+ ) as cur:+ row = await cur.fetchone()+ if row is None:+ return None+ return {+ "group_id": row[0],+ "name": row[1],+ "members": json.loads(row[2]),+ "created_ms": row[3],+ "updated_ms": row[4],+ }++ async def create_chat_group(+ self, group_id: str, name: str, members: list[str]+ ) -> dict[str, Any]:+ stamp = now_ms()+ await self.conn.execute(+ "INSERT INTO society_chat_groups VALUES (?, ?, ?, ?, ?)",+ (group_id, name, json.dumps(members), stamp, stamp),+ )+ return (await self.get_chat_group(group_id)) or {}++ async def update_chat_group(+ self, group_id: str, name: str, members: list[str]+ ) -> dict[str, Any]:+ await self.conn.execute(+ "UPDATE society_chat_groups SET name = ?, members_json = ?, updated_ms = ? "+ "WHERE group_id = ?",+ (name, json.dumps(members), now_ms(), group_id),+ )+ return (await self.get_chat_group(group_id)) or {}++ async def delete_chat_group(self, group_id: str) -> None:+ await self.conn.execute("DELETE FROM society_chat_groups WHERE group_id = ?", (group_id,))+async def last_seq(self) -> int:cur = await self.conn.execute("SELECT COALESCE(MAX(seq), 0) FROM society_events")row = await cur.fetchone()diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsxindex 2913fa9781..570c0b6017 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx@@ -16,12 +16,17 @@ import { AgentSwatch } from "../AgentSwatch";import type { SocietyAgent } from "../data";import { AgentChatPanel } from "../chat/AgentChatPanel";import { RosterRail } from "../roster/RosterRail";+import type { SocietyChatGroup } from "@/lib/societyChatGroups";import { OptionsRail } from "./OptionsRail";export interface AgentCardOverlayProps {agent: SocietyAgent | null;/** Every agent — the rail lists them, the chat @mentions them. */roster: SocietyAgent[];+ groups?: SocietyChatGroup[];+ onSelectGroup?: (groupId: string) => void;+ onGroupAgents?: (sourceId: string, targetId: string) => void;+ onAddAgentToGroup?: (agentId: string, groupId: string) => void;/** True while the roster is still loading; the rail says so. */rosterLoading?: boolean;/** True while rows come from the sample roster rather than society.db. */@@ -40,6 +45,10 @@ export interface AgentCardOverlayProps {export function AgentCardOverlay({agent,roster,+ groups = [],+ onSelectGroup,+ onGroupAgents,+ onAddAgentToGroup,rosterLoading = false,sample = false,onSelectAgent,@@ -84,6 +93,10 @@ export function AgentCardOverlay({<div className="grid min-h-0 flex-1 grid-cols-[minmax(240px,300px)_minmax(0,1fr)]"><RosterRailagents={roster}+ groups={groups}+ onOpenGroup={onSelectGroup}+ onGroupAgents={onGroupAgents}+ onAddAgentToGroup={onAddAgentToGroup}loading={rosterLoading}sample={sample}activeAgentId={agent.agentId}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex f26d232c9e..bfbc90c0f2 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -56,7 +56,7 @@ import { ProviderLogo } from "@/components/providers/ProviderLogo";import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { societyDisplayName } from "@/lib/societyDisplayName";-import { createAgentChatStore, useAgentChatStore } from "@/store/agentChat";+import { createAgentChatStore, useAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";import type { AgentChatSurface, ApprovalDecision } from "@/lib/agentChatApi";import { AgentSwatch } from "../AgentSwatch";@@ -102,6 +102,8 @@ let onboardingAsked = false;export interface AgentChatPanelProps {agent: SocietyAgent;roster: SocietyAgent[];+ /** An isolated store lets two canonical agent sessions remain open side by side. */+ chatStore?: AgentChatStoreHook;}/**@@ -143,16 +145,15 @@ export function itemsForOpenSession(export function AgentChatPanel(props: AgentChatPanelProps) {const disconnect = useCallback(() => {- (props.agent.tier === "lead" ? useAgentChatStore : useSocietyChatStore).getState().disconnect();- }, [props.agent.tier]);- const assistantName = useEventStore((s) => s.assistantName);- const displayName = societyDisplayName(props.agent, assistantName);- return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: displayName }}>+ (props.agent.tier === "lead" ? useAgentChatStore : props.chatStore ?? useSocietyChatStore).getState().disconnect();+ }, [props.agent.tier, props.chatStore]);+ const assistantName = useEventStore((state) => state.assistantName);+ return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: societyDisplayName(props.agent, assistantName) }}><RoutineChatHost agentId={props.agent.agentId} onOpen={disconnect}><AgentChatPanelContent {...props} /></RoutineChatHost></PairConversationBoundary>;}-function AgentChatPanelContent({ agent, roster }: AgentChatPanelProps) {+function AgentChatPanelContent({ agent, roster, chatStore }: AgentChatPanelProps) {if (agent.tier === "lead") {return (<AgentChatStoreProvider store={useAgentChatStore}>@@ -162,7 +163,7 @@ function AgentChatPanelContent({ agent, roster }: AgentChatPanelProps) {}if (!agent.chatSessionId) return <NotBoundYet />;return (- <AgentChatStoreProvider store={useSocietyChatStore}>+ <AgentChatStoreProvider store={chatStore ?? useSocietyChatStore}><SpecialistChat agent={agent} roster={roster} /></AgentChatStoreProvider>);@@ -221,11 +222,10 @@ function SpecialistChat({ agent, roster }: AgentChatPanelProps) {}}, [visibleItems, agent.agentId]);const outgoing = useOutgoingMessages(sessionReady ? agent.agentId : null);- const assistantNameForRoster = useEventStore((s) => s.assistantName);const allItems = useMemo(() => mergeOutgoingMessages(- visibleItems, outgoing, agent.agentId, societyDisplayName(agent, assistantNameForRoster),- new Map(roster.map((member) => [member.agentId, societyDisplayName(member, assistantNameForRoster)])),- ), [visibleItems, outgoing, agent, assistantNameForRoster, roster]);+ visibleItems, outgoing, agent.agentId, agent.name,+ new Map(roster.map((member) => [member.agentId, member.name])),+ ), [visibleItems, outgoing, agent.agentId, agent.name, roster]);const view = useTranscriptView(sessionReady ? sessionId : null, allItems);// Open the agent's own session before the browser paints. Waiting on bind /@@ -646,8 +646,6 @@ export function Transcript({}) {const t = useT();const sessionId = useAgentChat((state) => state.activeSessionId);- const assistantName = useEventStore((s) => s.assistantName);- const displayName = societyDisplayName(agent, assistantName);// Follow the newest while the view sits at the end — the rule every// conversation surface shares (hooks/useStickToBottom). This used to scroll// a bottom sentinel into view on `[items.length, busy]` only, so a@@ -666,7 +664,7 @@ export function Transcript({return (<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-6 text-center"><AgentSwatch agent={agent} size={56} />- <p className="text-sm font-medium text-foreground">{t("society.chat.empty_title").replace("{0}", displayName)}</p>+ <p className="text-sm font-medium text-foreground">{t("society.chat.empty_title").replace("{0}", agent.name)}</p><p className="max-w-[32ch] text-xs text-muted-foreground">{t("society.chat.empty_hint")}</p></div>);@@ -1005,8 +1003,6 @@ interface ComposerProps {export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, surface = "jarvis", onClear, onSend, onCancel }: ComposerProps) {const t = useT();- const assistantName = useEventStore((s) => s.assistantName);- const displayName = societyDisplayName(agent, assistantName);const [modelSaving, setModelSaving] = useState(false);const [value, setValue] = useState("");const [plusOpen, setPlusOpen] = useState(false);@@ -1124,7 +1120,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sif (named.agents.length > 0 && surface === "society") {const teammates = named.agents.map((a) => `${JSON.stringify(a.name)} (id ${JSON.stringify(a.agentId)})`).join(", ");lines.push(- `${MENTION_MARK} Current sender: the user. Current recipient: ${JSON.stringify(displayName)} (id ${JSON.stringify(agent.agentId)}). ` ++ `${MENTION_MARK} Current sender: the user. Current recipient: ${JSON.stringify(agent.name)} (id ${JSON.stringify(agent.agentId)}). ` +`Mentioned teammates: ${teammates}. For teammate contact requested by the user, use society_message_agent; ` +"use kind 'query' when asking for information. If a work assignment is needed, contact Jarvis or an orchestrator with that tool. " +"Reply to the user here. An @mention or prose addressed to a teammate does not deliver a message.",@@ -1253,7 +1249,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s</div><ComposerChipFieldref={fieldRef}- placeholder={t("society.chat.placeholder").replace("{0}", displayName)}+ placeholder={t("society.chat.placeholder").replace("{0}", agent.name)}disabled={false}onSubmit={() => void submit()}onDraftChange={onDraftChange}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsxnew file mode 100644index 0000000000..4c78d2139c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupDialog.tsx@@ -0,0 +1,74 @@+import { useState, type FormEvent } from "react";+import * as Dialog from "@radix-ui/react-dialog";+import { useQueryClient } from "@tanstack/react-query";+import { useT } from "@/i18n";+import { createSocietyChatGroup, updateSocietyChatGroup, type SocietyChatGroup } from "@/lib/societyChatGroups";+import type { SocietyAgent } from "../data";+import { AgentSwatch } from "../AgentSwatch";++interface Props {+ group?: SocietyChatGroup;+ agents: SocietyAgent[];+ onClose: () => void;+ onSaved: (groupId: string) => void;+}++export function ChatGroupDialog({ group, agents, onClose, onSaved }: Props) {+ const t = useT();+ const client = useQueryClient();+ const [name, setName] = useState(group?.name ?? "");+ const [members, setMembers] = useState<string[]>(group?.members.filter((id) =>+ agents.some((agent) => agent.agentId === id && agent.lifecycle !== "archived")) ?? []);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const choices = agents.filter((agent) => agent.tier !== "lead" && agent.lifecycle !== "archived");++ const submit = async (event: FormEvent) => {+ event.preventDefault();+ if (!name.trim() || members.length < 2) return;+ setBusy(true);+ setError("");+ try {+ const saved = group+ ? await updateSocietyChatGroup(group.group_id, name.trim(), members)+ : await createSocietyChatGroup(name.trim(), members);+ await client.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ onSaved(saved.group_id);+ onClose();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setBusy(false);+ }+ };++ return <Dialog.Root open onOpenChange={(open) => { if (!open) onClose(); }}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[150] bg-scrim/60" />+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[151] flex max-h-[80vh] w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col rounded-xl border border-border bg-card p-5 text-foreground shadow-xl">+ <Dialog.Title className="font-display text-lg font-semibold">{t(group ? "society.groups.edit" : "society.groups.create")}</Dialog.Title>+ <Dialog.Description className="mt-1 text-sm text-muted-foreground">{t("society.groups.description")}</Dialog.Description>+ <form onSubmit={(event) => void submit(event)} className="mt-4 flex min-h-0 flex-col gap-3">+ <label className="text-sm font-medium">{t("society.groups.name")}+ <input autoFocus maxLength={80} value={name} onChange={(event) => setName(event.target.value)}+ className="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-foreground" />+ </label>+ <p className="text-sm font-medium">{t("society.groups.members")} ({members.length})</p>+ <div className="min-h-0 overflow-y-auto rounded-md border border-border p-1">+ {choices.map((agent) => <label key={agent.agentId} className="flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 hover:bg-secondary">+ <input type="checkbox" checked={members.includes(agent.agentId)} onChange={() => setMembers((current) => current.includes(agent.agentId) ? current.filter((id) => id !== agent.agentId) : [...current, agent.agentId])} />+ <AgentSwatch agent={agent} size={28} />+ <span className="min-w-0 truncate text-sm">{agent.name}</span>+ </label>)}+ </div>+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ <div className="flex justify-end gap-2">+ <button type="button" onClick={onClose} className="rounded-md px-3 py-2 text-sm hover:bg-secondary">{t("society.groups.cancel")}</button>+ <button type="submit" disabled={busy || !name.trim() || members.length < 2}+ className="rounded-md bg-primary px-3 py-2 text-sm text-primary-foreground disabled:opacity-50">{t("society.groups.save")}</button>+ </div>+ </form>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsxnew file mode 100644index 0000000000..25278a0020--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.test.tsx@@ -0,0 +1,45 @@+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, expect, it, vi } from "vitest";+import type { SocietyAgent } from "../data";+import { ChatGroupPanel } from "./ChatGroupPanel";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("../roster/RosterRail", () => ({ RosterRail: () => <aside /> }));+vi.mock("./AgentChatPanel", () => ({+ AgentChatPanel: ({ agent, chatStore }: { agent: SocietyAgent; chatStore: any }) => {+ const session = chatStore((state: { activeSessionId: string | null }) => state.activeSessionId);+ return <div data-testid={`chat-${agent.agentId}`} data-session={session ?? ""}>+ <button onClick={() => chatStore.setState({ activeSessionId: agent.chatSessionId })}>+ Open {agent.name}+ </button>+ </div>;+ },+}));++afterEach(cleanup);++it("opens two existing agent chats in separate stores and keeps each pane independent", () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const other = { agentId: "other", name: "hdckjashx", tier: "specialist", chatSessionId: "society:other" } as SocietyAgent;+ const test = { agentId: "test", name: "Test", tier: "specialist", chatSessionId: "society:test" } as SocietyAgent;+ render(<QueryClientProvider client={client}><ChatGroupPanel+ group={{ group_id: "team", name: "hdckjashx + Test", members: ["other", "test"], created_ms: 1, updated_ms: 1 }}+ groups={[]} roster={[other, test]} onOpenAgent={() => undefined} onOpenGroup={() => undefined}+ onCreateAgent={() => undefined} onDeleted={() => undefined}+ onGroupAgents={() => undefined} onAddAgentToGroup={() => undefined}+ /></QueryClientProvider>);++ const left = screen.getByTestId("society-group-pane-left");+ const right = screen.getByTestId("society-group-pane-right");+ expect(within(left).getByTestId("society-group-select-left").getAttribute("data-value")).toBe("other");+ expect(within(right).getByTestId("society-group-select-right").getAttribute("data-value")).toBe("test");+ expect(within(left).getByTestId("chat-other")).toBeTruthy();+ expect(within(right).getByTestId("chat-test")).toBeTruthy();+ fireEvent.click(within(left).getByRole("button", { name: "Open hdckjashx" }));+ expect(within(left).getByTestId("chat-other").getAttribute("data-session")).toBe("society:other");+ expect(within(right).getByTestId("chat-test").getAttribute("data-session")).toBe("");+ fireEvent.click(within(right).getByRole("button", { name: "Open Test" }));+ expect(within(right).getByTestId("chat-test").getAttribute("data-session")).toBe("society:test");+ expect(within(left).getByTestId("chat-other").getAttribute("data-session")).toBe("society:other");+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsxnew file mode 100644index 0000000000..05bd100e63--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatGroupPanel.tsx@@ -0,0 +1,116 @@+import { useEffect, useMemo, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { Pencil, Trash2, UsersRound } from "lucide-react";+import { useT } from "@/i18n";+import { BrandedSelect } from "@/components/ui/select";+import { deleteSocietyChatGroup, type SocietyChatGroup } from "@/lib/societyChatGroups";+import { createAgentChatStore } from "@/store/agentChat";+import type { SocietyAgent } from "../data";+import { RosterRail } from "../roster/RosterRail";+import { AgentChatPanel } from "./AgentChatPanel";+import { ChatGroupDialog } from "./ChatGroupDialog";++interface Props {+ group: SocietyChatGroup;+ groups: SocietyChatGroup[];+ roster: SocietyAgent[];+ onOpenAgent: (id: string) => void;+ onOpenGroup: (id: string) => void;+ onCreateAgent: () => void;+ onDeleted: () => void;+ onGroupAgents: (sourceId: string, targetId: string) => void;+ onAddAgentToGroup: (agentId: string, groupId: string) => void;+}++export function ChatGroupPanel({+ group, groups, roster, onOpenAgent, onOpenGroup, onCreateAgent, onDeleted,+ onGroupAgents, onAddAgentToGroup,+}: Props) {+ const t = useT();+ const client = useQueryClient();+ const [leftId, setLeftId] = useState(group.members[0] ?? "");+ const [rightId, setRightId] = useState(group.members[1] ?? "");+ const [editing, setEditing] = useState(false);+ const [error, setError] = useState("");+ const leftStore = useMemo(() => createAgentChatStore("society", `group:${group.group_id}:left`), [group.group_id]);+ const rightStore = useMemo(() => createAgentChatStore("society", `group:${group.group_id}:right`), [group.group_id]);++ useEffect(() => () => {+ leftStore.getState().disconnect();+ rightStore.getState().disconnect();+ }, [leftStore, rightStore]);++ const members = group.members+ .map((id) => roster.find((agent) => agent.agentId === id))+ .filter((agent): agent is SocietyAgent => Boolean(agent));+ const left = members.find((agent) => agent.agentId === leftId) ?? members[0];+ const right = members.find((agent) => agent.agentId === rightId && agent.agentId !== left?.agentId)+ ?? members.find((agent) => agent.agentId !== left?.agentId);++ const remove = async () => {+ if (!window.confirm(t("society.groups.delete_confirm"))) return;+ setError("");+ try {+ await deleteSocietyChatGroup(group.group_id);+ await client.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ onDeleted();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ }+ };++ const pane = (side: "left" | "right", agent: SocietyAgent | undefined) => (+ <section key={side} data-testid={`society-group-pane-${side}`} className="flex min-h-0 min-w-0 flex-col bg-background">+ {agent ? <>+ <header className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">+ <div className="min-w-0 flex-1 text-xs font-medium text-muted-foreground">+ <span>{t(side === "left" ? "society.groups.left_chat" : "society.groups.right_chat")}</span>+ <BrandedSelect+ ariaLabel={t(side === "left" ? "society.groups.left_chat" : "society.groups.right_chat")}+ testId={`society-group-select-${side}`}+ value={agent.agentId}+ onValueChange={(value) => side === "left" ? setLeftId(value) : setRightId(value)}+ className="mt-1 w-full"+ options={members.filter((member) => member.agentId !== (side === "left" ? right?.agentId : left?.agentId))+ .map((member) => ({ value: member.agentId, label: member.name }))}+ />+ </div>+ <button type="button" onClick={() => onOpenAgent(agent.agentId)}+ className="rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground"+ aria-label={t("society.groups.open_individual").replace("{0}", agent.name)}>+ {t("society.groups.open")}+ </button>+ </header>+ <div className="min-h-0 flex-1">+ <AgentChatPanel key={agent.agentId} agent={agent} roster={roster}+ chatStore={side === "left" ? leftStore : rightStore} />+ </div>+ </> : <p className="m-auto p-6 text-center text-sm text-muted-foreground">{t("society.groups.missing_member")}</p>}+ </section>+ );++ return <div className="grid min-h-0 flex-1 grid-cols-[minmax(240px,300px)_minmax(0,1fr)] bg-card" data-testid="society-group-chat">+ <RosterRail agents={roster} groups={groups} activeGroupId={group.group_id} activeAgentId={null}+ onOpen={onOpenAgent} onOpenGroup={onOpenGroup} onCreate={onCreateAgent}+ onGroupAgents={onGroupAgents} onAddAgentToGroup={onAddAgentToGroup}+ loading={false} sample={false} side="left" className="w-full border-0 jarvis-nav-surface" />+ <div className="flex min-h-0 min-w-0 flex-col overflow-hidden border-l border-border bg-background">+ <header className="flex shrink-0 items-center gap-3 border-b border-border px-5 py-3">+ <UsersRound className="h-5 w-5 text-muted-foreground" aria-hidden />+ <div className="min-w-0 flex-1"><h2 className="truncate font-display text-base font-semibold">{group.name}</h2>+ <p className="text-xs text-muted-foreground">{members.length} {t("society.groups.members")}</p>+ </div>+ <button type="button" onClick={() => setEditing(true)} aria-label={t("society.groups.edit")}+ className="rounded-md p-2 text-muted-foreground hover:bg-secondary hover:text-foreground"><Pencil className="h-4 w-4" /></button>+ <button type="button" onClick={() => void remove()} aria-label={t("society.groups.delete")}+ className="rounded-md p-2 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"><Trash2 className="h-4 w-4" /></button>+ </header>+ {error && <p role="alert" className="px-5 py-1 text-sm text-destructive">{error}</p>}+ <div className="grid min-h-0 flex-1 grid-cols-2 divide-x divide-border" data-testid="society-group-split">+ {pane("left", left)}+ {pane("right", right)}+ </div>+ </div>+ {editing && <ChatGroupDialog group={group} agents={roster} onClose={() => setEditing(false)} onSaved={onOpenGroup} />}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsxindex 4158cb47f6..9fa6a23c71 100644--- a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { SocietyAgent } from "@/components/society/data";import { useRetireStore } from "@/components/society/world/retireStore";import { useEventStore } from "@/store/events";-import { RosterRail } from "./RosterRail";+import { RosterRail, type RosterRailProps } from "./RosterRail";vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));@@ -14,9 +14,9 @@ afterEach(() => {cleanup();localStorage.clear();vi.unstubAllGlobals();+ vi.useRealTimers();useEventStore.setState({ assistantName: "Assistant" });});-function agent(over: Partial<SocietyAgent> & Pick<SocietyAgent, "agentId" | "name">): SocietyAgent {return {title: "Title",@@ -57,6 +57,18 @@ const baseProps = {};describe("RosterRail status", () => {+ it("shows a team as one row and keeps its members out of the sidebar", () => {+ const openGroup = vi.fn();+ render(<RosterRail {...baseProps} activeAgentId={null}+ agents={[agent({ agentId: "scout", name: "Scout" }), agent({ agentId: "writer", name: "Writer" })]}+ groups={[{ group_id: "team", name: "Launch team", members: ["scout", "writer"], created_ms: 1, updated_ms: 1 }]}+ onOpenGroup={openGroup} />);+ expect(screen.queryByText("Scout")).toBeNull();+ expect(screen.queryByText("Writer")).toBeNull();+ expect(screen.getByText("Scout, Writer")).toBeTruthy();+ fireEvent.click(screen.getByTestId("society-group-team"));+ expect(openGroup).toHaveBeenCalledWith("team");+ });it("shows a loading spinner while an agent is thinking", () => {render(<RosterRail@@ -198,16 +210,9 @@ describe("RosterRail reorder", () => {return row;};- const dragData = () => ({ setData: vi.fn(), getData: vi.fn().mockReturnValue(""), effectAllowed: "", dropEffect: "" });-- it("files a dragged row before the drop target and persists the order", () => {+ it("leaves HTML dragging off so pointer reordering owns the gesture", () => {renderRail(trio());- expect(rowOrder()).toEqual(["a", "b", "c"]);- fireEvent.dragStart(rowOf("A"), { dataTransfer: dragData() });- fireEvent.dragOver(rowOf("C"), { dataTransfer: dragData() });- fireEvent.drop(rowOf("C"), { dataTransfer: dragData() });- expect(rowOrder()).toEqual(["b", "a", "c"]);- expect(JSON.parse(localStorage.getItem(ORDER_KEY) ?? "[]")).toEqual(["b", "a", "c"]);+ expect(rowOf("A").hasAttribute("draggable")).toBe(false);});it("restores the persisted order on mount", () => {@@ -235,14 +240,14 @@ describe("RosterRail reorder", () => {it("locks rows while searching so the excerpt cannot file the order", () => {renderRail(trio());fireEvent.change(screen.getByRole("searchbox"), { target: { value: "a" } });- expect(rowOf("A").getAttribute("draggable")).toBe("false");+ expect(rowOf("A").className).not.toContain("cursor-grab");expect(localStorage.getItem(ORDER_KEY)).toBeNull();});});describe("RosterRail press-drag", () => {const ORDER_KEY = "society.roster.order";- const renderRail = (agents: SocietyAgent[], props: Partial<typeof baseProps> = {}) => {+ const renderRail = (agents: SocietyAgent[], props: Partial<RosterRailProps> = {}) => {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });return render(<QueryClientProvider client={client}><RosterRail {...baseProps} {...props} agents={agents} activeAgentId={null} />@@ -323,6 +328,51 @@ describe("RosterRail press-drag", () => {expect(onOpen).not.toHaveBeenCalled();});+ it("keeps a quick drop as a reorder even when grouping is available", () => {+ const onGroupAgents = vi.fn();+ renderRail(trio(), { onGroupAgents });+ mockLayout({ a: 0, b: 48, c: 96 });+ pressRow(rowOf("A"), 10, 10);+ movePointer(10, 80);+ releasePointer(10, 80);+ expect(rowOrder()).toEqual(["b", "a", "c"]);+ expect(onGroupAgents).not.toHaveBeenCalled();+ });++ it("groups two agents only after holding over the target row", () => {+ const onGroupAgents = vi.fn();+ renderRail(trio(), { onGroupAgents });+ mockLayout({ a: 0, b: 48, c: 96 });+ vi.useFakeTimers();+ pressRow(rowOf("A"), 10, 10);+ movePointer(10, 80);+ expect(screen.getByTestId("society-group-drop-hint").textContent).toBe("society.groups.hold_to_group");+ act(() => vi.advanceTimersByTime(760));+ expect(screen.getByTestId("society-group-drop-hint").textContent).toBe("society.groups.release_to_group");+ releasePointer(10, 80);+ expect(onGroupAgents).toHaveBeenCalledWith("a", "b");+ expect(rowOrder()).toEqual(["a", "b", "c"]);+ });++ it("adds an agent to a team by holding over its single sidebar row", () => {+ const onAddAgentToGroup = vi.fn();+ renderRail(trio(), {+ groups: [{ group_id: "team", name: "Team", members: ["b", "c"], created_ms: 1, updated_ms: 1 }],+ onAddAgentToGroup,+ });+ mockLayout({ a: 100 });+ vi.spyOn(screen.getByTestId("society-group-team"), "getBoundingClientRect").mockReturnValue({+ x: 0, y: 0, top: 0, left: 0, bottom: 48, right: 200,+ width: 200, height: 48, toJSON: () => ({}),+ } as DOMRect);+ vi.useFakeTimers();+ pressRow(rowOf("A"), 10, 110);+ movePointer(10, 20);+ act(() => vi.advanceTimersByTime(760));+ releasePointer(10, 20);+ expect(onAddAgentToGroup).toHaveBeenCalledWith("a", "team");+ });+it("drops after the last row when released below the list", () => {renderRail(trio());mockLayout({ a: 0, b: 48, c: 96 });@@ -351,30 +401,13 @@ describe("RosterRail press-drag", () => {});});-describe("RosterRail lead display name", () => {- const renderRail = (agents: SocietyAgent[]) => {- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });- return render(<QueryClientProvider client={client}>- <RosterRail {...baseProps} agents={agents} activeAgentId={null} />- </QueryClientProvider>);- };-- it("shows the wake-word name for the lead instead of the backend name", () => {- useEventStore.setState({ assistantName: "Hanna" });- renderRail([agent({ agentId: "jarvis", name: "Jarvis", tier: "lead", title: "Lead" })]);- expect(screen.getByTestId("society-lead-hero")).toBeTruthy();- expect(screen.getByText("Hanna")).toBeTruthy();- expect(screen.queryByText("Jarvis")).toBeNull();- });-- it("finds the lead by display name and by stored name", () => {- useEventStore.setState({ assistantName: "Hanna" });- const lead = agent({ agentId: "jarvis", name: "Jarvis", tier: "lead", title: "Lead" });- const { unmount } = renderRail([lead]);- fireEvent.change(screen.getByRole("searchbox"), { target: { value: "hanna" } });- expect(screen.getByText("Hanna")).toBeTruthy();- fireEvent.change(screen.getByRole("searchbox"), { target: { value: "jarvis" } });- expect(screen.getByText("Hanna")).toBeTruthy();- unmount();- });+it("shows and finds the lead by the wake-word name", () => {+ useEventStore.setState({ assistantName: "Hanna" });+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}>+ <RosterRail {...baseProps} agents={[agent({ agentId: "jarvis", name: "Jarvis", tier: "lead" })]} activeAgentId={null} />+ </QueryClientProvider>);+ expect(screen.getByText("Hanna")).toBeTruthy();+ fireEvent.change(screen.getByRole("searchbox"), { target: { value: "hanna" } });+ expect(screen.getByText("Hanna")).toBeTruthy();});diff --git a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsxindex 726637d865..3259e7286f 100644--- a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx@@ -20,8 +20,8 @@* profile) working; the drop position shows as a line above or below the* target row. HTML5 drag events and Alt + Arrow keys stay as fallbacks.*/-import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent, type MouseEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";-import { Eye, Loader2, Plus, Search } from "lucide-react";+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";+import { Eye, Loader2, Plus, Search, UsersRound } from "lucide-react";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";@@ -30,16 +30,21 @@ import { useT } from "@/i18n";import { societyDisplayName } from "@/lib/societyDisplayName";import { cn } from "@/lib/utils";import { useEventStore } from "@/store/events";+import type { SocietyChatGroup } from "@/lib/societyChatGroups";import { AgentSwatch } from "../AgentSwatch";import type { AgentRunState, SocietyAgent } from "../data";import { AgentRosterActions } from "./AgentRosterActions";import { useRosterUnread } from "./useRosterUnread";+import { ChatGroupDialog } from "../chat/ChatGroupDialog";const HIDDEN_AGENTS_KEY = "society.roster.hidden-agent-ids";const ORDER_KEY = "society.roster.order";/** How far the pointer must travel before a press becomes a drag. */const PRESS_DRAG_THRESHOLD_PX = 6;+/** A deliberate pause over another row creates a team; a quick drop reorders. */+const GROUP_HOLD_MS = 750;+type GroupDropTarget = { kind: "agent" | "group"; id: string };function readHiddenAgents(): string[] {try {@@ -75,6 +80,11 @@ const STATE_DOT: Record<AgentRunState, string> = {export interface RosterRailProps {agents: SocietyAgent[];+ groups?: SocietyChatGroup[];+ activeGroupId?: string | null;+ onOpenGroup?: (groupId: string) => void;+ onGroupAgents?: (sourceId: string, targetId: string) => void;+ onAddAgentToGroup?: (agentId: string, groupId: string) => void;loading: boolean;/** True while rows come from the sample roster rather than society.db. */sample: boolean;@@ -91,6 +101,11 @@ export interface RosterRailProps {export function RosterRail({agents,+ groups = [],+ activeGroupId = null,+ onOpenGroup,+ onGroupAgents,+ onAddAgentToGroup,loading,sample,activeAgentId,@@ -102,20 +117,21 @@ export function RosterRail({}: RosterRailProps) {const t = useT();const [query, setQuery] = useState("");+ const [creatingGroup, setCreatingGroup] = useState(false);const [profileId, setProfileId] = useState<string | null>(null);const [hiddenIds, setHiddenIds] = useState(readHiddenAgents);const [orderIds, setOrderIds] = useState(readRosterOrder);const [dragId, setDragId] = useState<string | null>(null);const [dropId, setDropId] = useState<string | null>(null);const [dropAfter, setDropAfter] = useState(false);+ const [groupHover, setGroupHover] = useState<GroupDropTarget | null>(null);+ const [groupReady, setGroupReady] = useState(false);const [showHidden, setShowHidden] = useState(false);const [menu, setMenu] = useState<{ agentId: string; x: number; y: number } | null>(null);const profile = agents.find((agent) => agent.agentId === profileId);const menuAgent = agents.find((agent) => agent.agentId === menu?.agentId);const unread = useRosterUnread(agents, activeAgentId);- // The lead's visible name follows the wake word (e.g. "Hanna" for- // "Hey Hanna"); every other agent keeps its roster name.- const assistantName = useEventStore((s) => s.assistantName);+ const assistantName = useEventStore((state) => state.assistantName);const setHidden = useCallback((agentId: string, hidden: boolean) => {setHiddenIds((current) => {@@ -132,23 +148,22 @@ export function RosterRail({};const lead = useMemo(() => agents.find((a) => a.tier === "lead") ?? null, [agents]);+ const groupedIds = useMemo(() => new Set(groups.flatMap((group) => group.members)), [groups]);+ const visibleGroups = groups.filter((group) => `${group.name} ${group.members.map((id) => agents.find((agent) => agent.agentId === id)?.name ?? "").join(" ")}`.toLowerCase().includes(query.trim().toLowerCase()));const { leadVisible, rows } = useMemo(() => {const q = query.trim().toLowerCase();const filtered = agents.filter((a) => {if (!showHidden && hiddenIds.includes(a.agentId)) return false;if (!q) return true;- // The lead is shown under the wake-word name, so the search matches- // both the display name and the stored roster name.- const display = societyDisplayName(a, assistantName);- return `${a.name} ${display} ${a.title}`.toLowerCase().includes(q);+ return `${a.name} ${societyDisplayName(a, assistantName)} ${a.title}`.toLowerCase().includes(q);},);const masterVisible = lead ? filtered.some((a) => a.agentId === lead.agentId) : false;// Orchestrators, then specialists; stable within a tier. The lead lives// in its own centered hero above and never repeats in the list.const rank = { lead: 0, orchestrator: 1, specialist: 2 } as const;const rest = filtered- .filter((a) => a.agentId !== lead?.agentId);+ .filter((a) => a.agentId !== lead?.agentId && !groupedIds.has(a.agentId));// A drag persists the full visible order, so from then on the person's// own arrangement wins over the tier grouping. Agents the list never saw// (freshly created, or a retired id still stored) settle at the end in@@ -166,33 +181,12 @@ export function RosterRail({return rank[a.tier] - rank[b.tier];});return { leadVisible: masterVisible, rows: rest };- }, [agents, assistantName, hiddenIds, lead, orderIds, query, showHidden]);+ }, [agents, assistantName, groupedIds, hiddenIds, lead, orderIds, query, showHidden]);// While searching, the list is a filtered excerpt — dragging there would// file agents by where they happen to sit in the excerpt, so rows stay put.const reorderable = query.trim() === "";- /** File `fromId` in directly before `toId`, keeping every other row where it is. */- const moveBefore = useCallback((fromId: string, toId: string) => {- if (fromId === toId) return;- setOrderIds((current) => {- const base = rows.map((a) => a.agentId);- const known = new Set(base);- // Carry over stored ids for rows currently filtered out (hidden while- // "show hidden" is off) so a drag never silently drops them.- for (const id of current) if (!known.has(id)) base.push(id);- const without = base.filter((id) => id !== fromId);- const at = without.indexOf(toId);- const next = at === -1 ? [...without, fromId] : [...without.slice(0, at), fromId, ...without.slice(at)];- try {- localStorage.setItem(ORDER_KEY, JSON.stringify(next));- } catch {- // Private mode: the order holds for this window.- }- return next;- });- }, [rows]);-/*** File `fromId` directly before `toId`, or directly after it when `after`* is set. Unlike the native-drop path this can also land behind the last@@ -255,26 +249,31 @@ export function RosterRail({};// --- Press-and-drag: the whole row is the handle. ------------------------ // Native HTML5 dragging starts only from non-interactive gaps, so a press- // on the agent's name or avatar never became a drag. These pointer- // listeners turn any left-button press on the row into a drag once the- // pointer travels past a small threshold, track the row under the pointer- // on the window (so fast moves stay tracked), and swallow the click that- // follows a completed drag so the chat does not open by accident.+ // One pointer gesture owns both actions. Native HTML drag competes with+ // pointermove in WebView and can cancel the gesture before release.+ // A quick drop reorders; holding over a row or group makes a team.const listRef = useRef<HTMLUListElement | null>(null);+ const railRef = useRef<HTMLElement | null>(null);const pendingRef = useRef<{ id: string; startX: number; startY: number; pointerId: number } | null>(null);const pointerDragRef = useRef(false);const suppressClickRef = useRef(false);const dragIdRef = useRef<string | null>(null);const dropIdRef = useRef<string | null>(null);const dropAfterRef = useRef(false);+ const groupHoverRef = useRef<GroupDropTarget | null>(null);+ const groupReadyRef = useRef(false);+ const holdTimerRef = useRef<number | null>(null);const reorderableRef = useRef(reorderable);const moveToRef = useRef(moveToPosition);+ const groupAgentsRef = useRef(onGroupAgents);+ const addToGroupRef = useRef(onAddAgentToGroup);dragIdRef.current = dragId;dropIdRef.current = dropId;dropAfterRef.current = dropAfter;reorderableRef.current = reorderable;moveToRef.current = moveToPosition;+ groupAgentsRef.current = onGroupAgents;+ addToGroupRef.current = onAddAgentToGroup;useEffect(() => {const rowElements = () => {@@ -282,6 +281,44 @@ export function RosterRail({if (!list) return [] as HTMLElement[];return [...list.querySelectorAll("[data-agent-id]")] as HTMLElement[];};+ const hit = (element: HTMLElement, x: number, y: number) => {+ const rect = element.getBoundingClientRect();+ return rect.width > 0 && rect.height > 0 && x >= rect.left && x <= rect.right+ && y >= rect.top && y <= rect.bottom;+ };+ const groupTargetAt = (x: number, y: number, sourceId: string): GroupDropTarget | null => {+ if (groupAgentsRef.current) {+ const agent = rowElements().find((element) =>+ element.dataset.agentId !== sourceId && hit(element, x, y));+ if (agent?.dataset.agentId) return { kind: "agent", id: agent.dataset.agentId };+ }+ if (addToGroupRef.current) {+ const group = [...(railRef.current?.querySelectorAll("[data-group-id]") ?? [])]+ .find((element) => hit(element as HTMLElement, x, y)) as HTMLElement | undefined;+ if (group?.dataset.groupId) return { kind: "group", id: group.dataset.groupId };+ }+ return null;+ };+ const clearHold = () => {+ if (holdTimerRef.current !== null) window.clearTimeout(holdTimerRef.current);+ holdTimerRef.current = null;+ groupHoverRef.current = null;+ groupReadyRef.current = false;+ setGroupHover(null);+ setGroupReady(false);+ };+ const updateHold = (target: GroupDropTarget | null) => {+ const previous = groupHoverRef.current;+ if (previous?.kind === target?.kind && previous?.id === target?.id) return;+ clearHold();+ if (!target) return;+ groupHoverRef.current = target;+ setGroupHover(target);+ holdTimerRef.current = window.setTimeout(() => {+ groupReadyRef.current = true;+ setGroupReady(true);+ }, GROUP_HOLD_MS);+ };const onMove = (event: PointerEvent) => {if (!reorderableRef.current) return;let sourceId = pointerDragRef.current ? dragIdRef.current : null;@@ -304,6 +341,7 @@ export function RosterRail({if (sourceEl) {const rect = sourceEl.getBoundingClientRect();if (rect.height > 0 && event.clientY >= rect.top && event.clientY <= rect.bottom) {+ updateHold(null);if (dropIdRef.current !== null) {setDropId(null);setDropAfter(false);@@ -311,6 +349,13 @@ export function RosterRail({return;}}+ const groupTarget = groupTargetAt(event.clientX, event.clientY, sourceId);+ updateHold(groupTarget);+ if (groupTarget?.kind === "group") {+ if (dropIdRef.current !== null) setDropId(null);+ if (event.cancelable) event.preventDefault();+ return;+ }let target: { id: string; after: boolean } | null = null;for (const el of elements) {const id = el.getAttribute("data-agent-id");@@ -341,26 +386,35 @@ export function RosterRail({return;}};- const finish = (commit: boolean) => {+ const finish = (commit: boolean, event?: PointerEvent) => {if (pointerDragRef.current && dragIdRef.current) {const from = dragIdRef.current;const toId = dropIdRef.current;const after = dropAfterRef.current;+ const held = groupReadyRef.current ? groupHoverRef.current : null;+ const releasedOn = event ? groupTargetAt(event.clientX, event.clientY, from) : null;pendingRef.current = null;pointerDragRef.current = false;setDragId(null);setDropId(null);setDropAfter(false);- if (commit && toId && toId !== from) moveToRef.current(from, toId, after);+ clearHold();+ if (commit && held && releasedOn?.kind === held.kind && releasedOn.id === held.id) {+ if (held.kind === "agent") groupAgentsRef.current?.(from, held.id);+ else addToGroupRef.current?.(from, held.id);+ } else if (commit && releasedOn?.kind !== "group" && toId && toId !== from) {+ moveToRef.current(from, toId, after);+ }suppressClickRef.current = true;window.setTimeout(() => {suppressClickRef.current = false;}, 0);} else {pendingRef.current = null;+ clearHold();}};- const onUp = () => finish(true);+ const onUp = (event: PointerEvent) => finish(true, event);const onCancel = () => finish(false);const onKey = (event: globalThis.KeyboardEvent) => {if (event.key === "Escape") finish(false);@@ -374,6 +428,7 @@ export function RosterRail({window.removeEventListener("pointerup", onUp);window.removeEventListener("pointercancel", onCancel);window.removeEventListener("keydown", onKey);+ if (holdTimerRef.current !== null) window.clearTimeout(holdTimerRef.current);};}, []);@@ -401,64 +456,11 @@ export function RosterRail({setProfileId(agentId);};- const onDragStart = (event: DragEvent, agentId: string) => {- // A press-drag already owns the gesture; never let the native backend- // start a second drag on top of it.- if (pointerDragRef.current) {- event.preventDefault();- return;- }- setDragId(agentId);- try {- event.dataTransfer.effectAllowed = "move";- event.dataTransfer.setData("text/plain", agentId);- } catch {- // jsdom / touch: the state above still drives the drop.- }- };-- const onDragOverRow = (event: DragEvent, agentId: string) => {- if (pointerDragRef.current) return;- if (!dragId || dragId === agentId) return;- event.preventDefault();- try {- event.dataTransfer.dropEffect = "move";- } catch {- // Non-HTML backends ignore the hint; the drop still lands.- }- if (dropId !== agentId) {- setDropId(agentId);- setDropAfter(false);- }- };-- const onDropRow = (event: DragEvent, agentId: string) => {- if (pointerDragRef.current) return;- event.preventDefault();- const from = dragId ?? (() => {- try {- return event.dataTransfer.getData("text/plain") || null;- } catch {- return null;- }- })();- if (from && from !== agentId) moveBefore(from, agentId);- setDragId(null);- setDropId(null);- setDropAfter(false);- };-- const endDrag = useCallback(() => {- if (pointerDragRef.current) return;- setDragId(null);- setDropId(null);- setDropAfter(false);- }, []);-const hiddenCount = agents.filter((agent) => hiddenIds.includes(agent.agentId)).length;return (<aside+ ref={railRef}data-testid="society-roster-rail"className={cn("flex h-full min-h-0 flex-col border-border bg-sidebar",@@ -478,6 +480,10 @@ export function RosterRail({</Badge>) : null}</div>+ <div className="flex items-center gap-1">+ {!sample && onOpenGroup && <Button size="sm" variant="secondary" className="h-8 px-2" onClick={() => setCreatingGroup(true)} data-testid="society-create-group-button" aria-label={t("society.groups.create")} title={t("society.groups.create")}>+ <UsersRound className="h-4 w-4" aria-hidden />+ </Button>}<Buttonsize="sm"variant="secondary"@@ -488,6 +494,7 @@ export function RosterRail({<Plus className="h-3.5 w-3.5" aria-hidden />{t("society.roster.create")}</Button>+ </div></div><label className="relative mx-3 mt-3 block"><Search@@ -550,11 +557,30 @@ export function RosterRail({{leadVisible ? (<div className="mx-3 mb-1 border-t border-border/60" aria-hidden />) : null}+ {visibleGroups.length > 0 && <ul className="flex flex-col gap-0.5 px-2 pb-2">+ {visibleGroups.map((group) => <li key={group.group_id}>+ <button type="button" data-group-id={group.group_id} onClick={() => onOpenGroup?.(group.group_id)} aria-current={activeGroupId === group.group_id ? "true" : undefined}+ className={cn("flex w-full items-center gap-2.5 rounded-md px-2 py-2 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", activeGroupId === group.group_id && "bg-secondary", groupHover?.kind === "group" && groupHover.id === group.group_id && (groupReady ? "ring-2 ring-primary" : "ring-1 ring-border-strong"))}+ data-testid={`society-group-${group.group_id}`}>+ <span className="flex w-12 shrink-0 items-center justify-center">+ {group.members.slice(0, 3).map((id, index) => {+ const member = agents.find((agent) => agent.agentId === id);+ return member ? <span key={id} className={cn("rounded-full ring-2 ring-sidebar", index > 0 && "-ml-3")}><AgentSwatch agent={member} size={26} /></span> : null;+ })}+ </span>+ <span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-foreground">{group.name}</span>+ <span className="block truncate text-xs text-muted-foreground">{groupHover?.kind === "group" && groupHover.id === group.group_id+ ? t(groupReady ? "society.groups.release_to_group" : "society.groups.hold_to_group")+ : group.members.map((id) => agents.find((agent) => agent.agentId === id)?.name ?? id).join(", ")}</span>+ </span>+ </button>+ </li>)}+ </ul>}<ul ref={listRef} className="flex flex-col gap-0.5 px-2 pb-3">{loading && !leadVisible && rows.length === 0 ? (<li className="px-2 py-3 text-xs text-muted-foreground">{t("society.roster.loading")}</li>) : null}- {!loading && !leadVisible && rows.length === 0 ? (+ {!loading && !leadVisible && rows.length === 0 && visibleGroups.length === 0 ? (<li className="px-2 py-3 text-xs text-muted-foreground">{t("society.roster.empty")}</li>) : null}{rows.map((agent) => {@@ -562,17 +588,11 @@ export function RosterRail({const isDropTarget = dropId === agent.agentId && dragId !== agent.agentId;return (<li key={agent.agentId} className="relative">- {isDropTarget && !dropAfter ? (+ {isDropTarget && !dropAfter && !groupReady ? (<div aria-hidden className="pointer-events-none absolute inset-x-2 top-0 z-10 h-0.5 -translate-y-1/2 rounded-full bg-sky-400" />) : null}<divdata-agent-id={agent.agentId}- draggable={reorderable}- onDragStart={(event) => onDragStart(event, agent.agentId)}- onDragOver={(event) => onDragOverRow(event, agent.agentId)}- onDragLeave={() => setDropId((current) => (current === agent.agentId ? null : current))}- onDrop={(event) => onDropRow(event, agent.agentId)}- onDragEnd={endDrag}onPointerDown={(event) => onRowPointerDown(event, agent.agentId)}onClickCapture={onRowClickCapture}onKeyDown={(event) => onRowKeyDown(event, agent.agentId)}@@ -586,6 +606,7 @@ export function RosterRail({agent.agentId === activeAgentId && "bg-secondary",hiddenIds.includes(agent.agentId) && "opacity-60",isDropTarget && "bg-secondary ring-1 ring-inset ring-border-strong",+ groupHover?.kind === "agent" && groupHover.id === agent.agentId && groupReady && "ring-2 ring-primary",)}><button type="button" onClick={() => openProfile(agent.agentId)} aria-label={t("society.profile_card.open").replace("{0}", agent.name)} className="shrink-0 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">@@ -606,7 +627,12 @@ export function RosterRail({<RowStatus agent={agent} hasUnread={unread.has(agent.agentId)} /></button></div>- {isDropTarget && dropAfter ? (+ {groupHover?.kind === "agent" && groupHover.id === agent.agentId && (+ <span data-testid="society-group-drop-hint" className="pointer-events-none absolute right-2 top-1 rounded bg-primary px-1.5 py-0.5 text-[10px] text-primary-foreground">+ {t(groupReady ? "society.groups.release_to_group" : "society.groups.hold_to_group")}+ </span>+ )}+ {isDropTarget && dropAfter && !groupReady ? (<div aria-hidden className="pointer-events-none absolute inset-x-2 bottom-0 z-10 h-0.5 translate-y-1/2 rounded-full bg-sky-400" />) : null}</li>@@ -617,6 +643,7 @@ export function RosterRail({{menu && menuAgent && <AgentRosterActions key={menu.agentId} agent={menuAgent} roster={agents} sample={sample}hidden={hiddenIds.includes(menu.agentId)} x={menu.x} y={menu.y} onVisibilityChange={setHidden} onDismiss={closeMenu} />}{profile && <Suspense fallback={null}><AgentProfileDialog key={profile.agentId} agent={profile} sample={sample} onClose={() => setProfileId(null)} /></Suspense>}+ {creatingGroup && <ChatGroupDialog agents={agents} onClose={() => setCreatingGroup(false)} onSaved={(id) => onOpenGroup?.(id)} />}</aside>);}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex bd379bfac6..b4046ab127 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5176,6 +5176,11 @@"mode_pipeline": "Stimme rein und raus"},"society": {+ "groups": {+ "create": "Neues Agent-Team", "edit": "Agent-Team bearbeiten", "description": "Agents in einem Eintrag bündeln. Jeder Agent behält seinen eigenen Chat.",+ "name": "Teamname", "members": "Mitglieder", "cancel": "Abbrechen", "save": "Team speichern", "delete": "Gruppe auflösen", "delete_confirm": "Diese Gruppe auflösen? Die einzelnen Agent-Chats bleiben erhalten.",+ "left_chat": "Linker Chat", "right_chat": "Rechter Chat", "open": "Öffnen", "open_individual": "Einzelchat von {0} öffnen", "missing_member": "Wähle einen verfügbaren Agent für diesen Chat.", "hold_to_group": "Halten zum Gruppieren", "release_to_group": "Loslassen zum Gruppieren"+ },"chat": {"placeholder": "Nachricht an {0}","more": "Mehr",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 07eee448f4..e5debc57aa 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5209,6 +5209,11 @@"mode_pipeline": "voice in and out"},"society": {+ "groups": {+ "create": "New agent team", "edit": "Edit agent team", "description": "Bundle agents in one sidebar entry. Each agent keeps its own conversation.",+ "name": "Team name", "members": "Members", "cancel": "Cancel", "save": "Save team", "delete": "Ungroup", "delete_confirm": "Ungroup these agents? Their individual chats will remain.",+ "left_chat": "Left chat", "right_chat": "Right chat", "open": "Open", "open_individual": "Open {0}'s individual chat", "missing_member": "Select an available agent to view this chat.", "hold_to_group": "Hold to group", "release_to_group": "Release to group"+ },"chat": {"placeholder": "Message {0}","more": "More",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f8e36a6661..7e0ba58582 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5176,6 +5176,11 @@"mode_pipeline": "voz de entrada y salida"},"society": {+ "groups": {+ "create": "Nuevo equipo de agentes", "edit": "Editar equipo de agentes", "description": "Agrupa agentes en una entrada lateral. Cada agente conserva su propio chat.",+ "name": "Nombre del equipo", "members": "Miembros", "cancel": "Cancelar", "save": "Guardar equipo", "delete": "Desagrupar", "delete_confirm": "¿Desagrupar estos agentes? Sus chats individuales permanecerán.",+ "left_chat": "Chat izquierdo", "right_chat": "Chat derecho", "open": "Abrir", "open_individual": "Abrir el chat individual de {0}", "missing_member": "Selecciona un agente disponible para este chat.", "hold_to_group": "Mantén para agrupar", "release_to_group": "Suelta para agrupar"+ },"chat": {"placeholder": "Mensaje a {0}","more": "Más",diff --git a/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts b/jarvis/ui/web/frontend/src/lib/societyChatGroups.tsnew file mode 100644index 0000000000..2d01c60db7--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/societyChatGroups.ts@@ -0,0 +1,46 @@+import { useQuery } from "@tanstack/react-query";++export interface SocietyChatGroup {+ group_id: string;+ name: string;+ members: string[];+ created_ms: number;+ updated_ms: number;+}++async function json<T>(url: string, init?: RequestInit): Promise<T> {+ const response = await fetch(url, init);+ if (!response.ok) {+ const body = await response.json().catch(() => null) as { detail?: unknown } | null;+ throw new Error(typeof body?.detail === "string" ? body.detail : `HTTP ${response.status}`);+ }+ return response.json() as Promise<T>;+}++const body = (data: unknown): RequestInit => ({+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data),+});++export function useSocietyChatGroups(enabled = true) {+ return useQuery({+ queryKey: ["society", "chat-groups"],+ queryFn: async () => (await json<{ groups: SocietyChatGroup[] }>("/api/society/chat-groups")).groups,+ enabled,+ staleTime: 15_000,+ refetchInterval: 10_000,+ });+}++export async function createSocietyChatGroup(name: string, members: string[]) {+ return (await json<{ group: SocietyChatGroup }>("/api/society/chat-groups", body({ name, members }))).group;+}++export async function updateSocietyChatGroup(groupId: string, name: string, members: string[]) {+ return (await json<{ group: SocietyChatGroup }>(`/api/society/chat-groups/${encodeURIComponent(groupId)}`, {+ ...body({ name, members }), method: "PATCH",+ })).group;+}++export async function deleteSocietyChatGroup(groupId: string) {+ await json(`/api/society/chat-groups/${encodeURIComponent(groupId)}`, { method: "DELETE" });+}diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsxindex a75e88e12a..6d1d8305c2 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx@@ -5,12 +5,19 @@ import { LAST_AGENT_STORAGE_KEY } from "./lastAgent";import { SocietyView } from "./SocietyView";const app = vi.hoisted(() => ({ instance: { name: "default", isDev: false } }));+const groupsState = vi.hoisted(() => ({ groups: [] as Array<{ group_id: string; name: string; members: string[] }> }));vi.mock("@/hooks/useAppInstance", () => ({ useAppInstance: () => app.instance }));-beforeEach(() => { app.instance = { name: "default", isDev: false }; });+beforeEach(() => { app.instance = { name: "default", isDev: false }; groupsState.groups = []; });vi.mock("@/lib/mapFullscreen", () => ({ setMapFullscreen: vi.fn(async () => undefined) }));+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQueryClient: () => ({ invalidateQueries: async () => undefined }),+}));vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true }));vi.mock("@/components/society/chat/useModelMenuData", () => ({ useModelMenuData: () => undefined }));+vi.mock("@/lib/societyChatGroups", () => ({ useSocietyChatGroups: () => ({ data: groupsState.groups }) }));+vi.mock("@/components/society/chat/ChatGroupPanel", () => ({ ChatGroupPanel: ({ group, onOpenAgent }: any) => <div data-testid="group-workspace">{group.name}<button onClick={() => onOpenAgent("specialist")}>Open member</button></div> }));vi.mock("@/components/society/data", () => ({ useSocietyRoster: () => ({ data: { sample: false, agents: [{ agentId: "lead", name: "Lead", tier: "lead", state: "idle" },{ agentId: "specialist", name: "Specialist", tier: "specialist", state: "idle" },@@ -19,11 +26,12 @@ vi.mock("@/views/JarvisAgentsView", () => ({ JarvisAgentsView: ({ onSelectAgent,<div data-testid="map"><button onClick={() => onSelectAgent("specialist")}>Map specialist</button><button onClick={onOpenAgents}>Map fallback</button><div data-mars-ui><input aria-label="Mars draft" /></div><div data-mars-mode="player"><button>Player viewport</button></div><div data-mars-mode="follow"><button>Follow viewport</button></div><button onClick={() => onMarsSelectionChange(false)}>Previous world</button><button onClick={() => onMarsSelectionChange(true)}>Mars world</button></div>) }));vi.mock("@/components/society/mars/MarsStationPanel", () => ({ MarsStationPanel: ({ onClose }: any) => <aside aria-label="Mars station"><button onClick={onClose}>Close station</button></aside> }));-vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ agent, embedded, onSelectAgent, onCreate, railHeader }: any) => (+vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ agent, embedded, onSelectAgent, onSelectGroup, onCreate, railHeader }: any) => (<div data-testid="workspace" data-embedded={String(embedded)}>{railHeader}<span>{agent.name}</span><input aria-label="Draft" /><button onClick={() => onSelectAgent("specialist")}>Select specialist</button>+ <button onClick={() => onSelectGroup?.("team")}>Open group</button><button onClick={onCreate}>Create agent</button></div>) }));@@ -43,6 +51,15 @@ it("defaults to the embedded Agents workspace even with a saved legacy ledger prlocalStorage.removeItem("jarvis.agents.mode.v2");});+it("opens a group from the agent rail and returns to an individual member chat", () => {+ groupsState.groups = [{ group_id: "team", name: "Launch team", members: ["specialist"] }];+ render(<SocietyView />);+ fireEvent.click(screen.getByText("Open group"));+ expect(screen.getByTestId("group-workspace").textContent).toContain("Launch team");+ fireEvent.click(screen.getByText("Open member"));+ expect(screen.getByTestId("workspace").textContent).toContain("Specialist");+});+it("switches to Map and back without losing the selected agent or draft", async () => {render(<SocietyView />);fireEvent.click(screen.getByText("Select specialist"));diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsxindex 946bea6877..922add832d 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx@@ -1,5 +1,6 @@import { lazy, Suspense, useCallback, useMemo, useState, useEffect } from "react";import { createPortal } from "react-dom";+import { useQueryClient } from "@tanstack/react-query";import { useSocietyShell } from "@/store/societyShell";import { setMapFullscreen } from "@/lib/mapFullscreen";@@ -13,6 +14,9 @@ import type { PlaceId } from "@/components/society/world/islandLayout";import { useSocietyRoster } from "@/components/society/data";import { RosterRail } from "@/components/society/roster/RosterRail";import { useModelMenuData } from "@/components/society/chat/useModelMenuData";+import { ChatGroupPanel } from "@/components/society/chat/ChatGroupPanel";+import { useSocietyChatStore } from "@/components/society/chat/AgentChatPanel";+import { createSocietyChatGroup, updateSocietyChatGroup, useSocietyChatGroups } from "@/lib/societyChatGroups";import { CanvasActivity } from "@/hooks/useCanvasAwake";import { forgetLastAgentId, rememberLastAgentId, storedLastAgentId } from "./lastAgent";@@ -27,6 +31,7 @@ function isProtectedMarsInteraction(target: EventTarget | null): boolean {}export function SocietyView() {+ const queryClient = useQueryClient();useModelMenuData();const t = useT();useLocaleChunk("society");@@ -35,8 +40,13 @@ export function SocietyView() {const roster = useSocietyRoster();const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);const sample = roster.data?.sample ?? true;+ const groupsQuery = useSocietyChatGroups(!sample);+ const groups = useMemo(() => groupsQuery.data ?? [], [groupsQuery.data]);+ const [openGroupId, setOpenGroupId] = useState<string | null>(null);+ const openGroup = groups.find((group) => group.group_id === openGroupId) ?? null;const [openAgentId, setOpenAgentId] = useState<string | null>(storedLastAgentId);const [creating, setCreating] = useState(false);+ const [groupError, setGroupError] = useState("");const [openPlace, setOpenPlace] = useState<BuildingPlace | null>(null);const openAgent = useMemo(@@ -45,10 +55,46 @@ export function SocietyView() {);const selectAgent = useCallback((agentId: string | null) => {+ setOpenGroupId(null);setOpenAgentId(agentId);if (agentId) rememberLastAgentId(agentId);}, []);+ const selectGroup = useCallback((groupId: string) => {+ useSocietyChatStore.getState().disconnect();+ setOpenGroupId(groupId);+ setOpenAgentId(null);+ }, []);++ const groupAgents = useCallback((sourceId: string, targetId: string) => {+ const source = agents.find((agent) => agent.agentId === sourceId);+ const target = agents.find((agent) => agent.agentId === targetId);+ if (sample || !source || !target || sourceId === targetId) return;+ setGroupError("");+ void createSocietyChatGroup(`${source.name} + ${target.name}`, [sourceId, targetId])+ .then(async (group) => {+ await queryClient.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ selectGroup(group.group_id);+ })+ .catch((error) => setGroupError(error instanceof Error ? error.message : String(error)));+ }, [agents, queryClient, sample, selectGroup]);++ const addAgentToGroup = useCallback((agentId: string, groupId: string) => {+ const group = groups.find((entry) => entry.group_id === groupId);+ if (sample || !group || group.members.includes(agentId)) return;+ setGroupError("");+ void updateSocietyChatGroup(groupId, group.name, [...group.members, agentId])+ .then(async () => {+ await queryClient.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ selectGroup(groupId);+ })+ .catch((error) => setGroupError(error instanceof Error ? error.message : String(error)));+ }, [groups, queryClient, sample, selectGroup]);++ useEffect(() => {+ if (openGroupId && groupsQuery.data && !groups.some((group) => group.group_id === openGroupId)) setOpenGroupId(null);+ }, [groups, groupsQuery.data, openGroupId]);+useEffect(() => {if (openAgentId && agents.length > 0 && !agents.some((agent) => agent.agentId === openAgentId)) {setOpenAgentId(null);@@ -132,6 +178,7 @@ export function SocietyView() {document.body,)}{fullscreenError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{t("society.world.fullscreen_failed")}</p>}+ {groupError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{groupError}</p>}{mode === "world" ? (<div className="relative flex min-h-0 flex-1"><div className="min-w-0 flex-1">@@ -145,12 +192,20 @@ export function SocietyView() {</div>) : null}<div className={mode === "agents" ? "flex min-h-0 flex-1 flex-col" : "hidden"}>- {openAgent ? (+ {openGroup ? (+ <ChatGroupPanel group={openGroup} groups={groups} roster={agents} onOpenAgent={selectAgent} onOpenGroup={selectGroup}+ onCreateAgent={() => setCreating(true)} onDeleted={() => setOpenGroupId(null)}+ onGroupAgents={groupAgents} onAddAgentToGroup={addAgentToGroup} />+ ) : openAgent ? (<AgentCardOverlay embedded agent={openAgent} roster={agents} rosterLoading={roster.isLoading}+ groups={groups} onSelectGroup={selectGroup}+ onGroupAgents={sample ? undefined : groupAgents} onAddAgentToGroup={sample ? undefined : addAgentToGroup}sample={sample} onSelectAgent={selectAgent} onCreate={() => setCreating(true)}onClose={() => setOpenAgentId(null)} />) : (<RosterRail agents={agents} loading={roster.isLoading} sample={sample}+ groups={groups} onOpenGroup={selectGroup}+ onGroupAgents={sample ? undefined : groupAgents} onAddAgentToGroup={sample ? undefined : addAgentToGroup}activeAgentId={null} onOpen={selectAgent} onCreate={() => setCreating(true)} side="left"className="w-full border-0 jarvis-nav-surface" />)}diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 6335862315..5792f8ba22 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport loggingfrom typing import Any+from uuid import uuid4from fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel, ConfigDict, Field@@ -129,6 +130,11 @@ class MessageBody(BaseModel):payload: dict[str, Any] = Field(default_factory=dict)+class ChatGroupBody(BaseModel):+ name: str = Field(min_length=1, max_length=80)+ members: list[str] = Field(min_length=2, max_length=50)++class AssignBody(BaseModel):task: str = Field(min_length=1, max_length=20_000)from_agent: str = "user"@@ -298,6 +304,56 @@ async def archive_agent(agent_id: str, request: Request) -> dict[str, Any]:return {"agent": archived.to_dict()}+async def _valid_group_members(rt: SocietyRuntime, members: list[str]) -> list[str]:+ if len(set(members)) != len(members):+ raise HTTPException(422, "group members must be unique")+ for member_id in members:+ agent = await rt.roster.get(member_id)+ if agent is None or agent.tier == "lead" or agent.state == "archived":+ raise HTTPException(422, f"agent {member_id} is unavailable for a group")+ return members++[email protected]("/chat-groups")+async def list_chat_groups(request: Request) -> dict[str, Any]:+ """List persistent Society group chats and their members."""+ rt = await _runtime(request)+ return {"groups": await rt.store.list_chat_groups()}++[email protected]("/chat-groups")+async def create_chat_group(body: ChatGroupBody, request: Request) -> dict[str, Any]:+ """Create one group chat from available Society agents."""+ rt = await _runtime(request)+ if not body.name.strip():+ raise HTTPException(422, "group name is required")+ members = await _valid_group_members(rt, body.members)+ group = await rt.store.create_chat_group(uuid4().hex, body.name.strip(), members)+ return {"group": group}++[email protected]("/chat-groups/{group_id}")+async def update_chat_group(group_id: str, body: ChatGroupBody, request: Request) -> dict[str, Any]:+ """Rename a group chat and replace its member list."""+ rt = await _runtime(request)+ if not body.name.strip():+ raise HTTPException(422, "group name is required")+ if await rt.store.get_chat_group(group_id) is None:+ raise HTTPException(404, "chat group not found")+ members = await _valid_group_members(rt, body.members)+ return {"group": await rt.store.update_chat_group(group_id, body.name.strip(), members)}++[email protected]("/chat-groups/{group_id}", openapi_extra={"x-jarvis-dangerous": True})+async def delete_chat_group(group_id: str, request: Request) -> dict[str, bool]:+ """Ungroup agents while preserving their individual conversations."""+ rt = await _runtime(request)+ if await rt.store.get_chat_group(group_id) is None:+ raise HTTPException(404, "chat group not found")+ await rt.store.delete_chat_group(group_id)+ return {"deleted": True}++@router.post("/agents/{agent_id}/message", openapi_extra={"x-jarvis-dangerous": True})async def message_agent(agent_id: str, body: MessageBody, request: Request) -> dict[str, Any]:"""Append a message to the agent (user → agent by default). May start a turn."""@@ -623,7 +679,7 @@ async def agent_knowledge(agent_id: str, request: Request) -> dict[str, Any]:last = await rt.store.get_meta(f"review:last:{agent.agent_id}", "")return {"files": files,- "learned_instructions": [e.text[len(PREFIX):] for e in rules(entries)],+ "learned_instructions": [e.text[len(PREFIX) :] for e in rules(entries)],"reviews": rt.conversations.review_counts(agent.agent_id),"last_review": json.loads(last) if last else None,}diff --git a/tests/contract/test_society_substrate.py b/tests/contract/test_society_substrate.pyindex d5a1461d74..742f9b9d7b 100644--- a/tests/contract/test_society_substrate.py+++ b/tests/contract/test_society_substrate.py@@ -19,6 +19,45 @@ class FakeManager:return "m-1"+def test_persistent_group_membership_headless(tmp_path: Path) -> None:+ runtime = SocietyRuntime(+ tmp_path, seed_starter_team=False, mission_manager=lambda: FakeManager()+ )+ app = FastAPI()+ app.include_router(router)+ app.state.society_factory = lambda: runtime+ with TestClient(app) as client:+ for name in ("Scout", "Writer"):+ assert client.post("/api/society/agents", json={"name": name}).status_code == 200+ group = client.post(+ "/api/society/chat-groups",+ json={"name": "Research", "members": ["scout", "writer"]},+ ).json()["group"]+ group_id = group["group_id"]+ sessions = {+ agent["agent_id"]: agent["session_id"]+ for agent in client.get("/api/society/agents").json()["agents"]+ }+ assert client.get("/api/society/chat-groups").json()["groups"][0]["members"] == [+ "scout",+ "writer",+ ]+ assert client.portal is not None+ client.portal.call(runtime.close)++ restarted = SocietyRuntime(tmp_path, seed_starter_team=False)+ app2 = FastAPI()+ app2.include_router(router)+ app2.state.society_factory = lambda: restarted+ with TestClient(app2) as client:+ assert client.get("/api/society/chat-groups").json()["groups"][0]["group_id"] == group_id+ after = {+ agent["agent_id"]: agent["session_id"]+ for agent in client.get("/api/society/agents").json()["agents"]+ }+ assert after == sessions++def test_two_agents_exchange_typed_messages_headless(tmp_path: Path) -> None:manager = FakeManager()runtime = SocietyRuntime(tmp_path, seed_starter_team=False, mission_manager=lambda: manager)@@ -111,7 +150,7 @@ def test_roster_rename_and_archive_keep_identity_headless(tmp_path: Path) -> Nonassert client.delete(f"/api/society/agents/{created['agent_id']}").status_code == 200visible = client.get("/api/society/agents").json()["agents"]assert all(agent["agent_id"] != created["agent_id"] for agent in visible)- archived = client.get(- "/api/society/agents", params={"include_archived": "true"}- ).json()["agents"]+ archived = client.get("/api/society/agents", params={"include_archived": "true"}).json()[+ "agents"+ ]assert any(agent["agent_id"] == created["agent_id"] for agent in archived)diff --git a/tests/unit/society/test_store.py b/tests/unit/society/test_store.pyindex 31fff7eece..fbb487c11a 100644--- a/tests/unit/society/test_store.py+++ b/tests/unit/society/test_store.py@@ -72,6 +72,16 @@ async def test_payload_roundtrips_unicode(store: SocietyStore):assert back.event_id == env.event_id+async def test_chat_group_membership_survives_reopen(store: SocietyStore):+ group = await store.create_chat_group("team", "Research", ["scout", "writer"])+ assert group["members"] == ["scout", "writer"]+ await store.close()+ await store.open()+ assert (await store.list_chat_groups())[0]["members"] == ["scout", "writer"]+ await store.delete_chat_group("team")+ assert await store.list_chat_groups() == []++async def test_cost_and_stats_are_derived(store: SocietyStore):await store.append_and_publish(_say("scout", "quill", "t", cost=0.25))await store.append_and_publish(diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.pyindex 30f512cce7..6087f38caa 100644--- a/tests/unit/ui/web/test_society_routes.py+++ b/tests/unit/ui/web/test_society_routes.py@@ -68,6 +68,44 @@ def test_lead_is_seeded_and_listed(client):assert body["agents"][0]["run_state"] == "idle"+def test_group_membership_keeps_individual_agent_sessions(client):+ c, _ = client+ for name in ("Scout", "Planner", "Writer"):+ assert c.post("/api/society/agents", json={"name": name}).status_code == 200+ created = c.post(+ "/api/society/chat-groups",+ json={"name": "Launch team", "members": ["scout", "planner"]},+ )+ assert created.status_code == 200, created.text+ group = created.json()["group"]+ group_id = group["group_id"]+ assert c.get("/api/society/chat-groups").json()["groups"] == [group]+ assert (+ c.post(+ "/api/society/chat-groups", json={"name": "Too small", "members": ["scout"]}+ ).status_code+ == 422+ )+ before = {+ agent["agent_id"]: agent["session_id"]+ for agent in c.get("/api/society/agents").json()["agents"]+ }+ assert (+ c.patch(+ f"/api/society/chat-groups/{group_id}",+ json={"name": "Delivery team", "members": ["scout", "writer"]},+ ).status_code+ == 200+ )+ assert c.delete(f"/api/society/chat-groups/{group_id}").status_code == 200+ assert c.get("/api/society/chat-groups").json()["groups"] == []+ after = {+ agent["agent_id"]: agent["session_id"]+ for agent in c.get("/api/society/agents").json()["agents"]+ }+ assert after == before++def test_create_derives_focus_and_rules(client):c, _ = clientres = c.post(