Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agents): three-region shell, dense roster and chat header (#905)

Ruben Lütke4a6deeb8361f
diff --git a/dodaios/ui/web/frontend/src/components/society/agentSection.css b/dodaios/ui/web/frontend/src/components/society/agentSection.css
new file mode 100644
index 0000000000..e1d72048e6
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/agentSection.css
@@ -0,0 +1,764 @@
+/*
+ * The Agents section's own design tokens and furniture.
+ *
+ * Everything here is built from the theme tokens in `index.css` (the HSL
+ * roles and the `*-rgb` channel triples). No literal colour is decided in
+ * this file: the chrome stays neutral in both themes, and the only
+ * decorative hue is `--agent-tint`, the colour a person already knows an
+ * agent by (set inline by `agentTint()`), mixed into a token with
+ * `color-mix` so it leans on a surface instead of replacing it.
+ *
+ * Tokens are scoped to `.agent-section` so nothing leaks into the rest of the
+ * app. Dark is the product default; light uses the same rules.
+ */
+
+.agent-section {
+ /* Radius ladder: controls, rows, cards and menus, bubbles, composer, sheets. */
+ --as-radius-xs: 6px;
+ --as-radius-sm: 10px;
+ --as-radius-md: 12px;
+ --as-radius-lg: 18px;
+ --as-radius-xl: 20px;
+ --as-radius-2xl: 24px;
+
+ /* Two-part shadows: an ambient plus a key shadow, both low opacity. */
+ --as-shadow-control: 0 0 0 1px rgb(var(--scrim-rgb) / 0.03), 0 1px 1px rgb(var(--scrim-rgb) / 0.05);
+ --as-shadow-card: 0 1px 2px rgb(var(--scrim-rgb) / 0.06), 0 4px 14px rgb(var(--scrim-rgb) / 0.05);
+ --as-shadow-pop: 0 2px 6px rgb(var(--scrim-rgb) / 0.1), 0 14px 36px rgb(var(--scrim-rgb) / 0.14);
+ --as-sheen-edge: inset 0 1px 0 rgb(var(--sheen-rgb) / 0.04);
+
+ /* Motion: short durations and one stiff, non-bouncing layout curve. */
+ --as-dur-1: 100ms;
+ --as-dur-2: 150ms;
+ --as-dur-3: 200ms;
+ --as-dur-4: 300ms;
+ --as-ease: cubic-bezier(0.2, 0, 0, 1);
+ --as-ease-out: cubic-bezier(0.16, 1, 0.3, 1);
+ --as-spring: cubic-bezier(0.25, 1, 0.5, 1);
+
+ /* The tint falls back to ink when an element has no agent. */
+ --as-tint: var(--agent-tint, hsl(var(--foreground)));
+ --as-tint-wash: color-mix(in srgb, var(--as-tint) 9%, hsl(var(--secondary)));
+ --as-tint-ink: color-mix(in srgb, var(--as-tint) 62%, hsl(var(--foreground)));
+
+ /* Hover-only affordances read this (0 hidden, 1 shown). */
+ --as-reveal: 0;
+}
+
+.dark .agent-section {
+ --as-shadow-control: 0 0 0 1px rgb(var(--scrim-rgb) / 0.3), 0 1px 1px rgb(var(--scrim-rgb) / 0.35);
+ --as-shadow-card: 0 1px 2px rgb(var(--scrim-rgb) / 0.35), 0 6px 18px rgb(var(--scrim-rgb) / 0.3);
+ --as-shadow-pop: 0 2px 8px rgb(var(--scrim-rgb) / 0.4), 0 18px 44px rgb(var(--scrim-rgb) / 0.5);
+ --as-sheen-edge: inset 0 1px 0 rgb(var(--sheen-rgb) / 0.05);
+ --as-tint-wash: color-mix(in srgb, var(--as-tint) 12%, hsl(var(--secondary)));
+ --as-tint-ink: color-mix(in srgb, var(--as-tint) 72%, hsl(var(--foreground)));
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .agent-section {
+ --as-dur-1: 0ms;
+ --as-dur-2: 0ms;
+ --as-dur-3: 0ms;
+ --as-dur-4: 0ms;
+ }
+}
+
+/* --- reveal: hover-only affordances, always visible without a hover pointer */
+
+.as-reveal-host:hover,
+.as-reveal-host:focus-within,
+.as-reveal-host[data-menu-open="true"] {
+ --as-reveal: 1;
+}
+
+.as-reveal {
+ opacity: var(--as-reveal);
+ transition: opacity var(--as-dur-2) var(--as-ease);
+}
+
+@media (hover: none) {
+ .agent-section,
+ .as-reveal-host {
+ --as-reveal: 1;
+ }
+}
+
+/* --- the three-region frame ---------------------------------------------- */
+
+.as-shell {
+ position: relative;
+ display: grid;
+ min-height: 0;
+ min-width: 0;
+ flex: 1;
+ grid-template-rows: minmax(0, 1fr);
+ transition: grid-template-columns var(--as-dur-3) var(--as-spring);
+}
+
+.as-shell[data-resizing="true"] {
+ transition: none;
+ cursor: col-resize;
+ user-select: none;
+}
+
+.as-region {
+ position: relative;
+ display: flex;
+ min-width: 0;
+ min-height: 0;
+ flex-direction: column;
+}
+
+.as-stage {
+ background: hsl(var(--background));
+}
+
+/* The pane's content draws its own edge (the details rail has a left border). */
+.as-pane {
+ background: hsl(var(--sidebar));
+}
+
+.as-pane[hidden] {
+ display: none;
+}
+
+/* A pane the window had to close comes back as a sheet over the chat. */
+.as-pane[data-overlay="true"] {
+ position: absolute;
+ inset: 0 0 0 auto;
+ z-index: 30;
+ box-shadow: var(--as-shadow-pop);
+ animation: as-sheet-in var(--as-dur-3) var(--as-ease-out);
+}
+
+.as-roster-overlay {
+ position: absolute;
+ inset: 0 auto 0 0;
+ z-index: 30;
+ box-shadow: var(--as-shadow-pop);
+ animation: as-sheet-in-left var(--as-dur-3) var(--as-ease-out);
+}
+
+@keyframes as-sheet-in {
+ from {
+ opacity: 0;
+ transform: translateX(12px);
+ }
+}
+
+@keyframes as-sheet-in-left {
+ from {
+ opacity: 0;
+ transform: translateX(-12px);
+ }
+}
+
+/* The drag handle sits on a column edge: a wide hit zone, a hairline that
+ only shows while hovered or dragged. */
+.as-resizer {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ z-index: 20;
+ width: 9px;
+ cursor: col-resize;
+ touch-action: none;
+ background: transparent;
+ border: 0;
+ padding: 0;
+}
+
+.as-resizer[data-edge="right"] {
+ right: -5px;
+}
+
+.as-resizer[data-edge="left"] {
+ left: -5px;
+}
+
+.as-resizer::after {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 4px;
+ width: 1px;
+ background: hsl(var(--border-strong));
+ opacity: 0;
+ transition: opacity var(--as-dur-2) var(--as-ease);
+}
+
+.as-resizer:hover::after,
+.as-resizer:focus-visible::after,
+.as-resizer[data-active="true"]::after {
+ opacity: 1;
+}
+
+.as-resizer:focus-visible {
+ outline: none;
+}
+
+/* --- the chat header ------------------------------------------------------ */
+
+.as-header {
+ display: flex;
+ height: 52px;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 10px;
+ padding: 0 10px 0 14px;
+ border-bottom: 1px solid hsl(var(--border));
+ background: hsl(var(--background));
+ container: as-header / inline-size;
+}
+
+/* Control labels show once the header has room; the icon stays either way. */
+.as-header-label {
+ display: none;
+}
+
+@container as-header (min-width: 600px) {
+ .as-header-label {
+ display: inline;
+ }
+}
+
+.as-header-control {
+ display: inline-flex;
+ height: 30px;
+ min-width: 0;
+ align-items: center;
+ gap: 6px;
+ border-radius: var(--as-radius-xs);
+ padding: 0 8px;
+ font-size: 12px;
+ color: hsl(var(--muted-foreground));
+ transition:
+ background-color var(--as-dur-2) var(--as-ease),
+ color var(--as-dur-2) var(--as-ease);
+}
+
+.as-header-control:hover:not(:disabled),
+.as-header-control[aria-expanded="true"],
+.as-header-control[aria-pressed="true"] {
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground));
+}
+
+.as-header-control:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--ring));
+}
+
+.as-header-control:disabled {
+ opacity: 0.5;
+}
+
+/* The brain picker keeps its own trigger; the header only frames it. */
+.as-header-slot {
+ display: flex;
+ min-width: 0;
+ max-width: 260px;
+ height: 30px;
+ align-items: center;
+}
+
+/* --- menus and popovers ---------------------------------------------------- */
+
+.as-menu {
+ border: 1px solid hsl(var(--border));
+ border-radius: var(--as-radius-md);
+ background: hsl(var(--popover));
+ color: hsl(var(--popover-foreground));
+ box-shadow: var(--as-shadow-pop), var(--as-sheen-edge);
+ padding: 4px;
+ transform-origin: top;
+ animation: as-pop-in var(--as-dur-2) var(--as-ease-out);
+}
+
+.as-menu-item {
+ display: flex;
+ width: 100%;
+ min-height: 30px;
+ align-items: flex-start;
+ gap: 10px;
+ border-radius: 8px;
+ padding: 7px 10px;
+ text-align: left;
+ font-size: 13px;
+ line-height: 18px;
+}
+
+.as-menu-item:hover:not(:disabled),
+.as-menu-item:focus-visible {
+ background: hsl(var(--secondary));
+ outline: none;
+}
+
+.as-menu-item:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+@keyframes as-pop-in {
+ from {
+ opacity: 0;
+ transform: translateY(-4px) scale(0.99);
+ }
+}
+
+/* --- live status text ------------------------------------------------------ */
+
+.as-shimmer {
+ background-image: linear-gradient(
+ 90deg,
+ hsl(var(--muted-foreground)) 0%,
+ hsl(var(--muted-foreground)) 35%,
+ hsl(var(--foreground-strong)) 50%,
+ hsl(var(--muted-foreground)) 65%,
+ hsl(var(--muted-foreground)) 100%
+ );
+ background-size: 250% 100%;
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ animation: as-shimmer 2.2s linear infinite;
+}
+
+@keyframes as-shimmer {
+ from {
+ background-position: 100% 0;
+ }
+ to {
+ background-position: -150% 0;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .as-shimmer {
+ animation: none;
+ background-image: none;
+ color: hsl(var(--muted-foreground));
+ }
+}
+
+/* --- roster ---------------------------------------------------------------- */
+
+.as-roster {
+ background: hsl(var(--sidebar));
+}
+
+.as-row {
+ position: relative;
+ display: flex;
+ height: 54px;
+ width: 100%;
+ align-items: center;
+ gap: 8px;
+ border-radius: var(--as-radius-sm);
+ padding: 0 8px;
+ text-align: left;
+ transition: background-color var(--as-dur-2) var(--as-ease);
+}
+
+.as-row:hover {
+ background: hsl(var(--secondary));
+}
+
+.as-row[data-active="true"] {
+ background: var(--as-tint-wash);
+}
+
+/* A short tint bar marks the open agent, so selection never relies on colour
+ of the whole row alone. */
+.as-row[data-active="true"]::before {
+ content: "";
+ position: absolute;
+ left: 0;
+ top: 50%;
+ height: 20px;
+ width: 3px;
+ margin-top: -10px;
+ border-radius: 0 3px 3px 0;
+ background: var(--as-tint);
+}
+
+.as-row[data-dragging="true"] {
+ opacity: 0.4;
+}
+
+.as-row[data-drop="true"] {
+ background: hsl(var(--secondary));
+ box-shadow: inset 0 0 0 1px hsl(var(--border-strong));
+}
+
+.as-row[data-group-ready="true"] {
+ box-shadow: inset 0 0 0 2px hsl(var(--primary));
+}
+
+.as-row-name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 13px;
+ line-height: 18px;
+ font-weight: 500;
+ color: hsl(var(--foreground));
+}
+
+.as-row-time {
+ flex-shrink: 0;
+ font-size: 11px;
+ line-height: 16px;
+ font-variant-numeric: tabular-nums;
+ color: hsl(var(--muted-foreground));
+}
+
+.as-row-preview {
+ display: block;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ line-height: 17px;
+ color: hsl(var(--muted-foreground));
+}
+
+.as-row-preview[data-kind="waiting"] {
+ color: hsl(var(--warning));
+}
+
+.as-preview-tag {
+ font-weight: 500;
+ color: var(--as-tint-ink);
+}
+
+.as-row-preview[data-kind="waiting"] .as-preview-tag {
+ color: inherit;
+}
+
+/* The drop line between rows while reordering. */
+.as-drop-line {
+ pointer-events: none;
+ position: absolute;
+ left: 8px;
+ right: 8px;
+ z-index: 10;
+ height: 2px;
+ border-radius: 999px;
+ background: hsl(var(--accent));
+}
+
+/* --- the avatar and its corner status ------------------------------------- */
+
+.as-avatar {
+ position: relative;
+ display: inline-flex;
+ flex-shrink: 0;
+}
+
+.as-status {
+ position: absolute;
+ right: -1px;
+ bottom: -1px;
+ display: grid;
+ place-items: center;
+ width: 12px;
+ height: 12px;
+ border-radius: 999px;
+ background: hsl(var(--sidebar));
+}
+
+.as-status::after {
+ content: "";
+ width: 8px;
+ height: 8px;
+ border-radius: 999px;
+ background: hsl(var(--muted-foreground));
+}
+
+.as-status[data-status="working"]::after {
+ background: hsl(var(--success));
+ animation: as-breathe 1.6s ease-in-out infinite;
+}
+
+.as-status[data-status="unread"]::after {
+ background: hsl(var(--accent));
+}
+
+.as-status[data-status="paused"]::after {
+ background: hsl(var(--border-strong));
+}
+
+/* Needs you: a ring, larger than a dot, so it reads before colour does. */
+.as-status[data-status="needs-you"] {
+ width: 15px;
+ height: 15px;
+ right: -3px;
+ bottom: -3px;
+}
+
+.as-status[data-status="needs-you"]::after {
+ width: 11px;
+ height: 11px;
+ background: hsl(var(--sidebar));
+ box-shadow: inset 0 0 0 3px hsl(var(--warning));
+}
+
+@keyframes as-breathe {
+ 50% {
+ opacity: 0.45;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .as-status[data-status="working"]::after {
+ animation: none;
+ }
+}
+
+/* The unread marker at the end of a row. */
+.as-unread-badge {
+ display: inline-flex;
+ height: 16px;
+ min-width: 16px;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+ border-radius: 999px;
+ padding: 0 5px;
+ font-size: 10px;
+ font-weight: 600;
+ line-height: 1;
+ background: hsl(var(--accent));
+ color: hsl(var(--accent-foreground));
+}
+
+.as-shortcut-badge {
+ position: absolute;
+ left: -4px;
+ top: -4px;
+ display: grid;
+ place-items: center;
+ width: 16px;
+ height: 16px;
+ border-radius: 5px;
+ font-size: 10px;
+ font-weight: 600;
+ background: hsl(var(--foreground));
+ color: hsl(var(--background));
+ box-shadow: var(--as-shadow-control);
+}
+
+/* --- pinned tiles ---------------------------------------------------------- */
+
+.as-pins {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 2px;
+}
+
+.as-pin {
+ position: relative;
+ display: flex;
+ min-width: 0;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ border-radius: var(--as-radius-sm);
+ padding: 8px 2px 6px;
+ transition: background-color var(--as-dur-2) var(--as-ease);
+ animation: as-pin-in var(--as-dur-3) var(--as-spring);
+}
+
+.as-pin:hover {
+ background: hsl(var(--secondary));
+}
+
+.as-pin[data-active="true"] {
+ background: var(--as-tint-wash);
+}
+
+.as-pin-name {
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 11px;
+ line-height: 14px;
+ color: hsl(var(--muted-foreground));
+}
+
+.as-pin[data-active="true"] .as-pin-name {
+ color: hsl(var(--foreground));
+}
+
+@keyframes as-pin-in {
+ from {
+ opacity: 0;
+ transform: scale(0.85);
+ }
+}
+
+/* --- section headings, filter and search ---------------------------------- */
+
+.as-section-head {
+ display: flex;
+ height: 28px;
+ align-items: center;
+ gap: 6px;
+ padding: 0 10px;
+ font-size: 11px;
+ font-weight: 500;
+ letter-spacing: 0.02em;
+ color: hsl(var(--muted-foreground));
+}
+
+.as-section-count {
+ font-variant-numeric: tabular-nums;
+ color: hsl(var(--faint-foreground));
+}
+
+.as-seg {
+ display: flex;
+ gap: 2px;
+ border-radius: 8px;
+ padding: 2px;
+ background: hsl(var(--secondary));
+}
+
+.as-seg-item {
+ display: inline-flex;
+ min-width: 0;
+ flex: 1;
+ height: 24px;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ border-radius: 6px;
+ padding: 0 6px;
+ font-size: 12px;
+ color: hsl(var(--muted-foreground));
+ white-space: nowrap;
+ transition:
+ background-color var(--as-dur-2) var(--as-ease),
+ color var(--as-dur-2) var(--as-ease);
+}
+
+.as-seg-item:hover {
+ color: hsl(var(--foreground));
+}
+
+.as-seg-item[aria-pressed="true"],
+.as-seg-item[aria-selected="true"] {
+ background: hsl(var(--background));
+ color: hsl(var(--foreground-strong));
+ box-shadow: var(--as-shadow-control);
+}
+
+.as-seg-item:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--ring));
+}
+
+.as-seg-count {
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ color: hsl(var(--warning));
+}
+
+/* The primary action wears ink, not a hue. */
+.as-ink-button {
+ display: inline-flex;
+ height: 28px;
+ align-items: center;
+ gap: 5px;
+ border-radius: 8px;
+ padding: 0 10px;
+ font-size: 12px;
+ font-weight: 500;
+ background: hsl(var(--primary));
+ color: hsl(var(--primary-foreground));
+ box-shadow: var(--as-shadow-control);
+ transition:
+ opacity var(--as-dur-2) var(--as-ease),
+ transform var(--as-dur-1) var(--as-ease);
+}
+
+.as-ink-button:hover {
+ opacity: 0.9;
+}
+
+.as-ink-button:active {
+ transform: scale(0.98);
+}
+
+.as-ink-button:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--background)), 0 0 0 4px hsl(var(--ring));
+}
+
+.as-ghost-button {
+ display: inline-flex;
+ height: 28px;
+ min-width: 28px;
+ align-items: center;
+ justify-content: center;
+ gap: 5px;
+ border-radius: 8px;
+ padding: 0 8px;
+ font-size: 12px;
+ color: hsl(var(--muted-foreground));
+ transition:
+ background-color var(--as-dur-2) var(--as-ease),
+ color var(--as-dur-2) var(--as-ease);
+}
+
+.as-ghost-button:hover:not(:disabled) {
+ background: hsl(var(--secondary));
+ color: hsl(var(--foreground));
+}
+
+.as-ghost-button:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px hsl(var(--ring));
+}
+
+.as-ghost-button:disabled {
+ opacity: 0.45;
+}
+
+/* --- hover card ------------------------------------------------------------ */
+
+.as-hovercard {
+ position: fixed;
+ z-index: 90;
+ width: 280px;
+ border: 1px solid hsl(var(--border));
+ border-radius: var(--as-radius-md);
+ background: hsl(var(--popover));
+ color: hsl(var(--popover-foreground));
+ box-shadow: var(--as-shadow-pop), var(--as-sheen-edge);
+ padding: 14px;
+ pointer-events: none;
+ animation: as-pop-in var(--as-dur-2) var(--as-ease-out);
+}
+
+.as-hovercard .as-status {
+ background: hsl(var(--popover));
+}
+
+/* --- empty states ---------------------------------------------------------- */
+
+.as-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 14px 12px;
+ font-size: 12px;
+ line-height: 18px;
+ color: hsl(var(--muted-foreground));
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/agentSection.test.ts b/dodaios/ui/web/frontend/src/components/society/agentSection.test.ts
new file mode 100644
index 0000000000..d7862d0af4
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/agentSection.test.ts
@@ -0,0 +1,72 @@
+/**
+ * The Agents frame decides no colour of its own (index.css: never write a
+ * literal colour) and honours reduced motion. Both are read straight from the
+ * source, so a regression fails here rather than in one theme only.
+ */
+import { readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+const SOCIETY = join(__dirname);
+const FILES = [
+ join(SOCIETY, "agentSection.css"),
+ join(SOCIETY, "agentTint.ts"),
+ join(SOCIETY, "card", "agentChatLayout.css"),
+ join(SOCIETY, "card", "AgentChatLayout.tsx"),
+ join(SOCIETY, "card", "AgentCardOverlay.tsx"),
+ join(SOCIETY, "card", "AgentHeader.tsx"),
+ join(SOCIETY, "card", "approvalModes.ts"),
+ join(SOCIETY, "card", "shellLayout.ts"),
+ ...readdirSync(join(SOCIETY, "roster"))
+ .filter((name) => /\.(tsx?|css)$/.test(name) && !/\.test\./.test(name))
+ .map((name) => join(SOCIETY, "roster", name)),
+ join(SOCIETY, "..", "..", "views", "society", "SocietyView.tsx"),
+];
+
+const PALETTE = "slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose";
+const LITERALS: [string, RegExp][] = [
+ ["hex colour", /#[0-9a-fA-F]{3,8}\b(?![\w-])/],
+ ["rgb() with numbers", /\brgba?\(\s*\d/],
+ ["hsl() with numbers", /\bhsla?\(\s*\d/],
+ ["Tailwind palette colour", new RegExp(`\\b(?:bg|text|ring|border|fill|stroke|from|to|via|outline|shadow)-(?:${PALETTE})-\\d{2,3}\\b`)],
+ ["black or white utility", /\b(?:bg|text|ring|border)-(?:black|white)\b/],
+];
+
+function stripComments(source: string): string {
+ return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`])\/\/[^\n]*/g, "$1");
+}
+
+describe("Agents section design rules", () => {
+ it("writes no literal colour anywhere in the frame", () => {
+ const offences: string[] = [];
+ for (const file of FILES) {
+ const text = stripComments(readFileSync(file, "utf8"));
+ for (const [label, pattern] of LITERALS) {
+ const match = pattern.exec(text);
+ if (match) offences.push(`${file.split(/[\\/]/).slice(-2).join("/")}: ${label} "${match[0]}"`);
+ }
+ }
+ expect(offences).toEqual([]);
+ });
+
+ it("stops every section animation under reduced motion", () => {
+ const css = readFileSync(join(SOCIETY, "agentSection.css"), "utf8");
+ const reduced = [...css.matchAll(/@media \(prefers-reduced-motion: reduce\) \{([\s\S]*?)\n\}/g)].map((m) => m[1]).join("\n");
+ for (const token of ["--as-dur-1", "--as-dur-2", "--as-dur-3", "--as-dur-4"]) {
+ expect(reduced).toMatch(new RegExp(`${token}: 0ms`));
+ }
+ expect(reduced).toMatch(/\.as-shimmer \{[\s\S]*animation: none/);
+ expect(reduced).toMatch(/\.as-status\[data-status="working"\]::after \{[\s\S]*animation: none/);
+ // Every keyframe animation in the file runs on a duration token, or is switched off above.
+ for (const match of css.matchAll(/animation: ([^;]+);/g)) {
+ const value = match[1];
+ if (value === "none") continue;
+ expect(/var\(--as-dur-\d\)/.test(value) || /as-shimmer|as-breathe/.test(value), value).toBe(true);
+ }
+ });
+
+ it("keeps hover-only affordances visible without a hover pointer", () => {
+ const css = readFileSync(join(SOCIETY, "agentSection.css"), "utf8");
+ expect(css).toMatch(/@media \(hover: none\) \{[\s\S]*--as-reveal: 1/);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/agentTint.ts b/dodaios/ui/web/frontend/src/components/society/agentTint.ts
new file mode 100644
index 0000000000..36b1a27d7a
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/agentTint.ts
@@ -0,0 +1,24 @@
+import type { CSSProperties } from "react";
+
+import { agentColor } from "./AgentSwatch";
+import type { SocietyAgent } from "./data";
+
+type TintAgent = Pick<SocietyAgent, "figure" | "palette" | "name"> & Partial<Pick<SocietyAgent, "agentId" | "tier">>;
+
+/**
+ * The per-agent tint as a CSS custom property.
+ *
+ * The Agents section keeps its chrome neutral; the only decorative hue is the
+ * colour a person already knows an agent by (its companion colour, or the
+ * lead's gold). `agentSection.css` mixes `--agent-tint` into theme tokens with
+ * `color-mix`, so a tint never replaces a surface token, it only leans on it.
+ */
+export function agentTint(agent: TintAgent | null | undefined): CSSProperties {
+ if (!agent) return {};
+ try {
+ return { "--agent-tint": agentColor(agent) } as CSSProperties;
+ } catch {
+ // An identity without a resolvable look keeps the neutral chrome.
+ return {};
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.test.tsx
new file mode 100644
index 0000000000..762bcbfd1a
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.test.tsx
@@ -0,0 +1,91 @@
+/**
+ * The workspace wires the frame together: roster, header and chat in one
+ * grid, the brain picker handed from the composer to the header, and the
+ * keyboard shortcuts live only while the section is on screen.
+ */
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { SocietyAgent } from "../data";
+import { useHeaderModelSlot } from "./headerModelSlot";
+import { AgentCardOverlay } from "./AgentCardOverlay";
+
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true, useUiLanguage: () => "en" }));
+vi.mock("./OptionsRail", () => ({ OptionsRail: ({ agent }: { agent: SocietyAgent }) => <aside aria-label="Details">{agent.name}</aside> }));
+vi.mock("../chat/AgentModelPicker", () => ({ AgentModelPicker: () => <button type="button">brain</button> }));
+const renders = vi.hoisted(() => ({ chat: 0 }));
+vi.mock("../chat/AgentChatPanel", async () => {
+ const { create } = await import("zustand");
+ const store = create(() => ({ busy: false, activeSessionId: null, sessions: [], loadSessions: async () => undefined }));
+ function ChatProbe({ agent }: { agent: SocietyAgent }) {
+ renders.chat += 1;
+ const slot = useHeaderModelSlot();
+ return <div data-testid="chat-probe" data-header-picker={slot ? "yes" : "no"}>{agent.name}</div>;
+ }
+ return { AgentChatPanel: ChatProbe, useSocietyChatStore: store };
+});
+
+function agent(over: Partial<SocietyAgent> & Pick<SocietyAgent, "agentId" | "name">): SocietyAgent {
+ return {
+ title: "Title", description: "", tier: "specialist", provider: "", providerLabel: "", model: "", effort: "",
+ figure: null, palette: { primary: "#000", secondary: "#111", accent: "#222" }, grantMode: "all", toolGrants: [],
+ focus: [], denies: [], approvalRules: { requireApproval: [], alwaysAllow: [] }, permissionCeiling: "ask",
+ dailyBudgetUsd: 0, checkpoint: "idle", state: "idle", lifecycle: "active", createdMs: 0, maxConcurrentRuns: 1,
+ workspaceDir: "", wikiNamespace: "", chatSessionId: null, routines: [],
+ stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },
+ ...over,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ localStorage.clear();
+ vi.unstubAllGlobals();
+});
+
+function mount(props: Partial<Parameters<typeof AgentCardOverlay>[0]> = {}) {
+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ providers: [] }) })));
+ const roster = [agent({ agentId: "lead", name: "Lead", tier: "lead" }), agent({ agentId: "a", name: "Alpha" }), agent({ agentId: "b", name: "Beta" })];
+ const onSelectAgent = vi.fn();
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(<QueryClientProvider client={client}>
+ <AgentCardOverlay embedded agent={roster[1]} roster={roster} onSelectAgent={onSelectAgent} onClose={() => undefined} {...props} />
+ </QueryClientProvider>);
+ return { onSelectAgent };
+}
+
+describe("AgentCardOverlay", () => {
+ it("renders roster, header, chat and details once, without a render storm", () => {
+ renders.chat = 0;
+ mount();
+ expect(screen.getByTestId("society-roster-rail")).toBeTruthy();
+ expect(screen.getByTestId("agent-header-name").textContent).toBe("Alpha");
+ expect(screen.getByRole("complementary", { name: "Details" }).textContent).toBe("Alpha");
+ expect(renders.chat).toBeLessThan(5);
+ });
+
+ it("moves the brain picker into the header for a specialist", () => {
+ mount();
+ expect(screen.getByTestId("chat-probe").dataset.headerPicker).toBe("yes");
+ expect(screen.getByRole("button", { name: "brain" })).toBeTruthy();
+ });
+
+ it("leaves the lead's chat its own model controls", () => {
+ const roster = [agent({ agentId: "lead", name: "Lead", tier: "lead" })];
+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}) })));
+ const client = new QueryClient();
+ render(<QueryClientProvider client={client}><AgentCardOverlay embedded agent={roster[0]} roster={roster} onClose={() => undefined} /></QueryClientProvider>);
+ expect(screen.getByTestId("chat-probe").dataset.headerPicker).toBe("no");
+ });
+
+ it("steps to the next agent with Alt + Arrow Down only while active", () => {
+ const { onSelectAgent } = mount();
+ fireEvent.keyDown(window, { key: "ArrowDown", altKey: true });
+ expect(onSelectAgent).toHaveBeenCalledWith("b");
+ cleanup();
+ const inactive = mount({ active: false });
+ fireEvent.keyDown(window, { key: "ArrowDown", altKey: true });
+ expect(inactive.onSelectAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
index 4bbd307d99..7ef158a112 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx
@@ -1,24 +1,26 @@
/**
- * The agent card is a chat workspace: agent selection, conversation and actions.
- * The workspace can be embedded in the section or opened as a modal.
- * Radix Dialog provides focus containment and Escape-to-close.
+ * The agent workspace: the roster, the open agent's chat under its header,
+ * and its details pane, in the three-region frame of `AgentChatLayout`.
+ * It can be embedded in the section or opened as a modal; Radix Dialog
+ * provides focus containment and Escape-to-close for the modal.
*/
-import type { ReactNode } from "react";
+import { useState, type ReactNode } from "react";
import * as Dialog from "@radix-ui/react-dialog";
import { X } from "lucide-react";
-import { Badge } from "@/components/ui/badge";
import { useLocaleChunk, useT } from "@/i18n";
import { societyDisplayName } from "@/lib/societyDisplayName";
import { useEventStore } from "@/store/events";
-import { AgentSwatch } from "../AgentSwatch";
import type { SocietyAgent } from "../data";
-import { AgentChatPanel } from "../chat/AgentChatPanel";
+import { AgentChatPanel, useSocietyChatStore } from "../chat/AgentChatPanel";
import { RosterRail } from "../roster/RosterRail";
+import { useRosterActivity } from "../roster/useRosterActivity";
import type { SocietyChatGroup } from "@/lib/societyChatGroups";
import { OptionsRail } from "./OptionsRail";
import { AgentChatLayout } from "./AgentChatLayout";
+import { AgentHeader } from "./AgentHeader";
+import { HeaderModelSlotContext } from "./headerModelSlot";
export interface AgentCardOverlayProps {
agent: SocietyAgent | null;
@@ -43,6 +45,8 @@ export interface AgentCardOverlayProps {
embedded?: boolean;
/** Drawn at the top of the agent list, in the gray column. */
railHeader?: ReactNode;
+ /** The section-wide roster shortcuts listen while this is true (the section is on screen). */
+ active?: boolean;
}
export function AgentCardOverlay({
@@ -60,76 +64,67 @@ export function AgentCardOverlay({
onClose,
embedded = false,
railHeader,
+ active = true,
}: AgentCardOverlayProps) {
const t = useT();
useLocaleChunk("society");
const assistantName = useEventStore((s) => s.assistantName);
const displayName = agent ? societyDisplayName(agent, assistantName) : "";
- // The modal keeps a real dialog title plus its close control. The embedded
- // workspace hides this row entirely: the left rail already marks the active
- // agent and the right rail names it, so the row was a second, boring band.
+ const activity = useRosterActivity(roster, useSocietyChatStore);
+ const [modelSaving, setModelSaving] = useState(false);
const Title = embedded ? "h2" : Dialog.Title;
const Description = embedded ? "p" : Dialog.Description;
- const content = (
+ const content = agent ? (
<>
- {agent ? (
- <>
- {!embedded && (
- <header className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-1.5">
- <div data-testid="agent-card-identity" className="flex min-w-0 flex-1 items-center gap-2">
- <AgentSwatch agent={agent} size={32} />
- <div className="min-w-0 flex-1">
- <Title className="truncate font-display text-base font-semibold tracking-tight text-foreground">
- {displayName}
- </Title>
- <Description className="truncate text-xs text-muted-foreground">
- {agent.title}
- </Description>
- </div>
- </div>
- <Badge variant="outline">{t(`society.state.${agent.state}`)}</Badge>
- <button type="button" onClick={onClose} aria-label={t("society.card.close")}
- className="rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground">
- <X className="h-4 w-4" aria-hidden />
- </button>
- </header>
- )}
- <div className="agent-card-columns grid min-h-0 flex-1 grid-cols-[minmax(240px,300px)_minmax(0,1fr)]">
- <RosterRail
- agents={roster}
- groups={groups}
- onOpenGroup={onSelectGroup}
- onGroupAgents={onGroupAgents}
- onAddAgentToGroup={onAddAgentToGroup}
- loading={rosterLoading}
- teamsPending={teamsPending}
- sample={sample}
- activeAgentId={agent.agentId}
- onOpen={(id) => { if (id !== agent.agentId) onSelectAgent?.(id); }}
- onCreate={() => onCreate?.()}
- side="left"
- className="w-full border-0 jarvis-nav-surface"
- header={railHeader}
- />
- {/* Inner reading pane: same ground, divider and corner as the
- window sheet, but WITHOUT its top border. Top + left borders
- meet exactly at the rounded corner, and on a fractional grid
- seam that joint rasterizes as a small step. The gray caption
- above already separates by ground, so one border is enough. */}
- <AgentChatLayout options={<OptionsRail agent={agent} onRetired={onClose} sample={sample} />}>
- <section
- className="flex min-h-0 min-w-0 flex-col"
- aria-label={t("society.card.chat")}
- data-testid="agent-card-chat"
- >
- <AgentChatPanel key={agent.agentId} agent={agent} roster={roster} />
- </section>
- </AgentChatLayout>
+ {!embedded && (
+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-1.5">
+ <div data-testid="agent-card-identity" className="min-w-0 flex-1">
+ <Title className="truncate font-display text-sm font-semibold tracking-tight text-foreground">{displayName}</Title>
+ <Description className="sr-only">{agent.title}</Description>
</div>
- </>
- ) : null}
+ <button type="button" onClick={onClose} aria-label={t("society.card.close")}
+ className="rounded-md p-1.5 text-muted-foreground hover:bg-secondary hover:text-foreground">
+ <X className="h-4 w-4" aria-hidden />
+ </button>
+ </div>
+ )}
+ <AgentChatLayout
+ resetKey={agent.agentId}
+ roster={({ collapsed, onToggleCollapsed }) => (
+ <RosterRail
+ agents={roster}
+ groups={groups}
+ onOpenGroup={onSelectGroup}
+ onGroupAgents={onGroupAgents}
+ onAddAgentToGroup={onAddAgentToGroup}
+ loading={rosterLoading}
+ teamsPending={teamsPending}
+ sample={sample}
+ activeAgentId={agent.agentId}
+ onOpen={(id) => { if (id !== agent.agentId) onSelectAgent?.(id); }}
+ onCreate={() => onCreate?.()}
+ side="left"
+ className="w-full border-0"
+ header={railHeader}
+ activity={activity}
+ collapsed={collapsed}
+ onToggleCollapsed={onToggleCollapsed}
+ keyboard={active}
+ />
+ )}
+ header={(detailsToggle) => (
+ <AgentHeader agent={agent} sample={sample} detailsToggle={detailsToggle} onModelSavingChange={setModelSaving} />
+ )}
+ options={<OptionsRail agent={agent} onRetired={onClose} sample={sample} />}
+ >
+ <section className="flex min-h-0 min-w-0 flex-1 flex-col" aria-label={t("society.card.chat")} data-testid="agent-card-chat">
+ <HeaderModelSlotContext.Provider value={agent.tier === "lead" ? null : { saving: modelSaving }}>
+ <AgentChatPanel key={agent.agentId} agent={agent} roster={roster} />
+ </HeaderModelSlotContext.Provider>
+ </section>
+ </AgentChatLayout>
</>
- );
+ ) : null;
if (embedded) {
return <div data-testid="agent-card" className="agent-card-workspace flex min-h-0 flex-1 flex-col overflow-hidden bg-card">{content}</div>;
}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.test.tsx
new file mode 100644
index 0000000000..b713836f84
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.test.tsx
@@ -0,0 +1,119 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { AgentChatLayout } from "./AgentChatLayout";
+import { CHAT_MIN, ROSTER_DEFAULT, ROSTER_RAIL } from "./shellLayout";
+
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true }));
+
+const STORE = "society.shell.layout.v1";
+
+afterEach(() => {
+ cleanup();
+ localStorage.clear();
+ vi.restoreAllMocks();
+});
+
+/** jsdom has no layout: pretend the frame is `width` pixels wide. */
+function frameWidth(width: number) {
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ const w = this.dataset.testid === "agent-shell" ? width : 0;
+ return { x: 0, y: 0, top: 0, left: 0, right: w, bottom: 600, width: w, height: 600, toJSON: () => ({}) } as DOMRect;
+ });
+}
+
+function mount() {
+ const rosterState: { collapsed?: boolean; toggle?: () => void } = {};
+ render(
+ <AgentChatLayout
+ resetKey="a"
+ roster={({ collapsed, onToggleCollapsed }) => {
+ rosterState.collapsed = collapsed;
+ rosterState.toggle = onToggleCollapsed;
+ return <nav aria-label="Roster" data-collapsed={String(collapsed)}>roster</nav>;
+ }}
+ header={(toggle) => <header aria-label="Chat header">{toggle}</header>}
+ options={<aside aria-label="Details">details</aside>}
+ >
+ <textarea aria-label="Draft" />
+ </AgentChatLayout>,
+ );
+ return rosterState;
+}
+
+describe("AgentChatLayout", () => {
+ it("lays out roster | chat | details and puts the details toggle into the header", () => {
+ mount();
+ const shell = screen.getByTestId("agent-shell");
+ expect(shell.style.gridTemplateColumns).toBe(`${ROSTER_DEFAULT}px minmax(0, 1fr) 320px`);
+ const toggle = screen.getByRole("button", { name: "society.card.options_collapse" });
+ expect(screen.getByRole("banner", { name: "Chat header" }).contains(toggle)).toBe(true);
+ expect(toggle.getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("folds the details pane without unmounting anything and remembers it", () => {
+ mount();
+ const draft = screen.getByLabelText("Draft") as HTMLTextAreaElement;
+ fireEvent.change(draft, { target: { value: "unsent" } });
+ fireEvent.click(screen.getByRole("button", { name: "society.card.options_collapse" }));
+ expect(screen.getByTestId("shell-details").hidden).toBe(true);
+ expect(screen.getByLabelText("Draft")).toBe(draft);
+ expect(draft.value).toBe("unsent");
+ expect(JSON.parse(localStorage.getItem(STORE) ?? "{}").paneOpen).toBe(false);
+
+ cleanup();
+ mount();
+ expect(screen.getByTestId("shell-details").hidden).toBe(true);
+ expect(screen.getByRole("button", { name: "society.card.options_expand" })).toBeTruthy();
+ });
+
+ it("resizes the roster from the keyboard and keeps the width across reloads", () => {
+ mount();
+ const handle = screen.getByRole("separator", { name: "society.shell.resize_roster" });
+ fireEvent.keyDown(handle, { key: "ArrowRight" });
+ fireEvent.keyDown(handle, { key: "ArrowRight" });
+ expect(JSON.parse(localStorage.getItem(STORE) ?? "{}").rosterWidth).toBe(ROSTER_DEFAULT + 32);
+ cleanup();
+ mount();
+ expect(screen.getByTestId("agent-shell").style.gridTemplateColumns.startsWith(`${ROSTER_DEFAULT + 32}px`)).toBe(true);
+ });
+
+ it("folds the roster to the rail on request", () => {
+ const roster = mount();
+ act(() => roster.toggle?.());
+ expect(screen.getByRole("navigation", { name: "Roster" }).dataset.collapsed).toBe("true");
+ expect(screen.getByTestId("agent-shell").style.gridTemplateColumns.startsWith(`${ROSTER_RAIL}px`)).toBe(true);
+ });
+
+ it("gives way in order on a narrow window and shows a closed pane as a sheet", () => {
+ frameWidth(ROSTER_DEFAULT + CHAT_MIN + 100);
+ mount();
+ const shell = screen.getByTestId("agent-shell");
+ // The pane could not fit: it closed, the roster kept its width.
+ expect(shell.style.gridTemplateColumns).toBe(`${ROSTER_DEFAULT}px minmax(0, 1fr) 0px`);
+ expect(screen.getByTestId("shell-details").hidden).toBe(true);
+ // Opening it now lays it over the chat instead of squeezing the chat.
+ fireEvent.click(screen.getByRole("button", { name: "society.card.options_expand" }));
+ const pane = screen.getByTestId("shell-details");
+ expect(pane.hidden).toBe(false);
+ expect(pane.dataset.overlay).toBe("true");
+ expect(shell.style.gridTemplateColumns).toBe(`${ROSTER_DEFAULT}px minmax(0, 1fr) 0px`);
+ // The person's own choice was not overwritten by the window.
+ expect(JSON.parse(localStorage.getItem(STORE) ?? "{}").paneOpen).toBe(true);
+ fireEvent.keyDown(document, { key: "Escape" });
+ expect(screen.getByTestId("shell-details").hidden).toBe(true);
+ });
+
+ it("folds the roster to the rail when even the pane is gone and the chat still needs room", () => {
+ frameWidth(200 + CHAT_MIN);
+ const roster = mount();
+ expect(roster.collapsed).toBe(true);
+ expect(screen.getByTestId("agent-shell").style.gridTemplateColumns).toBe(`${ROSTER_RAIL}px minmax(0, 1fr) 0px`);
+ });
+
+ it("keeps a slim bar with the toggle when no header is given", () => {
+ render(<AgentChatLayout options={<aside>details</aside>}><div>chat</div></AgentChatLayout>);
+ expect(screen.getByRole("button", { name: "society.card.options_collapse" }).textContent).toContain("society.card.options");
+ expect(screen.getByTestId("agent-shell").style.gridTemplateColumns).toBe("minmax(0, 1fr) 320px");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.tsx
index 6c2d18e1fa..d59641e431 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentChatLayout.tsx
@@ -1,39 +1,288 @@
-import { useId, useState, type ReactNode } from "react";
+/**
+ * The Agents section's frame: roster | chat | details, as one grid.
+ *
+ * The roster is the navigation, the chat is the stage, and the details pane
+ * belongs to the open agent. The roster and the pane are resizable within
+ * fixed bounds and remember their width and open state; the chat always
+ * keeps `CHAT_MIN` pixels. When the window narrows, the pane shrinks, then
+ * closes, then the roster folds to its avatar rail (`resolveShellLayout`).
+ * Opening a region the window had to close shows it as a sheet over the chat
+ * instead, so nothing is ever out of reach.
+ *
+ * Every region stays mounted: folding the pane must not reset a browser
+ * stream, a routine draft or the chat's unsent text.
+ */
+import { useCallback, useEffect, useId, useLayoutEffect, useReducer, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode, type RefObject } from "react";
import { PanelRightClose, PanelRightOpen } from "lucide-react";
import { useLocaleChunk, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+import "../agentSection.css";
import "./agentChatLayout.css";
+import {
+ CHAT_MIN,
+ PANE_DEFAULT,
+ PANE_MAX,
+ PANE_MIN,
+ ROSTER_DEFAULT,
+ ROSTER_MAX,
+ ROSTER_MIN,
+ ROSTER_RAIL,
+ readShellPrefs,
+ resolveShellLayout,
+ shellPrefsReducer,
+ writeShellPrefs,
+} from "./shellLayout";
+
+export interface RosterSlotState {
+ /** Show the avatar rail instead of rows. */
+ collapsed: boolean;
+ onToggleCollapsed: () => void;
+}
+
+export interface AgentChatLayoutProps {
+ /** The chat column. */
+ children: ReactNode;
+ /** The details pane's content (`OptionsRail`). */
+ options: ReactNode;
+ /** The roster column; without it the frame is chat | details only. */
+ roster?: (state: RosterSlotState) => ReactNode;
+ /** The chat header, handed the details toggle to place. Without it a slim bar carries the toggle. */
+ header?: (detailsToggle: ReactNode) => ReactNode;
+ /** Closes the sheets when it changes (the open agent's id). */
+ resetKey?: string;
+}
-/** Keep both panes mounted: folding Options must not reset a browser or draft. */
-export function AgentChatLayout({ children, options }: { children: ReactNode; options: ReactNode }) {
+const KEY_STEP = 16;
+
+function useMeasuredWidth(ref: RefObject<HTMLElement | null>): number {
+ const [width, setWidth] = useState(0);
+ useLayoutEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ setWidth(element.getBoundingClientRect().width);
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver((entries) => {
+ const next = entries[0]?.contentRect.width;
+ if (typeof next === "number") setWidth(next);
+ });
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [ref]);
+ return width;
+}
+
+export function AgentChatLayout({ children, options, roster, header, resetKey }: AgentChatLayoutProps) {
const t = useT();
useLocaleChunk("society");
- const [open, setOpen] = useState(true);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const rosterRef = useRef<HTMLDivElement>(null);
+ const paneRef = useRef<HTMLDivElement>(null);
+ const toggleRef = useRef<HTMLButtonElement>(null);
const panelId = useId();
- const label = t(open ? "society.card.options_collapse" : "society.card.options_expand");
- const Icon = open ? PanelRightClose : PanelRightOpen;
+ const [prefs, dispatch] = useReducer(shellPrefsReducer, undefined, readShellPrefs);
+ const [paneSheet, setPaneSheet] = useState(false);
+ const [rosterSheet, setRosterSheet] = useState(false);
+ const [resizing, setResizing] = useState<"roster" | "pane" | null>(null);
+ const measured = useMeasuredWidth(rootRef);
+ // Before the first measurement (and in a test DOM) nothing has to give way.
+ const available = measured > 0 ? measured : Number.POSITIVE_INFINITY;
+ // Without a roster the frame is chat | details; the resolver always counts
+ // a roster column, so hand it the rail's width back.
+ const layout = roster
+ ? resolveShellLayout(available, prefs, true)
+ : resolveShellLayout(available + ROSTER_RAIL, { ...prefs, rosterCollapsed: true }, true);
+ const rosterWidth = roster ? layout.rosterWidth : 0;
+
+ useEffect(() => {
+ writeShellPrefs(prefs);
+ }, [prefs]);
+
+ // A sheet is for a region the window closed; once it fits again it docks.
+ useEffect(() => {
+ if (!layout.paneForced) setPaneSheet(false);
+ }, [layout.paneForced]);
+ useEffect(() => {
+ if (!layout.rosterForced) setRosterSheet(false);
+ }, [layout.rosterForced]);
+ useEffect(() => {
+ setRosterSheet(false);
+ setPaneSheet(false);
+ }, [resetKey]);
+
+ // Sheets close on Escape and on a press outside them.
+ useEffect(() => {
+ if (!paneSheet && !rosterSheet) return;
+ const onDown = (event: PointerEvent) => {
+ const target = event.target as Node;
+ if (target instanceof Element && target.closest('[role="menu"], [role="dialog"], [role="listbox"]')) return;
+ if (rosterSheet && !rosterRef.current?.contains(target)) setRosterSheet(false);
+ if (paneSheet && !paneRef.current?.contains(target) && !toggleRef.current?.contains(target)) setPaneSheet(false);
+ };
+ const onKey = (event: globalThis.KeyboardEvent) => {
+ if (event.key !== "Escape" || event.defaultPrevented) return;
+ setRosterSheet(false);
+ setPaneSheet(false);
+ };
+ document.addEventListener("pointerdown", onDown, true);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("pointerdown", onDown, true);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [paneSheet, rosterSheet]);
+
+ const paneVisible = layout.paneOpen || paneSheet;
+ const toggleLabel = t(paneVisible ? "society.card.options_collapse" : "society.card.options_expand");
+ const ToggleIcon = paneVisible ? PanelRightClose : PanelRightOpen;
+ const togglePane = useCallback(() => {
+ if (layout.paneForced) setPaneSheet((value) => !value);
+ else {
+ setPaneSheet(false);
+ dispatch({ type: "toggle-pane" });
+ }
+ }, [layout.paneForced]);
+ const toggleRoster = useCallback(() => {
+ if (layout.rosterForced) setRosterSheet((value) => !value);
+ else {
+ setRosterSheet(false);
+ dispatch({ type: "toggle-roster" });
+ }
+ }, [layout.rosterForced]);
+
+ // --- resizing -------------------------------------------------------------
+ const drag = useRef<{ edge: "roster" | "pane"; startX: number; startWidth: number; pointerId: number } | null>(null);
+ const maxFor = (edge: "roster" | "pane") => {
+ if (!Number.isFinite(available)) return edge === "roster" ? ROSTER_MAX : PANE_MAX;
+ const others = edge === "roster" ? layout.paneWidth : rosterWidth;
+ const room = available - others - CHAT_MIN;
+ return edge === "roster" ? Math.max(ROSTER_MIN, Math.min(ROSTER_MAX, room)) : Math.max(PANE_MIN, Math.min(PANE_MAX, room));
+ };
+ const resizeTo = (edge: "roster" | "pane", width: number) => {
+ const bounded = Math.min(maxFor(edge), width);
+ dispatch(edge === "roster" ? { type: "resize-roster", width: bounded } : { type: "resize-pane", width: bounded });
+ };
+ const onResizeDown = (edge: "roster" | "pane") => (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ drag.current = {
+ edge,
+ startX: event.clientX,
+ startWidth: edge === "roster" ? rosterWidth : layout.paneWidth,
+ pointerId: event.pointerId,
+ };
+ try {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ } catch {
+ // A synthetic or already-released pointer: window listeners still follow it.
+ }
+ setResizing(edge);
+ };
+ const onResizeMove = (event: ReactPointerEvent<HTMLButtonElement>) => {
+ const current = drag.current;
+ if (!current || current.pointerId !== event.pointerId) return;
+ const delta = event.clientX - current.startX;
+ resizeTo(current.edge, current.edge === "roster" ? current.startWidth + delta : current.startWidth - delta);
+ };
+ const onResizeEnd = (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (!drag.current || drag.current.pointerId !== event.pointerId) return;
+ drag.current = null;
+ setResizing(null);
+ };
+ const onResizeKey = (edge: "roster" | "pane") => (event: KeyboardEvent<HTMLButtonElement>) => {
+ const width = edge === "roster" ? rosterWidth : layout.paneWidth;
+ const grow = edge === "roster" ? "ArrowRight" : "ArrowLeft";
+ const shrink = edge === "roster" ? "ArrowLeft" : "ArrowRight";
+ if (event.key === grow || event.key === shrink) {
+ event.preventDefault();
+ resizeTo(edge, width + (event.key === grow ? KEY_STEP : -KEY_STEP));
+ } else if (event.key === "Home" || event.key === "End") {
+ event.preventDefault();
+ resizeTo(edge, event.key === "Home" ? (edge === "roster" ? ROSTER_MIN : PANE_MIN) : maxFor(edge));
+ }
+ };
+
+ const separator = (edge: "roster" | "pane", width: number) => (
+ <button
+ type="button"
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={t(edge === "roster" ? "society.shell.resize_roster" : "society.shell.resize_details")}
+ aria-valuemin={edge === "roster" ? ROSTER_MIN : PANE_MIN}
+ aria-valuemax={maxFor(edge)}
+ aria-valuenow={width}
+ data-edge={edge === "roster" ? "right" : "left"}
+ data-active={resizing === edge ? "true" : undefined}
+ data-testid={`shell-resize-${edge}`}
+ className="as-resizer"
+ onPointerDown={onResizeDown(edge)}
+ onPointerMove={onResizeMove}
+ onPointerUp={onResizeEnd}
+ onPointerCancel={onResizeEnd}
+ onKeyDown={onResizeKey(edge)}
+ onDoubleClick={() => resizeTo(edge, edge === "roster" ? ROSTER_DEFAULT : PANE_DEFAULT)}
+ />
+ );
+
+ const detailsToggle = (
+ <button
+ ref={toggleRef}
+ type="button"
+ onClick={togglePane}
+ title={toggleLabel}
+ aria-label={toggleLabel}
+ aria-expanded={paneVisible}
+ aria-controls={panelId}
+ data-testid="shell-details-toggle"
+ className="as-header-control"
+ >
+ <ToggleIcon aria-hidden className="h-4 w-4" />
+ {header ? null : <span>{t("society.card.options")}</span>}
+ </button>
+ );
+
+ const columns = roster
+ ? `${rosterWidth}px minmax(0, 1fr) ${layout.paneWidth}px`
+ : `minmax(0, 1fr) ${layout.paneWidth}px`;
+ const rosterCollapsed = layout.roster === "rail" && !rosterSheet;
return (
- <div className="agent-chat-layout flex min-h-0 min-w-0 flex-col overflow-hidden rounded-tl-[12px] border-l border-border bg-background">
- <div className="flex shrink-0 justify-end border-b border-border px-2 py-1">
- <button
- type="button"
- onClick={() => setOpen((value) => !value)}
- title={label}
- aria-label={label}
- aria-expanded={open}
- aria-controls={panelId}
- className="inline-flex h-8 shrink-0 items-center justify-center gap-2 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
- <Icon aria-hidden className="h-4 w-4" />
- {t("society.card.options")}
- </button>
- </div>
- <div className="agent-chat-layout-panes" data-options-open={open}>
- {children}
- <div id={panelId} hidden={!open} className="agent-chat-layout-options">
- {options}
+ <div
+ ref={rootRef}
+ className="agent-chat-layout agent-section as-shell"
+ data-resizing={resizing ? "true" : undefined}
+ data-roster={roster ? layout.roster : undefined}
+ data-options-open={paneVisible}
+ data-testid="agent-shell"
+ style={{ gridTemplateColumns: columns, "--agent-pane-width": `${layout.paneWidth || PANE_MIN}px` } as CSSProperties}
+ >
+ {roster ? (
+ <div className="as-region" style={{ zIndex: rosterSheet ? 30 : undefined }}>
+ <div ref={rosterRef} className={cn("flex min-h-0 flex-1 flex-col", rosterSheet && "as-roster-overlay")}
+ style={rosterSheet ? { width: ROSTER_DEFAULT } : undefined} data-testid="shell-roster">
+ {roster({ collapsed: rosterCollapsed, onToggleCollapsed: toggleRoster })}
+ </div>
+ {layout.roster === "full" ? separator("roster", rosterWidth) : null}
</div>
+ ) : null}
+ <div className={cn("as-region as-stage", roster && "border-l border-border")} data-testid="shell-stage">
+ {header ? header(detailsToggle) : (
+ <div className="flex shrink-0 justify-end border-b border-border px-2 py-1">{detailsToggle}</div>
+ )}
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">{children}</div>
+ </div>
+ <div
+ ref={paneRef}
+ id={panelId}
+ hidden={!paneVisible}
+ className="agent-chat-layout-options as-region as-pane"
+ data-overlay={paneSheet ? "true" : undefined}
+ style={paneSheet ? { width: Math.min(PANE_DEFAULT, Math.max(PANE_MIN, available - 48)) } : undefined}
+ data-testid="shell-details"
+ >
+ {layout.paneOpen && !paneSheet ? separator("pane", layout.paneWidth) : null}
+ {options}
</div>
</div>
);
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx
new file mode 100644
index 0000000000..376698aa17
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.test.tsx
@@ -0,0 +1,169 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { create } from "zustand";
+
+import type { SocietyAgent } from "../data";
+import { modeSupported, runnerFor } from "./approvalModes";
+import { AgentHeader } from "./AgentHeader";
+
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useUiLanguage: () => "en" }));
+vi.mock("../chat/AgentModelPicker", () => ({
+ AgentModelPicker: ({ agent }: { agent: SocietyAgent }) => <button type="button">model:{agent.model || "default"}</button>,
+}));
+const chatStore = vi.hoisted(() => ({ hook: null as unknown }));
+vi.mock("../chat/AgentChatPanel", () => {
+ chatStore.hook = create(() => ({ busy: false, activeSessionId: null }));
+ return { useSocietyChatStore: chatStore.hook };
+});
+
+function agent(over: Partial<SocietyAgent> = {}): SocietyAgent {
+ return {
+ agentId: "scout",
+ name: "Scout",
+ title: "Research scout",
+ description: "",
+ tier: "specialist",
+ provider: "codex",
+ providerLabel: "Codex",
+ model: "gpt-x",
+ effort: "",
+ figure: null,
+ palette: { primary: "#000", secondary: "#111", accent: "#222" },
+ grantMode: "all",
+ toolGrants: [],
+ focus: [],
+ denies: [],
+ approvalRules: { requireApproval: [], alwaysAllow: [] },
+ permissionCeiling: "ask",
+ approvalMode: "ask",
+ dailyBudgetUsd: 0,
+ checkpoint: "idle",
+ state: "idle",
+ lifecycle: "active",
+ createdMs: 0,
+ maxConcurrentRuns: 1,
+ workspaceDir: "",
+ wikiNamespace: "",
+ chatSessionId: "society:scout",
+ routines: [],
+ stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },
+ ...over,
+ };
+}
+
+const providers = [
+ { id: "codex", runner: "codex-cli" },
+ { id: "claude-api", runner: "claude-cli" },
+ { id: "opencode", runner: "opencode-cli" },
+];
+
+function json(body: unknown, status = 200) {
+ return { ok: status >= 200 && status < 300, status, json: async () => body } as Response;
+}
+
+function mount(row: SocietyAgent, fetcher = vi.fn(async (url: string) => (String(url).endsWith("/providers") ? json({ providers }) : json({})))) {
+ vi.stubGlobal("fetch", fetcher);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(<QueryClientProvider client={client}><AgentHeader agent={row} detailsToggle={<button type="button">details</button>} /></QueryClientProvider>);
+ return { fetcher, client };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("approval mode support", () => {
+ it("mirrors the server's runner rules", () => {
+ expect(runnerFor({ provider: "", runtime: "jarvis" }, providers)).toBe("brain");
+ expect(runnerFor({ provider: "codex", runtime: "hermes" }, providers)).toBe("hermes-cli");
+ expect(runnerFor({ provider: "codex", runtime: "openclaw" }, providers)).toBe("openclaw-cli");
+ expect(runnerFor({ provider: "codex" }, providers)).toBe("codex-cli");
+ expect(runnerFor({ provider: "codex" }, undefined)).toBeNull();
+
+ expect(modeSupported("brain", "always_ask")).toBe(true);
+ expect(modeSupported("codex-cli", "always_ask")).toBe(true);
+ expect(modeSupported("claude-cli", "always_ask")).toBe(false);
+ expect(modeSupported("claude-cli", "ask")).toBe(true);
+ expect(modeSupported("hermes-cli", "ask")).toBe(true);
+ expect(modeSupported("openclaw-cli", "ask")).toBe(true);
+ expect(modeSupported("opencode-cli", "ask")).toBe(false);
+ expect(modeSupported(null, "ask")).toBe(false);
+ expect(modeSupported(null, "bypass")).toBe(true);
+ });
+});
+
+describe("AgentHeader", () => {
+ it("shows identity, the live phrase, the brain picker and the details toggle", () => {
+ mount(agent({ state: "working" }));
+ expect(screen.getByTestId("agent-header-name").textContent).toBe("Scout");
+ expect(screen.getByTestId("agent-header-status").textContent).toBe("society.shell.preview_working");
+ expect(screen.getByRole("button", { name: "model:gpt-x" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "details" })).toBeTruthy();
+ });
+
+ it("says why the agent waits when the backend names a reason", () => {
+ mount({ ...agent({ state: "waiting" }), waiting_reason: { kind: "approval", summary: "Send the invoice?" } } as SocietyAgent);
+ expect(screen.getByTestId("agent-header-status").textContent).toBe("society.shell.preview_needs_you · Send the invoice?");
+ });
+
+ it("shows no brain or approval picker for the lead, whose chat follows the app's own choice", () => {
+ mount(agent({ tier: "lead", agentId: "jarvis", name: "Jarvis" }));
+ expect(screen.queryByTestId("agent-header-model")).toBeNull();
+ expect(screen.queryByTestId("agent-header-approval")).toBeNull();
+ });
+
+ it("offers only the modes the runner can honour", async () => {
+ mount(agent({ provider: "claude-api", approvalMode: "ask" }));
+ fireEvent.click(screen.getByTestId("agent-header-approval"));
+ await waitFor(() => expect((screen.getByTestId("approval-mode-ask") as HTMLButtonElement).disabled).toBe(false));
+ expect((screen.getByTestId("approval-mode-always_ask") as HTMLButtonElement).disabled).toBe(true);
+ expect((screen.getByTestId("approval-mode-bypass") as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it("lets a Hermes agent ask but not always ask", async () => {
+ mount(agent({ provider: "codex", runtime: "hermes", approvalMode: "bypass" }));
+ fireEvent.click(screen.getByTestId("agent-header-approval"));
+ await waitFor(() => expect((screen.getByTestId("approval-mode-ask") as HTMLButtonElement).disabled).toBe(false));
+ expect((screen.getByTestId("approval-mode-always_ask") as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it("tightens at once but asks once more before loosening", async () => {
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
+ if (String(url).endsWith("/providers")) return json({ providers });
+ if (init?.method === "PATCH") return json({});
+ return json({});
+ });
+ mount(agent({ approvalMode: "ask" }), fetcher);
+ const patches = () => fetcher.mock.calls.filter(([, init]) => (init as RequestInit | undefined)?.method === "PATCH");
+
+ fireEvent.click(screen.getByTestId("agent-header-approval"));
+ await waitFor(() => expect((screen.getByTestId("approval-mode-always_ask") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByTestId("approval-mode-always_ask"));
+ await waitFor(() => expect(patches()).toHaveLength(1));
+ expect(JSON.parse(String((patches()[0][1] as RequestInit).body))).toEqual({ approval_mode: "always_ask" });
+
+ fireEvent.click(screen.getByTestId("agent-header-approval"));
+ fireEvent.click(await screen.findByTestId("approval-mode-bypass"));
+ expect(patches()).toHaveLength(1);
+ expect(screen.getByTestId("approval-mode-bypass").textContent).toContain("society.shell.approval_confirm");
+ fireEvent.click(screen.getByTestId("approval-mode-bypass"));
+ await waitFor(() => expect(patches()).toHaveLength(2));
+ expect(JSON.parse(String((patches()[1][1] as RequestInit).body))).toEqual({ approval_mode: "bypass" });
+ });
+
+ it("keeps the menu open with the server's reason when a save is refused", async () => {
+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
+ if (String(url).endsWith("/providers")) return json({ providers });
+ if (init?.method === "PATCH") return json({ detail: "This runner cannot provide an actionable approval for that mode." }, 422);
+ return json({});
+ });
+ mount(agent({ approvalMode: "bypass" }), fetcher);
+ fireEvent.click(screen.getByTestId("agent-header-approval"));
+ await waitFor(() => expect((screen.getByTestId("approval-mode-ask") as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByTestId("approval-mode-ask"));
+ expect((await screen.findByRole("alert")).textContent).toContain("cannot provide");
+ expect(screen.getByRole("menu")).toBeTruthy();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.tsx
new file mode 100644
index 0000000000..c8d507a290
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentHeader.tsx
@@ -0,0 +1,251 @@
+/**
+ * The chat's header bar: who this is and what it is doing on the left; what
+ * it thinks with and how freely it may act on the right; then the details
+ * toggle. "Who and how" lives here, "what to say" lives in the composer.
+ *
+ * The brain picker is the composer's own `AgentModelPicker`, moved up; it
+ * already knows every runtime (a Hermes or OpenClaw agent shows its
+ * runtime-locked state inside it). The approval picker only offers what the
+ * agent's runner can honour and asks once more before loosening a mode.
+ */
+import { useEffect, useId, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Check, ChevronDown, Shield, ShieldAlert, ShieldOff, ShieldQuestion } from "lucide-react";
+
+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";
+import { useT } from "@/i18n";
+import { fetchSocietyProviders, type AgentApprovalMode, type SocietyAgentRow } from "@/lib/societyApi";
+import { societyDisplayName } from "@/lib/societyDisplayName";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+
+import { AgentSwatch } from "../AgentSwatch";
+import { agentTint } from "../agentTint";
+import { rowToAgent, type SocietyAgent } from "../data";
+import { AgentModelPicker } from "../chat/AgentModelPicker";
+import { useSocietyChatStore } from "../chat/AgentChatPanel";
+import { previewText, rosterStatus, waitingReasonOf } from "../roster/rosterPreview";
+import { StatusMark } from "../roster/RosterRow";
+import { AGENT_APPROVAL_MODES, modeSupported, runnerFor } from "./approvalModes";
+
+const MODE_ICON: Record<AgentApprovalMode | "legacy", typeof Shield> = {
+ bypass: ShieldOff,
+ ask: ShieldQuestion,
+ always_ask: ShieldAlert,
+ legacy: Shield,
+};
+
+/** How strict a mode is; choosing a lower number loosens what the agent may do unasked. */
+const STRICTNESS: Record<AgentApprovalMode | "legacy", number> = { bypass: 0, legacy: 1, ask: 1, always_ask: 2 };
+
+export interface AgentHeaderProps {
+ agent: SocietyAgent;
+ sample?: boolean;
+ /** The details-pane toggle; the layout owns it so its state and focus survive. */
+ detailsToggle?: ReactNode;
+ /** Reports a model save in flight so the composer holds Send meanwhile. */
+ onModelSavingChange?: (saving: boolean) => void;
+}
+
+export function AgentHeader({ agent, sample = false, detailsToggle, onModelSavingChange }: AgentHeaderProps) {
+ const t = useT();
+ const assistantName = useEventStore((state) => state.assistantName);
+ const displayName = societyDisplayName(agent, assistantName);
+ const lead = agent.tier === "lead";
+ const busy = useSocietyChatStore((state) => state.busy && state.activeSessionId === agent.chatSessionId);
+ const status = rosterStatus(agent, false);
+ const reason = waitingReasonOf(agent);
+
+ let phrase: ReactNode;
+ if (status === "needs-you") {
+ const summary = previewText(reason?.summary);
+ phrase = <span className="truncate text-warning">{summary ? `${t("society.shell.preview_needs_you")} · ${summary}` : t("society.shell.status_waiting")}</span>;
+ } else if (status === "working") {
+ phrase = <span className="as-shimmer truncate">{t("society.shell.preview_working")}</span>;
+ } else if (status === "paused") {
+ phrase = <span className="truncate">{t("society.state.paused")}</span>;
+ } else {
+ phrase = <span className="truncate">{agent.title || t("society.state.idle")}</span>;
+ }
+
+ return (
+ <header className="as-header" data-testid="agent-header" style={agentTint(agent)}>
+ <span className="as-avatar">
+ <AgentSwatch agent={agent} size={30} />
+ <StatusMark status={status} className="[background:hsl(var(--background))]" />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <h2 className="truncate text-[13.5px] font-semibold leading-[18px] text-foreground-strong" data-testid="agent-header-name">{displayName}</h2>
+ <p className="flex min-w-0 text-xs leading-4 text-muted-foreground" aria-live="polite" data-testid="agent-header-status">{phrase}</p>
+ </div>
+ {!lead ? (
+ <div className="as-header-slot" data-testid="agent-header-model">
+ <AgentChatStoreProvider store={useSocietyChatStore}>
+ <AgentModelPicker key={agent.agentId} agent={agent} busy={busy} onSavingChange={(saving) => onModelSavingChange?.(saving)} />
+ </AgentChatStoreProvider>
+ </div>
+ ) : null}
+ {!lead && !sample ? <ApprovalModePicker agent={agent} /> : null}
+ {detailsToggle ? (
+ <>
+ <span aria-hidden className="mx-0.5 h-5 w-px bg-border" />
+ {detailsToggle}
+ </>
+ ) : null}
+ </header>
+ );
+}
+
+export function ApprovalModePicker({ agent }: { agent: SocietyAgent }) {
+ const t = useT();
+ const client = useQueryClient();
+ const menuId = useId();
+ const [open, setOpen] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+ const [confirming, setConfirming] = useState<AgentApprovalMode | null>(null);
+ const root = useRef<HTMLDivElement>(null);
+ const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders, staleTime: 60_000 });
+ const runner = runnerFor(agent, providers.data);
+ const current = agent.approvalMode ?? null;
+ const currentKey = current ?? "legacy";
+ const Icon = MODE_ICON[currentKey];
+ const label = current ? t(`society.approval_mode.${current}`) : t("society.shell.approval_legacy");
+
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (event: PointerEvent) => {
+ if (!root.current?.contains(event.target as Node)) setOpen(false);
+ };
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ setOpen(false);
+ root.current?.querySelector<HTMLButtonElement>("[data-approval-trigger]")?.focus();
+ }
+ };
+ document.addEventListener("pointerdown", onDown, true);
+ document.addEventListener("keydown", onKey, true);
+ root.current?.querySelector<HTMLButtonElement>('[role="menuitemradio"]:not([disabled])')?.focus();
+ return () => {
+ document.removeEventListener("pointerdown", onDown, true);
+ document.removeEventListener("keydown", onKey, true);
+ };
+ }, [open]);
+
+ useEffect(() => {
+ setOpen(false);
+ setError("");
+ setConfirming(null);
+ }, [agent.agentId]);
+
+ const choose = async (mode: AgentApprovalMode) => {
+ if (saving || mode === current) {
+ setOpen(false);
+ return;
+ }
+ if (STRICTNESS[mode] < STRICTNESS[currentKey] && confirming !== mode) {
+ setConfirming(mode);
+ return;
+ }
+ setSaving(true);
+ setError("");
+ try {
+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ approval_mode: mode }),
+ });
+ if (!response.ok) {
+ const body = await response.json().catch(() => null) as { detail?: unknown } | null;
+ throw new Error(typeof body?.detail === "string" ? body.detail : t("society.approval_mode.unavailable"));
+ }
+ const body = await response.json().catch(() => null) as { agent?: SocietyAgentRow } | null;
+ if (body?.agent) {
+ const updated = rowToAgent(body.agent);
+ client.setQueryData<{ agents: SocietyAgent[]; sample: boolean }>(["society", "roster"], (previous) => previous
+ ? { ...previous, agents: previous.agents.map((row) => (row.agentId === updated.agentId ? updated : row)) }
+ : previous);
+ }
+ await client.invalidateQueries({ queryKey: ["society", "roster"] });
+ setConfirming(null);
+ setOpen(false);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
+ event.preventDefault();
+ const items = [...(event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="menuitemradio"]:not([disabled])'))];
+ if (!items.length) return;
+ const at = items.indexOf(document.activeElement as HTMLButtonElement);
+ items[(at + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length]?.focus();
+ };
+
+ return (
+ <div ref={root} className="relative">
+ <button
+ type="button"
+ data-approval-trigger
+ data-testid="agent-header-approval"
+ aria-haspopup="menu"
+ aria-expanded={open}
+ aria-controls={open ? menuId : undefined}
+ aria-label={`${t("society.approval_mode.title")}: ${label}`}
+ title={current ? t(`society.approval_mode.${current}_hint`) : t("society.approval_mode.legacy_hint")}
+ disabled={saving}
+ onClick={() => {
+ setConfirming(null);
+ setError("");
+ setOpen((value) => !value);
+ }}
+ className="as-header-control"
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span className="as-header-label truncate">{label}</span>
+ <ChevronDown className="h-3 w-3 shrink-0 opacity-70" aria-hidden />
+ </button>
+ {open ? (
+ <div id={menuId} role="menu" aria-label={t("society.approval_mode.title")} onKeyDown={onMenuKeyDown}
+ className="as-menu absolute right-0 top-full z-50 mt-1.5 w-72">
+ <p className="px-2.5 pb-1 pt-1.5 text-[11px] font-medium text-muted-foreground">{t("society.approval_mode.title")}</p>
+ {AGENT_APPROVAL_MODES.map((mode) => {
+ const supported = modeSupported(runner, mode);
+ const ModeIcon = MODE_ICON[mode];
+ const selected = mode === current;
+ const confirm = confirming === mode;
+ return (
+ <button
+ key={mode}
+ type="button"
+ role="menuitemradio"
+ aria-checked={selected}
+ disabled={!supported || saving}
+ title={supported ? undefined : t("society.approval_mode.unavailable")}
+ onClick={() => void choose(mode)}
+ className="as-menu-item"
+ data-testid={`approval-mode-${mode}`}
+ >
+ <ModeIcon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="min-w-0 flex-1">
+ <span className={cn("block font-medium", confirm ? "text-warning" : "text-foreground")}>
+ {confirm ? t("society.shell.approval_confirm") : t(`society.approval_mode.${mode}`)}
+ </span>
+ <span className="block text-xs leading-4 text-muted-foreground">
+ {supported ? t(`society.approval_mode.${mode}_hint`) : t("society.approval_mode.unavailable")}
+ </span>
+ </span>
+ {selected ? <Check className="mt-0.5 h-4 w-4 shrink-0 text-foreground" aria-hidden /> : null}
+ </button>
+ );
+ })}
+ {error ? <p role="alert" className="px-2.5 pb-1.5 pt-1 text-xs text-destructive">{error}</p> : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/agentChatLayout.css b/dodaios/ui/web/frontend/src/components/society/card/agentChatLayout.css
index f078169f8f..82959532be 100644
--- a/dodaios/ui/web/frontend/src/components/society/card/agentChatLayout.css
+++ b/dodaios/ui/web/frontend/src/components/society/card/agentChatLayout.css
@@ -1,51 +1,13 @@
+/*
+ * The Agents frame's grid lives in `agentSection.css` (`.as-shell`); its
+ * column widths come from `resolveShellLayout` as an inline template. What
+ * remains here is the workspace container the section measures against.
+ */
.agent-card-workspace {
container: agent-card / inline-size;
}
-@container agent-card (max-width: 760px) {
- .agent-card-columns {
- grid-template-columns: minmax(160px, 200px) minmax(0, 1fr);
- }
-}
-
-@container agent-card (max-width: 480px) {
- .agent-card-columns {
- grid-template-columns: minmax(0, 1fr);
- grid-template-rows: minmax(0, 140px) minmax(0, 1fr);
- }
-}
-
-.agent-chat-layout {
- container: agent-chat-layout / inline-size;
-}
-
-.agent-chat-layout-panes {
- display: grid;
- flex: 1;
- min-width: 0;
- min-height: 0;
- grid-template-columns: minmax(0, 1fr);
- grid-template-rows: minmax(0, 1fr);
-}
-
-.agent-chat-layout-panes[data-options-open="true"] {
- grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);
-}
-
.agent-chat-layout-options {
min-width: 0;
min-height: 0;
- border-top: 1px solid hsl(var(--border));
-}
-
-/* Use the available pane width, including when the app navigation is open. */
-@container agent-chat-layout (min-width: 680px) {
- .agent-chat-layout-panes[data-options-open="true"] {
- grid-template-columns: minmax(0, 1fr) minmax(280px, 320px);
- grid-template-rows: minmax(0, 1fr);
- }
-
- .agent-chat-layout-options {
- border-top: 0;
- }
}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts b/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts
new file mode 100644
index 0000000000..0ac261c812
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/approvalModes.ts
@@ -0,0 +1,52 @@
+/**
+ * Which approval modes an agent's runner can actually honour, mirrored from
+ * `society_mode_supported` in `dodaios/agent_chat/permissions.py`.
+ *
+ * The header only offers a mode the transport can turn into a usable card;
+ * the server validates the same rule again on PATCH and answers 422 when the
+ * picture here was stale (a seat changed on another window, say).
+ */
+import { AGENT_APPROVAL_MODES, type AgentApprovalMode, type SocietyProviderRow } from "@/lib/societyApi";
+
+import type { SocietyAgent } from "../data";
+
+export { AGENT_APPROVAL_MODES };
+
+/** Hermes and OpenClaw run every turn in their own loop (service.EXTERNAL_RUNTIME_RUNNERS). */
+const EXTERNAL_RUNNERS: Record<string, string> = {
+ hermes: "hermes-cli",
+ openclaw: "openclaw-cli",
+};
+
+const ASK_RUNNERS: ReadonlySet<string> = new Set([
+ "brain",
+ "codex-cli",
+ "claude-cli",
+ "glm-cli",
+ "hermes-cli",
+ "openclaw-cli",
+]);
+const ALWAYS_ASK_RUNNERS: ReadonlySet<string> = new Set(["brain", "codex-cli"]);
+
+/**
+ * The runner that answers this agent's turns, or null while it is not known
+ * yet (the provider list is still loading, or names no such provider).
+ */
+export function runnerFor(
+ agent: Pick<SocietyAgent, "provider" | "runtime">,
+ providers: readonly Pick<SocietyProviderRow, "id" | "runner">[] | undefined,
+): string | null {
+ const external = agent.runtime ? EXTERNAL_RUNNERS[agent.runtime] : undefined;
+ if (external) return external;
+ // No provider = the app's own brain.
+ if (!agent.provider) return "brain";
+ return providers?.find((row) => row.id === agent.provider)?.runner ?? null;
+}
+
+export function modeSupported(runner: string | null, mode: AgentApprovalMode): boolean {
+ if (mode === "bypass") return true;
+ if (runner === null) return false;
+ if (mode === "ask") return ASK_RUNNERS.has(runner);
+ if (mode === "always_ask") return ALWAYS_ASK_RUNNERS.has(runner);
+ return false;
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/headerModelSlot.ts b/dodaios/ui/web/frontend/src/components/society/card/headerModelSlot.ts
new file mode 100644
index 0000000000..c2fe2db8cb
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/headerModelSlot.ts
@@ -0,0 +1,17 @@
+import { createContext, useContext } from "react";
+
+/**
+ * Set when the chat header carries the agent's brain picker. The composer
+ * then leaves its own copy out and holds Send while the header saves a new
+ * model, exactly as it did while its own picker saved. Where no header
+ * provides it (team panes, older mounts) the composer keeps its picker.
+ */
+export interface HeaderModelSlot {
+ saving: boolean;
+}
+
+export const HeaderModelSlotContext = createContext<HeaderModelSlot | null>(null);
+
+export function useHeaderModelSlot(): HeaderModelSlot | null {
+ return useContext(HeaderModelSlotContext);
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/card/shellLayout.test.ts b/dodaios/ui/web/frontend/src/components/society/card/shellLayout.test.ts
new file mode 100644
index 0000000000..d19063d2ec
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/shellLayout.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ CHAT_MIN,
+ DEFAULT_SHELL_PREFS,
+ PANE_MAX,
+ PANE_MIN,
+ ROSTER_MAX,
+ ROSTER_MIN,
+ ROSTER_RAIL,
+ readShellPrefs,
+ resolveShellLayout,
+ shellPrefsReducer,
+ writeShellPrefs,
+ type ShellPrefs,
+} from "./shellLayout";
+
+const prefs = (over: Partial<ShellPrefs> = {}): ShellPrefs => ({ ...DEFAULT_SHELL_PREFS, ...over });
+
+afterEach(() => localStorage.clear());
+
+describe("resolveShellLayout", () => {
+ it("gives every region its preferred width when the window is wide", () => {
+ const layout = resolveShellLayout(1600, prefs({ rosterWidth: 300, paneWidth: 360 }));
+ expect(layout).toMatchObject({ roster: "full", rosterWidth: 300, paneOpen: true, paneWidth: 360, chatWidth: 940 });
+ expect(layout.paneForced).toBe(false);
+ expect(layout.rosterForced).toBe(false);
+ });
+
+ it("shrinks the pane first, so the chat keeps its minimum", () => {
+ const layout = resolveShellLayout(280 + CHAT_MIN + 300, prefs({ rosterWidth: 280, paneWidth: 400 }));
+ expect(layout.rosterWidth).toBe(280);
+ expect(layout.paneWidth).toBe(300);
+ expect(layout.chatWidth).toBe(CHAT_MIN);
+ });
+
+ it("closes the pane once it cannot shrink further, before the roster gives anything", () => {
+ const layout = resolveShellLayout(280 + CHAT_MIN + PANE_MIN - 1, prefs({ rosterWidth: 280 }));
+ expect(layout.paneOpen).toBe(false);
+ expect(layout.paneForced).toBe(true);
+ expect(layout.rosterWidth).toBe(280);
+ expect(layout.chatWidth).toBeGreaterThanOrEqual(CHAT_MIN);
+ });
+
+ it("then shrinks the roster, then folds it to the rail", () => {
+ const shrunk = resolveShellLayout(ROSTER_MIN + CHAT_MIN + 10, prefs({ rosterWidth: 320 }));
+ expect(shrunk).toMatchObject({ roster: "full", rosterWidth: ROSTER_MIN + 10, paneOpen: false });
+
+ const railed = resolveShellLayout(ROSTER_MIN + CHAT_MIN - 1, prefs({ rosterWidth: 320 }));
+ expect(railed).toMatchObject({ roster: "rail", rosterWidth: ROSTER_RAIL, rosterForced: true, paneOpen: false });
+ expect(railed.chatWidth).toBeGreaterThanOrEqual(CHAT_MIN);
+ });
+
+ it("never lets the chat drop below its minimum while something else can give way", () => {
+ for (let width = ROSTER_RAIL + CHAT_MIN; width <= 1800; width += 7) {
+ const layout = resolveShellLayout(width, prefs({ rosterWidth: ROSTER_MAX, paneWidth: PANE_MAX }));
+ expect(layout.chatWidth, `at ${width}px`).toBeGreaterThanOrEqual(CHAT_MIN);
+ expect(layout.rosterWidth + layout.paneWidth + layout.chatWidth).toBe(width);
+ }
+ });
+
+ it("honours a roster the person folded and a pane the person closed", () => {
+ const layout = resolveShellLayout(1600, prefs({ rosterCollapsed: true, paneOpen: false }));
+ expect(layout).toMatchObject({ roster: "rail", rosterWidth: ROSTER_RAIL, rosterForced: false, paneOpen: false, paneForced: false });
+ });
+
+ it("has no pane where nothing is open", () => {
+ expect(resolveShellLayout(1600, prefs(), false).paneWidth).toBe(0);
+ });
+});
+
+describe("shell preferences", () => {
+ it("clamps widths into their bounds", () => {
+ let state = shellPrefsReducer(prefs(), { type: "resize-roster", width: 10 });
+ expect(state.rosterWidth).toBe(ROSTER_MIN);
+ state = shellPrefsReducer(state, { type: "resize-roster", width: 9999 });
+ expect(state.rosterWidth).toBe(ROSTER_MAX);
+ state = shellPrefsReducer(state, { type: "resize-pane", width: 10 });
+ expect(state.paneWidth).toBe(PANE_MIN);
+ state = shellPrefsReducer(state, { type: "resize-pane", width: 9999 });
+ expect(state.paneWidth).toBe(PANE_MAX);
+ });
+
+ it("toggles the regions and unfolds the roster on a resize", () => {
+ let state = shellPrefsReducer(prefs(), { type: "toggle-pane" });
+ expect(state.paneOpen).toBe(false);
+ state = shellPrefsReducer(state, { type: "toggle-roster" });
+ expect(state.rosterCollapsed).toBe(true);
+ state = shellPrefsReducer(state, { type: "resize-roster", width: 300 });
+ expect(state.rosterCollapsed).toBe(false);
+ });
+
+ it("persists across reloads and survives bad storage", () => {
+ writeShellPrefs(prefs({ rosterWidth: 333, paneWidth: 401, paneOpen: false, rosterCollapsed: true }));
+ expect(readShellPrefs()).toEqual({ rosterWidth: 333, paneWidth: 401, paneOpen: false, rosterCollapsed: true });
+
+ localStorage.setItem("society.shell.layout.v1", "{not json");
+ expect(readShellPrefs()).toEqual(DEFAULT_SHELL_PREFS);
+
+ localStorage.setItem("society.shell.layout.v1", JSON.stringify({ rosterWidth: 5000, paneWidth: "wide" }));
+ expect(readShellPrefs()).toMatchObject({ rosterWidth: ROSTER_MAX, paneWidth: DEFAULT_SHELL_PREFS.paneWidth });
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/card/shellLayout.ts b/dodaios/ui/web/frontend/src/components/society/card/shellLayout.ts
new file mode 100644
index 0000000000..be4ae770a8
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/card/shellLayout.ts
@@ -0,0 +1,161 @@
+/**
+ * The Agents section's three-region frame as plain numbers: the roster on the
+ * left, the chat in the middle, the details pane on the right.
+ *
+ * The person sets two widths and two switches (roster collapsed, pane open);
+ * the window decides how much of that fits. `resolveShellLayout` is the one
+ * place that decides it, so the order in which regions give way is testable
+ * and identical everywhere:
+ *
+ * 1. the chat keeps at least `CHAT_MIN` pixels,
+ * 2. the details pane shrinks to its minimum,
+ * 3. then the pane closes,
+ * 4. then the roster shrinks to its minimum,
+ * 5. then the roster folds to the avatar rail.
+ *
+ * Only what the person chose is persisted. A pane the window closed comes
+ * back by itself once the window is wide enough again.
+ */
+
+export const ROSTER_MIN = 240;
+export const ROSTER_MAX = 400;
+export const ROSTER_DEFAULT = 280;
+/** The folded roster: avatars only. */
+export const ROSTER_RAIL = 64;
+export const PANE_MIN = 280;
+export const PANE_MAX = 480;
+export const PANE_DEFAULT = 320;
+/** The chat never gets narrower than this while anything else can give way. */
+export const CHAT_MIN = 424;
+
+const STORAGE_KEY = "society.shell.layout.v1";
+
+export interface ShellPrefs {
+ rosterWidth: number;
+ rosterCollapsed: boolean;
+ paneOpen: boolean;
+ paneWidth: number;
+}
+
+export const DEFAULT_SHELL_PREFS: ShellPrefs = {
+ rosterWidth: ROSTER_DEFAULT,
+ rosterCollapsed: false,
+ paneOpen: true,
+ paneWidth: PANE_DEFAULT,
+};
+
+export interface ShellLayout {
+ /** Width of the roster column in pixels (the rail width when folded). */
+ rosterWidth: number;
+ /** "full" shows rows; "rail" shows avatars only. */
+ roster: "full" | "rail";
+ /** True when the roster is a rail because the window is too narrow, not by choice. */
+ rosterForced: boolean;
+ /** 0 when the pane is closed. */
+ paneWidth: number;
+ paneOpen: boolean;
+ /** True when the pane is closed because the window is too narrow, not by choice. */
+ paneForced: boolean;
+ /** What is left for the chat. */
+ chatWidth: number;
+}
+
+export const clampRoster = (width: number) => Math.round(Math.min(ROSTER_MAX, Math.max(ROSTER_MIN, width)));
+export const clampPane = (width: number) => Math.round(Math.min(PANE_MAX, Math.max(PANE_MIN, width)));
+
+/**
+ * Fit the person's preferred layout into `available` pixels.
+ * `hasPane` is false where no details pane exists (no agent open).
+ */
+export function resolveShellLayout(available: number, prefs: ShellPrefs, hasPane = true): ShellLayout {
+ const total = Math.max(0, Math.floor(available));
+ let roster = prefs.rosterCollapsed ? ROSTER_RAIL : clampRoster(prefs.rosterWidth);
+ let rosterMode: "full" | "rail" = prefs.rosterCollapsed ? "rail" : "full";
+ let pane = hasPane && prefs.paneOpen ? clampPane(prefs.paneWidth) : 0;
+ let paneForced = false;
+ let rosterForced = false;
+
+ const overflow = () => roster + pane + CHAT_MIN - total;
+
+ // 2. The pane shrinks first ...
+ if (pane > 0 && overflow() > 0) pane = Math.max(PANE_MIN, pane - overflow());
+ // 3. ... then closes.
+ if (pane > 0 && overflow() > 0) {
+ pane = 0;
+ paneForced = true;
+ }
+ // 4. The roster shrinks ...
+ if (rosterMode === "full" && overflow() > 0) roster = Math.max(ROSTER_MIN, roster - overflow());
+ // 5. ... then folds to the rail.
+ if (rosterMode === "full" && overflow() > 0) {
+ roster = ROSTER_RAIL;
+ rosterMode = "rail";
+ rosterForced = true;
+ }
+ return {
+ rosterWidth: roster,
+ roster: rosterMode,
+ rosterForced,
+ paneWidth: pane,
+ paneOpen: pane > 0,
+ paneForced,
+ chatWidth: Math.max(0, total - roster - pane),
+ };
+}
+
+function sanitize(value: unknown): ShellPrefs {
+ if (!value || typeof value !== "object") return { ...DEFAULT_SHELL_PREFS };
+ const raw = value as Partial<Record<keyof ShellPrefs, unknown>>;
+ const num = (input: unknown, fallback: number) => (typeof input === "number" && Number.isFinite(input) ? input : fallback);
+ return {
+ rosterWidth: clampRoster(num(raw.rosterWidth, ROSTER_DEFAULT)),
+ rosterCollapsed: raw.rosterCollapsed === true,
+ paneOpen: raw.paneOpen !== false,
+ paneWidth: clampPane(num(raw.paneWidth, PANE_DEFAULT)),
+ };
+}
+
+export function readShellPrefs(): ShellPrefs {
+ try {
+ const stored = localStorage.getItem(STORAGE_KEY);
+ return stored ? sanitize(JSON.parse(stored)) : { ...DEFAULT_SHELL_PREFS };
+ } catch {
+ return { ...DEFAULT_SHELL_PREFS };
+ }
+}
+
+export function writeShellPrefs(prefs: ShellPrefs): void {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(sanitize(prefs)));
+ } catch {
+ // Private mode or a full disk: the layout holds for this window.
+ }
+}
+
+export type ShellAction =
+ | { type: "resize-roster"; width: number }
+ | { type: "resize-pane"; width: number }
+ | { type: "toggle-roster" }
+ | { type: "set-roster-collapsed"; collapsed: boolean }
+ | { type: "toggle-pane" }
+ | { type: "set-pane-open"; open: boolean };
+
+/** The person's choices, changed by one gesture. Pure; persistence is the caller's. */
+export function shellPrefsReducer(prefs: ShellPrefs, action: ShellAction): ShellPrefs {
+ switch (action.type) {
+ case "resize-roster":
+ return { ...prefs, rosterWidth: clampRoster(action.width), rosterCollapsed: false };
+ case "resize-pane":
+ return { ...prefs, paneWidth: clampPane(action.width), paneOpen: true };
+ case "toggle-roster":
+ return { ...prefs, rosterCollapsed: !prefs.rosterCollapsed };
+ case "set-roster-collapsed":
+ return prefs.rosterCollapsed === action.collapsed ? prefs : { ...prefs, rosterCollapsed: action.collapsed };
+ case "toggle-pane":
+ return { ...prefs, paneOpen: !prefs.paneOpen };
+ case "set-pane-open":
+ return prefs.paneOpen === action.open ? prefs : { ...prefs, paneOpen: action.open };
+ default:
+ return prefs;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index 34dd68cdbb..295e74e7ac 100644
--- a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -87,6 +87,7 @@ import { AgentModelPicker } from "./AgentModelPicker";
import { mentionChoice, messageChoices } from "./mentionChoices";
import { ChatCommandPanel, useChatCommands } from "@/components/agentchat/ChatCommands";
import { useTranscriptView } from "./useTranscriptView";
+import { useHeaderModelSlot } from "../card/headerModelSlot";
import { societyResultHeadline, societyResultText } from "@/lib/skipReasons";
import {
buildMentionCatalog,
@@ -1217,7 +1218,10 @@ interface ComposerProps {
export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, surface = "jarvis", onClear, onSend, onCancel }: ComposerProps) {
const t = useT();
const chatStore = useAgentChatApi();
- const [modelSaving, setModelSaving] = useState(false);
+ const [ownModelSaving, setModelSaving] = useState(false);
+ // The Agents header may carry the brain picker; then it owns the save state.
+ const headerModel = useHeaderModelSlot();
+ const modelSaving = ownModelSaving || Boolean(headerModel?.saving);
const messageDraft = useComposerDraft(chatStore, sessionId);
const value = messageDraft.text;
const setValue = (text: string) => writeComposerDraft(chatStore, sessionId, {
@@ -1532,7 +1536,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s
/>
{/* Hidden, not unmounted, while recording: the pill needs the room,
and a save in flight must still report back. */}
- {surface === "society" ? <div className={cn("h-8 min-w-0 max-w-[40%] shrink-0 items-center", dictation.dictating ? "hidden" : "flex")}>
+ {surface === "society" && !headerModel ? <div className={cn("h-8 min-w-0 max-w-[40%] shrink-0 items-center", dictation.dictating ? "hidden" : "flex")}>
<AgentModelPicker key={agent.agentId} agent={agent} busy={busy} onSavingChange={setModelSaving} />
</div> : null}
<DictationButton
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/AgentRosterActions.tsx b/dodaios/ui/web/frontend/src/components/society/roster/AgentRosterActions.tsx
index 6039418a69..d96a3be5ff 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/AgentRosterActions.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/roster/AgentRosterActions.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import { createPortal } from "react-dom";
import * as Dialog from "@radix-ui/react-dialog";
-import { EyeOff, Eye, Pencil, Trash2 } from "lucide-react";
+import { EyeOff, Eye, MailCheck, MailOpen, Pencil, Pin, PinOff, Trash2 } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
@@ -17,9 +17,21 @@ interface Props {
y: number;
onVisibilityChange: (agentId: string, hidden: boolean) => void;
onDismiss: () => void;
+ /** Pinning is offered when the roster shows a pinned grid. */
+ pinned?: boolean;
+ canPin?: boolean;
+ onTogglePin?: (agentId: string) => void;
+ /** Read state is offered when the roster tracks unread results. */
+ unread?: boolean;
+ /** False for the open agent: it is being read right now. */
+ canMarkUnread?: boolean;
+ onMarkUnread?: (agentId: string, unread: boolean) => void;
}
-export function AgentRosterActions({ agent, roster, sample, hidden, x, y, onVisibilityChange, onDismiss }: Props) {
+export function AgentRosterActions({
+ agent, roster, sample, hidden, x, y, onVisibilityChange, onDismiss,
+ pinned = false, canPin = true, onTogglePin, unread = false, canMarkUnread = true, onMarkUnread,
+}: Props) {
const t = useT();
const client = useQueryClient();
const retire = useRetireAgent();
@@ -112,6 +124,18 @@ export function AgentRosterActions({ agent, roster, sample, hidden, x, y, onVisi
{!mode && <div ref={menuRef} role="menu" aria-label={t("society.roster.menu")} onKeyDown={onMenuKeyDown}
style={{ width: 260, visibility: "hidden" }}
className="fixed z-[100] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-float">
+ {onTogglePin && <button type="button" role="menuitem" disabled={!pinned && !canPin} onClick={() => { onTogglePin(agent.agentId); onDismiss(); }}
+ title={!pinned && !canPin ? t("society.shell.pin_full") : undefined}
+ className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm hover:bg-secondary focus:bg-secondary focus:outline-none disabled:opacity-40">
+ {pinned ? <PinOff className="h-4 w-4" aria-hidden /> : <Pin className="h-4 w-4" aria-hidden />}
+ {t(pinned ? "society.shell.unpin" : "society.shell.pin")}
+ </button>}
+ {onMarkUnread && <button type="button" role="menuitem" disabled={!unread && !canMarkUnread} onClick={() => { onMarkUnread(agent.agentId, !unread); onDismiss(); }}
+ className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm hover:bg-secondary focus:bg-secondary focus:outline-none disabled:opacity-40">
+ {unread ? <MailCheck className="h-4 w-4" aria-hidden /> : <MailOpen className="h-4 w-4" aria-hidden />}
+ {t(unread ? "society.shell.mark_read" : "society.shell.mark_unread")}
+ </button>}
+ {(onTogglePin || onMarkUnread) && <div className="my-1 border-t border-border" aria-hidden />}
<button type="button" role="menuitem" disabled={sample || isLead} onClick={() => { setMode("rename"); setError(false); }}
className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm hover:bg-secondary focus:bg-secondary focus:outline-none disabled:opacity-40">
<Pencil className="h-4 w-4" aria-hidden />{t("society.roster.rename")}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/RosterHoverCard.tsx b/dodaios/ui/web/frontend/src/components/society/roster/RosterHoverCard.tsx
new file mode 100644
index 0000000000..049d680c0c
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/RosterHoverCard.tsx
@@ -0,0 +1,80 @@
+/**
+ * The larger identity a row shows after the pointer rests on it: face, name,
+ * role, what the agent is doing, and the latest words in its chat. Read-only
+ * and pointer-transparent, so it never steals a click or a drag.
+ */
+import { useLayoutEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+
+import { useT } from "@/i18n";
+
+import { AgentSwatch } from "../AgentSwatch";
+import { agentTint } from "../agentTint";
+import type { SocietyAgent } from "../data";
+import { previewText, type RosterStatus, type WaitingReason } from "./rosterPreview";
+import { StatusMark, statusLabel } from "./RosterRow";
+
+export interface HoverCardData {
+ agent: SocietyAgent;
+ displayName: string;
+ status: RosterStatus;
+ reason: WaitingReason | null;
+ lastMessage?: string;
+ draft?: string;
+ timeLabel?: string;
+ anchor: DOMRect;
+}
+
+const GAP = 10;
+
+export function RosterHoverCard({ data }: { data: HoverCardData }) {
+ const t = useT();
+ const ref = useRef<HTMLDivElement>(null);
+ const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
+
+ useLayoutEffect(() => {
+ const element = ref.current;
+ if (!element) return;
+ const { width, height } = element.getBoundingClientRect();
+ const fitsRight = data.anchor.right + GAP + width <= window.innerWidth - 8;
+ const left = fitsRight ? data.anchor.right + GAP : Math.max(8, data.anchor.left - GAP - width);
+ const top = Math.max(8, Math.min(data.anchor.top - 6, window.innerHeight - height - 8));
+ setPosition({ left, top });
+ }, [data.anchor]);
+
+ const last = previewText(data.lastMessage);
+ const draft = previewText(data.draft);
+ return createPortal(
+ <div
+ ref={ref}
+ role="tooltip"
+ data-testid="roster-hover-card"
+ className="agent-section as-hovercard"
+ style={{ ...agentTint(data.agent), left: position?.left ?? -9999, top: position?.top ?? -9999 }}
+ >
+ <div className="flex items-center gap-3">
+ <span className="as-avatar">
+ <AgentSwatch agent={data.agent} size={44} />
+ <StatusMark status={data.status} />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-semibold text-foreground-strong">{data.displayName}</p>
+ {data.agent.title ? <p className="truncate text-xs text-muted-foreground">{data.agent.title}</p> : null}
+ </div>
+ </div>
+ <p className={data.status === "needs-you" ? "mt-3 text-xs font-medium text-warning" : "mt-3 text-xs text-muted-foreground"}>
+ {data.status === "needs-you" && data.reason?.summary
+ ? `${t("society.shell.preview_needs_you")} · ${previewText(data.reason.summary)}`
+ : statusLabel(data.status, t)}
+ {data.timeLabel ? <span className="text-muted-foreground"> · {data.timeLabel}</span> : null}
+ </p>
+ {last ? <p className="mt-2 line-clamp-3 text-[13px] leading-[19px] text-foreground">{last}</p> : null}
+ {draft ? (
+ <p className="mt-2 line-clamp-2 text-xs text-muted-foreground">
+ <span className="as-preview-tag">{t("society.shell.preview_draft")}</span> {draft}
+ </p>
+ ) : null}
+ </div>,
+ document.body,
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx b/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx
index 725b1cd010..bcb09cad0b 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx
@@ -7,7 +7,7 @@ import { useRetireStore } from "@/components/society/world/retireStore";
import { useEventStore } from "@/store/events";
import { RosterRail, type RosterRailProps } from "./RosterRail";
-vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useUiLanguage: () => "en" }));
afterEach(() => {
useRetireStore.getState().cutShort();
@@ -166,10 +166,12 @@ describe("RosterRail agent actions", () => {
</QueryClientProvider>);
};
- it("opens exactly the three requested actions on right click", () => {
+ it("opens the pin, read, rename, hide and delete actions on right click", () => {
renderRail([agent({ agentId: "a", name: "A" })]);
fireEvent.contextMenu(screen.getByText("A"));
- expect(screen.getAllByRole("menuitem")).toHaveLength(3);
+ expect(screen.getAllByRole("menuitem")).toHaveLength(5);
+ expect(screen.getByRole("menuitem", { name: "society.shell.pin" })).toBeTruthy();
+ expect(screen.getByRole("menuitem", { name: "society.shell.mark_unread" })).toBeTruthy();
expect(screen.getByRole("menuitem", { name: "society.roster.rename" })).toBeTruthy();
expect(screen.getByRole("menuitem", { name: "society.roster.hide" })).toBeTruthy();
expect(screen.getByRole("menuitem", { name: "society.roster.delete" })).toBeTruthy();
@@ -261,12 +263,12 @@ describe("RosterRail reorder", () => {
expect(rowOrder()).toEqual(["c", "a", "b"]);
});
- it("moves a row with Alt + Arrow keys", () => {
+ it("moves a row with Alt + Shift + Arrow keys", () => {
renderRail(trio());
- fireEvent.keyDown(rowOf("A"), { key: "ArrowDown", altKey: true });
+ fireEvent.keyDown(rowOf("A"), { key: "ArrowDown", altKey: true, shiftKey: true });
expect(rowOrder()).toEqual(["b", "a", "c"]);
expect(JSON.parse(localStorage.getItem(ORDER_KEY) ?? "[]")).toEqual(["b", "a", "c"]);
- fireEvent.keyDown(rowOf("A"), { key: "ArrowUp", altKey: true });
+ fireEvent.keyDown(rowOf("A"), { key: "ArrowUp", altKey: true, shiftKey: true });
expect(rowOrder()).toEqual(["a", "b", "c"]);
});
@@ -451,3 +453,156 @@ it("shows and finds the lead by the wake-word name", () => {
fireEvent.change(screen.getByRole("searchbox"), { target: { value: "hanna" } });
expect(screen.getByText("Hanna")).toBeTruthy();
});
+
+describe("RosterRail shell", () => {
+ const renderRail = (agents: SocietyAgent[], props: Partial<RosterRailProps> = {}) => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(<QueryClientProvider client={client}>
+ <RosterRail {...baseProps} activeAgentId={null} {...props} agents={agents} />
+ </QueryClientProvider>);
+ };
+ const waiting = (over: Partial<SocietyAgent> & Pick<SocietyAgent, "agentId" | "name">) =>
+ ({ ...agent({ state: "waiting", ...over }), waiting_reason: { kind: "question", summary: "Which folder?" } }) as SocietyAgent;
+
+ it("groups agents that wait on the person under Needs you, with the reason as the preview", () => {
+ renderRail([agent({ agentId: "a", name: "A" }), waiting({ agentId: "b", name: "B" })]);
+ const section = screen.getByTestId("roster-needs-you");
+ expect(section.textContent).toContain("B");
+ expect(section.textContent).toContain("society.shell.preview_needs_you · Which folder?");
+ expect(section.textContent).not.toContain("A");
+ expect(screen.getByLabelText("society.shell.status_needs_you")).toBeTruthy();
+ });
+
+ it("previews a draft before the last message, then the last message with its time", () => {
+ const now = Date.now();
+ renderRail([agent({ agentId: "a", name: "A" }), agent({ agentId: "b", name: "B" })], {
+ activity: new Map([
+ ["a", { draft: "check the invoices", lastMessage: "Done.", lastMs: now - 5 * 60_000 }],
+ ["b", { lastMessage: "All **three** reports are in.", lastMs: now - 3 * 3_600_000 }],
+ ]),
+ });
+ const previews = screen.getAllByTestId("roster-preview");
+ expect(previews[0].dataset.kind).toBe("draft");
+ expect(previews[0].textContent).toBe("society.shell.preview_draft check the invoices");
+ expect(previews[1].dataset.kind).toBe("message");
+ expect(previews[1].textContent).toBe("All three reports are in.");
+ expect(screen.getByText(/^5\s?m/)).toBeTruthy();
+ });
+
+ it("pins an agent into the face grid and remembers it", () => {
+ const agents = [agent({ agentId: "a", name: "A" }), agent({ agentId: "b", name: "B" })];
+ const { unmount } = renderRail(agents);
+ fireEvent.contextMenu(screen.getByText("B"));
+ fireEvent.click(screen.getByRole("menuitem", { name: "society.shell.pin" }));
+ expect(screen.getByTestId("roster-pins").textContent).toContain("B");
+ expect(JSON.parse(localStorage.getItem("society.roster.pinned.v1") ?? "[]")).toEqual(["b"]);
+ unmount();
+ renderRail(agents);
+ expect(screen.getByTestId("roster-pins").textContent).toContain("B");
+ });
+
+ it("filters to the agents that need the person and offers a way back when none do", () => {
+ renderRail([agent({ agentId: "a", name: "A" }), waiting({ agentId: "b", name: "B" })]);
+ fireEvent.click(screen.getByTestId("roster-filter-needs-you"));
+ expect(screen.queryByText("A")).toBeNull();
+ expect(screen.getByText("B")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("roster-filter-unread"));
+ expect(screen.getByTestId("roster-empty").textContent).toContain("society.shell.empty_unread");
+ fireEvent.click(screen.getByRole("button", { name: "society.shell.show_all" }));
+ expect(screen.getByText("A")).toBeTruthy();
+ expect(localStorage.getItem("society.roster.filter.v1")).toBe("all");
+ });
+
+ it("marks an agent unread from its menu", () => {
+ renderRail([agent({ agentId: "a", name: "A" })]);
+ fireEvent.contextMenu(screen.getByText("A"));
+ fireEvent.click(screen.getByRole("menuitem", { name: "society.shell.mark_unread" }));
+ expect(screen.getByLabelText("society.roster.unread")).toBeTruthy();
+ fireEvent.contextMenu(screen.getByText("A"));
+ fireEvent.click(screen.getByRole("menuitem", { name: "society.shell.mark_read" }));
+ expect(screen.queryByLabelText("society.roster.unread")).toBeNull();
+ });
+
+ it("steps between agents with Alt + Arrow and jumps with Ctrl + digit, pinned first", () => {
+ localStorage.setItem("society.roster.pinned.v1", JSON.stringify(["c"]));
+ const onOpen = vi.fn();
+ renderRail([agent({ agentId: "a", name: "A" }), agent({ agentId: "b", name: "B" }), agent({ agentId: "c", name: "C" })],
+ { keyboard: true, activeAgentId: "a", onOpen });
+ // Visible order: C (pinned), A, B.
+ fireEvent.keyDown(window, { key: "ArrowDown", altKey: true });
+ expect(onOpen).toHaveBeenLastCalledWith("b");
+ fireEvent.keyDown(window, { key: "ArrowUp", altKey: true });
+ expect(onOpen).toHaveBeenLastCalledWith("c");
+ fireEvent.keyDown(window, { key: "1", code: "Digit1", ctrlKey: true });
+ expect(onOpen).toHaveBeenLastCalledWith("c");
+ fireEvent.keyDown(window, { key: "3", code: "Digit3", ctrlKey: true });
+ expect(onOpen).toHaveBeenLastCalledWith("b");
+ expect(onOpen).toHaveBeenCalledTimes(4);
+ });
+
+ it("leaves the keyboard alone when the shortcuts are off or a dialog is open", () => {
+ const onOpen = vi.fn();
+ const { unmount } = renderRail([agent({ agentId: "a", name: "A" }), agent({ agentId: "b", name: "B" })], { activeAgentId: "a", onOpen });
+ fireEvent.keyDown(window, { key: "ArrowDown", altKey: true });
+ expect(onOpen).not.toHaveBeenCalled();
+ unmount();
+ renderRail([agent({ agentId: "a", name: "A" }), agent({ agentId: "b", name: "B" })], { activeAgentId: "a", onOpen, keyboard: true });
+ const modal = document.createElement("div");
+ modal.setAttribute("role", "dialog");
+ modal.setAttribute("aria-modal", "true");
+ document.body.appendChild(modal);
+ fireEvent.keyDown(window, { key: "ArrowDown", altKey: true });
+ expect(onOpen).not.toHaveBeenCalled();
+ modal.remove();
+ });
+
+ it("folds to an avatar rail that still opens agents", () => {
+ const onOpen = vi.fn();
+ const onToggleCollapsed = vi.fn();
+ renderRail([agent({ agentId: "a", name: "A" }), waiting({ agentId: "b", name: "B" })], { collapsed: true, onToggleCollapsed, onOpen });
+ expect(screen.getByTestId("society-roster-rail").dataset.collapsed).toBe("true");
+ fireEvent.click(screen.getByRole("button", { name: "A" }));
+ expect(onOpen).toHaveBeenCalledWith("a");
+ fireEvent.click(screen.getByTestId("roster-expand"));
+ expect(onToggleCollapsed).toHaveBeenCalled();
+ });
+
+ it("lists everyone on the folded rail even while a filter is chosen", () => {
+ localStorage.setItem("society.roster.filter.v1", "needs-you");
+ renderRail([agent({ agentId: "a", name: "A" }), waiting({ agentId: "b", name: "B" })], { collapsed: true });
+ expect(screen.getByRole("button", { name: "A" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "B" })).toBeTruthy();
+ // The choice itself is kept for when the rows come back.
+ expect(localStorage.getItem("society.roster.filter.v1")).toBe("needs-you");
+ });
+
+ it("does not let pins of retired agents fill the pinned places", () => {
+ localStorage.setItem("society.roster.pinned.v1", JSON.stringify(["gone1", "gone2", "gone3", "gone4", "gone5", "gone6", "gone7", "gone8"]));
+ renderRail([agent({ agentId: "a", name: "A" })]);
+ fireEvent.contextMenu(screen.getByText("A"));
+ const pin = screen.getByRole("menuitem", { name: "society.shell.pin" }) as HTMLButtonElement;
+ expect(pin.disabled).toBe(false);
+ fireEvent.click(pin);
+ expect(JSON.parse(localStorage.getItem("society.roster.pinned.v1") ?? "[]")).toEqual(["a"]);
+ });
+
+ it("shows no misleading empty state when every agent is hidden", () => {
+ localStorage.setItem("society.roster.hidden-agent-ids", JSON.stringify(["a"]));
+ renderRail([agent({ agentId: "a", name: "A" })]);
+ expect(screen.queryByTestId("roster-empty")).toBeNull();
+ expect(screen.getByText("society.roster.show_hidden")).toBeTruthy();
+ });
+
+ it("says what to do when there are no agents yet", () => {
+ const onCreate = vi.fn();
+ renderRail([], { onCreate });
+ expect(screen.getByTestId("roster-empty").textContent).toContain("society.shell.empty_agents");
+ fireEvent.click(screen.getByRole("button", { name: "society.shell.new_agent" }));
+ expect(onCreate).toHaveBeenCalled();
+ });
+
+ it("offers a visible New team action", () => {
+ renderRail([agent({ agentId: "a", name: "A" })], { onOpenGroup: () => undefined });
+ expect(screen.getByTestId("society-create-group-button").textContent).toContain("society.groups.create");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.tsx b/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.tsx
index 92b1c79daa..457e3f468f 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/roster/RosterRail.tsx
@@ -1,85 +1,87 @@
/**
- * The fixed agents rail beside the stage (MASTERPLAN §4.1): the lead as a
- * compact centered master above the team — swatch and name in a small box —
- * then a search field and one row per remaining agent, plus the "+" that
- * opens the creator. Names open the chat; avatars open a compact profile
- * dialog without switching the conversation.
+ * The roster: the Agents section's navigation. One dense row per agent, each
+ * with a corner status mark and a single preview line, plus the groups that
+ * keep a long list calm:
*
- * The layout follows the Chef Bot reference: the master is centered and
- * larger, the team stays a compact list below the search. The rail is app
- * chrome: Ink & Paper tokens, both modes. The world beside it carries its
- * own branding; nothing here leaks into the viewport.
+ * - pinned agents as a four-up grid of faces at the top,
+ * - "Needs you" for every agent that waits on the person (it beats unread),
+ * - teams, with a visible "New team" action,
+ * - everyone else, in the person's own drag order.
*
- * It sits on either edge. Beside the island it is the RIGHT rail with its own
- * fixed width; inside the agent card it is the LEFT eighth and takes its width
- * from the grid cell — same rows, same sizes, only the divider swaps sides.
+ * A search box and a filter (all / needs you / unread) narrow the list. The
+ * roster can fold to an avatar rail; the frame decides when it must.
*
- * Reordering is press-and-drag: pressing the left mouse button anywhere on a
- * row and moving it files the agent before or after the row under the
- * pointer. A small movement threshold keeps plain clicks (open chat /
- * 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.
+ * Reordering is press-and-drag: pressing anywhere on a row and moving it
+ * files the agent before or after the row under the pointer. A small
+ * movement threshold keeps plain clicks (open chat / profile) working.
+ * Holding over another row for a moment makes a team; Alt + Shift + Arrow
+ * keys are the keyboard twin of the drag.
+ *
+ * With `keyboard` on, Alt + Arrow Up / Down steps between agents from
+ * anywhere in the section, and Ctrl (Cmd) + 1–9 jumps to the pinned agents,
+ * then the rest in list order. Holding the modifier shows the numbers.
*/
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 { Eye, PanelLeftClose, PanelLeftOpen, Plus, Search, UsersRound, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { useT } from "@/i18n";
+import { useT, useUiLanguage } 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 { RuntimeBadge } from "../RuntimeBadge";
-import type { AgentRunState, SocietyAgent } from "../data";
+import { agentTint } from "../agentTint";
+import type { SocietyAgent } from "../data";
+import "../agentSection.css";
import { AgentRosterActions } from "./AgentRosterActions";
import { GroupRosterActions } from "./GroupRosterActions";
-import { useRosterUnread } from "./useRosterUnread";
+import { useRosterUnreadState } from "./useRosterUnread";
import { ChatGroupDialog } from "../chat/ChatGroupDialog";
+import { RosterRow, StatusMark } from "./RosterRow";
+import { RosterSection } from "./RosterSection";
+import { RosterHoverCard, type HoverCardData } from "./RosterHoverCard";
+import { formatRelative, needsYou, rosterPreview, rosterStatus, waitingReasonOf } from "./rosterPreview";
+import { HIDDEN_AGENTS_KEY, MAX_PINNED, ORDER_KEY, PINNED_KEY, togglePin, usePersistedIds, useRosterFilter, writeIdList, type RosterFilter } from "./rosterPrefs";
+import type { RosterActivityMap } from "./useRosterActivity";
-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;
+/** How long the pointer rests on a row before its hover card shows. */
+const HOVER_CARD_MS = 550;
+/** How long the jump modifier is held before the numbers show. */
+const SHORTCUT_HINT_MS = 450;
type GroupDropTarget = { kind: "agent" | "group"; id: string };
-function readHiddenAgents(): string[] {
- try {
- const value: unknown = JSON.parse(localStorage.getItem(HIDDEN_AGENTS_KEY) ?? "[]");
- return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [];
- } catch {
- return [];
- }
+const AgentProfileDialog = lazy(() => import("../card/AgentProfileDialog").then((module) => ({ default: module.AgentProfileDialog })));
+
+const NO_ACTIVITY: RosterActivityMap = new Map();
+
+function isMacPlatform(): boolean {
+ return typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || "");
}
-/**
- * The person's own row order, newest drag last. Unknown ids (retired agents,
- * a fresh install) are ignored when sorting; agents missing from the list
- * keep their default place at the end until the next drag persists them.
- */
-function readRosterOrder(): string[] {
+function isEditable(target: EventTarget | null): boolean {
+ return target instanceof HTMLElement && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName));
+}
+
+/** A modal over the section owns the keyboard. */
+function modalOpen(): boolean {
+ return Boolean(document.querySelector('[role="dialog"][aria-modal="true"], [role="alertdialog"]'));
+}
+
+function hoverCapable(): boolean {
try {
- const value: unknown = JSON.parse(localStorage.getItem(ORDER_KEY) ?? "[]");
- return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [];
+ return typeof window.matchMedia !== "function" || window.matchMedia("(hover: hover)").matches;
} catch {
- return [];
+ return true;
}
}
-const AgentProfileDialog = lazy(() => import("../card/AgentProfileDialog").then((module) => ({ default: module.AgentProfileDialog })));
-
-const STATE_DOT: Record<AgentRunState, string> = {
- idle: "bg-muted-foreground/50",
- working: "bg-success",
- waiting: "bg-warning",
- paused: "bg-muted-foreground/30",
-};
-
export interface RosterRailProps {
agents: SocietyAgent[];
groups?: SocietyChatGroup[];
@@ -103,6 +105,14 @@ export interface RosterRailProps {
header?: ReactNode;
/** Team actions stay visible below the scrolling roster. */
footer?: ReactNode;
+ /** Last message, time and draft per agent (from the chat stores). */
+ activity?: RosterActivityMap;
+ /** Show the avatar rail instead of rows. */
+ collapsed?: boolean;
+ /** Offers the fold control in the header (and the unfold one on the rail). */
+ onToggleCollapsed?: () => void;
+ /** Section-wide shortcuts: Alt + Arrow between agents, Ctrl/Cmd + 1–9 to jump. */
+ keyboard?: boolean;
}
export function RosterRail({
@@ -122,13 +132,27 @@ export function RosterRail({
className,
header,
footer,
+ activity = NO_ACTIVITY,
+ collapsed = false,
+ onToggleCollapsed,
+ keyboard = false,
}: RosterRailProps) {
const t = useT();
+ const language = useUiLanguage();
const [query, setQuery] = useState("");
+ const [chosenFilter, setFilter] = useRosterFilter();
const [creatingGroup, setCreatingGroup] = useState(false);
const [profileId, setProfileId] = useState<string | null>(null);
- const [hiddenIds, setHiddenIds] = useState(readHiddenAgents);
- const [orderIds, setOrderIds] = useState(readRosterOrder);
+ const [hiddenIds, setHiddenIds] = usePersistedIds(HIDDEN_AGENTS_KEY);
+ const [orderIds, setOrderIds] = useState(() => {
+ try {
+ const value: unknown = JSON.parse(localStorage.getItem(ORDER_KEY) ?? "[]");
+ return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [];
+ } catch {
+ return [];
+ }
+ });
+ const [pinIds, setPinIds] = usePersistedIds(PINNED_KEY);
const [dragId, setDragId] = useState<string | null>(null);
const [dropId, setDropId] = useState<string | null>(null);
const [dropAfter, setDropAfter] = useState(false);
@@ -138,25 +162,40 @@ export function RosterRail({
const [menu, setMenu] = useState<{ agentId: string; x: number; y: number } | null>(null);
const [groupMenu, setGroupMenu] = useState<{ groupId: string; x: number; y: number } | null>(null);
const [editingGroupId, setEditingGroupId] = useState<string | null>(null);
+ const [hover, setHover] = useState<{ agentId: string; anchor: DOMRect } | null>(null);
+ const [showShortcuts, setShowShortcuts] = useState(false);
+ const [now, setNow] = useState(() => Date.now());
const profile = agents.find((agent) => agent.agentId === profileId);
const menuAgent = agents.find((agent) => agent.agentId === menu?.agentId);
const menuGroup = groups.find((group) => group.group_id === groupMenu?.groupId);
const editingGroup = groups.find((group) => group.group_id === editingGroupId);
- const unread = useRosterUnread(agents, activeAgentId);
+ const { unread, mark: markUnread } = useRosterUnreadState(agents, activeAgentId);
const assistantName = useEventStore((state) => state.assistantName);
+ const display = useCallback((agent: SocietyAgent) => societyDisplayName(agent, assistantName), [assistantName]);
- const setHidden = useCallback((agentId: string, hidden: boolean) => {
- setHiddenIds((current) => {
- const next = hidden ? [...new Set([...current, agentId])] : current.filter((id) => id !== agentId);
- localStorage.setItem(HIDDEN_AGENTS_KEY, JSON.stringify(next));
- return next;
- });
+ // Relative times age while the roster stays open.
+ useEffect(() => {
+ const timer = window.setInterval(() => setNow(Date.now()), 60_000);
+ return () => window.clearInterval(timer);
}, []);
+
+ const setHidden = useCallback((agentId: string, hidden: boolean) => {
+ setHiddenIds((current) => (hidden ? [...new Set([...current, agentId])] : current.filter((id) => id !== agentId)));
+ }, [setHiddenIds]);
+ // A pin left behind by a retired agent must not hold one of the places.
+ const livePinCount = pinIds.filter((id) => agents.some((agent) => agent.agentId === id)).length;
+ const onTogglePin = useCallback((agentId: string) => setPinIds((current) => {
+ const known = loading || agents.length === 0
+ ? current
+ : current.filter((id) => agents.some((agent) => agent.agentId === id));
+ return togglePin(known, agentId);
+ }), [agents, loading, setPinIds]);
const closeMenu = useCallback(() => setMenu(null), []);
const openMenu = (event: MouseEvent, agentId: string) => {
event.preventDefault();
event.stopPropagation();
setGroupMenu(null);
+ setHover(null);
setMenu({ agentId, x: event.clientX, y: event.clientY });
};
const openGroupMenu = (event: MouseEvent, groupId: string) => {
@@ -171,29 +210,42 @@ export function RosterRail({
// A group may hold the lead, who wears the assistant's chosen name everywhere.
const memberName = (id: string) => {
const agent = agents.find((row) => row.agentId === id);
- return agent ? societyDisplayName(agent, assistantName) : id;
+ return agent ? display(agent) : id;
};
- const visibleGroups = groups.filter((group) => `${group.name} ${group.members.map(memberName).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;
- 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;
+ // The folded rail has no search box or filter on screen, so it lists
+ // everyone; the person's choice comes back with the rows.
+ const filter: RosterFilter = collapsed ? "all" : chosenFilter;
+ const q = collapsed ? "" : query.trim().toLowerCase();
+ const browsing = q === "" && filter === "all";
+ const visibleGroups = filter === "all"
+ ? groups.filter((group) => `${group.name} ${group.members.map(memberName).join(" ")}`.toLowerCase().includes(q))
+ : [];
+
+ const { pinned, attention, leadRow, rows } = useMemo(() => {
+ const isHidden = (a: SocietyAgent) => !showHidden && hiddenIds.includes(a.agentId);
+ const matches = (a: SocietyAgent) => !q || `${a.name} ${display(a)} ${a.title}`.toLowerCase().includes(q);
+ const passes = (a: SocietyAgent) => filter === "all" || (filter === "needs-you" ? needsYou(a) : unread.has(a.agentId));
+ const shown = (a: SocietyAgent) => !isHidden(a) && matches(a) && passes(a);
+ // Pins are an arrangement of the whole list; while a search or filter
+ // narrows it, they fold back into the excerpt.
+ const pinnedRows = browsing
+ ? pinIds.map((id) => agents.find((a) => a.agentId === id)).filter((a): a is SocietyAgent => Boolean(a) && !isHidden(a!))
+ : [];
+ const pinnedSet = new Set(pinnedRows.map((a) => a.agentId));
+ // Team members wait on the person too; they surface here even though
+ // their team keeps them out of the plain list.
+ const waiting = agents.filter((a) => shown(a) && needsYou(a) && !pinnedSet.has(a.agentId));
+ const waitingSet = new Set(waiting.map((a) => a.agentId));
+ const leadShown = lead && shown(lead) && !pinnedSet.has(lead.agentId) && !waitingSet.has(lead.agentId) ? lead : null;
// Until the teams have answered, a member would be listed on its own and
// jump into its team a moment later; the list waits for the answer instead.
- const rest = teamsPending ? [] : filtered
- .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
- // tier order until the next drag files them in.
+ const rest = teamsPending ? [] : agents.filter((a) => a.agentId !== lead?.agentId && !groupedIds.has(a.agentId)
+ && shown(a) && !pinnedSet.has(a.agentId) && !waitingSet.has(a.agentId));
+ // Orchestrators, then specialists; stable within a tier. 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 settle at the
+ // end in tier order until the next drag files them in.
+ const rank = { lead: 0, orchestrator: 1, specialist: 2 } as const;
const position = new Map(orderIds.map((id, index) => [id, index] as const));
const custom = rest.some((a) => position.has(a.agentId));
rest.sort((a, b) => {
@@ -206,12 +258,24 @@ export function RosterRail({
}
return rank[a.tier] - rank[b.tier];
});
- return { leadVisible: masterVisible, rows: rest };
- }, [agents, assistantName, groupedIds, hiddenIds, lead, orderIds, query, showHidden, teamsPending]);
+ return { pinned: pinnedRows, attention: waiting, leadRow: leadShown, rows: rest };
+ }, [agents, browsing, display, filter, groupedIds, hiddenIds, lead, orderIds, pinIds, q, showHidden, teamsPending, unread]);
+
+ // While searching or filtering, the list is an excerpt — dragging there
+ // would file agents by where they happen to sit in it, so rows stay put.
+ const reorderable = browsing;
- // 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() === "";
+ /** Every agent in the order the person sees them: the keyboard walks this. */
+ const navOrder = useMemo(
+ () => [...pinned, ...attention, ...(leadRow ? [leadRow] : []), ...rows].map((a) => a.agentId),
+ [attention, leadRow, pinned, rows],
+ );
+ const shortcutIds = navOrder.slice(0, 9);
+ const shortcutOf = (agentId: string) => {
+ if (!showShortcuts) return null;
+ const index = shortcutIds.indexOf(agentId);
+ return index === -1 ? null : index + 1;
+ };
/**
* File `fromId` directly before `toId`, or directly after it when `after`
@@ -226,27 +290,14 @@ export function RosterRail({
for (const id of current) if (!known.has(id)) base.push(id);
const without = base.filter((id) => id !== fromId);
const at = without.indexOf(toId);
- if (at === -1) {
- const next = [...without, fromId];
- try {
- localStorage.setItem(ORDER_KEY, JSON.stringify(next));
- } catch {
- // Private mode: the order holds for this window.
- }
- return next;
- }
- const insert = after ? at + 1 : at;
+ const insert = at === -1 ? without.length : after ? at + 1 : at;
const next = [...without.slice(0, insert), fromId, ...without.slice(insert)];
- try {
- localStorage.setItem(ORDER_KEY, JSON.stringify(next));
- } catch {
- // Private mode: the order holds for this window.
- }
+ writeIdList(ORDER_KEY, next);
return next;
});
}, [rows]);
- /** Keyboard twin of the drag: Alt + Arrow Up / Down steps the row. */
+ /** Keyboard twin of the drag: Alt + Shift + Arrow Up / Down steps the row. */
const moveStep = useCallback((agentId: string, delta: -1 | 1) => {
setOrderIds((current) => {
const base = rows.map((a) => a.agentId);
@@ -257,23 +308,78 @@ export function RosterRail({
if (at === -1 || swap < 0 || swap >= base.length) return current;
const next = [...base];
[next[at], next[swap]] = [next[swap], next[at]];
- try {
- localStorage.setItem(ORDER_KEY, JSON.stringify(next));
- } catch {
- // Private mode: the order holds for this window.
- }
+ writeIdList(ORDER_KEY, next);
return next;
});
}, [rows]);
const onRowKeyDown = (event: KeyboardEvent, agentId: string) => {
- if (!reorderable || !event.altKey) return;
+ if (!reorderable || !event.altKey || !event.shiftKey) return;
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
event.preventDefault();
moveStep(agentId, event.key === "ArrowUp" ? -1 : 1);
}
};
+ // --- Section-wide keyboard ----------------------------------------------
+ const navRef = useRef(navOrder);
+ const activeRef = useRef(activeAgentId);
+ const onOpenRef = useRef(onOpen);
+ navRef.current = navOrder;
+ activeRef.current = activeAgentId;
+ onOpenRef.current = onOpen;
+ useEffect(() => {
+ if (!keyboard) return;
+ const mac = isMacPlatform();
+ let hintTimer: number | null = null;
+ const clearHint = () => {
+ if (hintTimer !== null) window.clearTimeout(hintTimer);
+ hintTimer = null;
+ setShowShortcuts(false);
+ };
+ const onKey = (event: globalThis.KeyboardEvent) => {
+ if (event.defaultPrevented || modalOpen()) return;
+ if ((event.key === "Control" || event.key === "Meta") && !event.repeat) {
+ if (hintTimer === null) hintTimer = window.setTimeout(() => setShowShortcuts(true), SHORTCUT_HINT_MS);
+ return;
+ }
+ const order = navRef.current;
+ if (event.altKey && !event.shiftKey && !event.ctrlKey && !event.metaKey
+ && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
+ // On a Mac, Option + Arrow moves the caret inside text; leave it there.
+ if (mac && isEditable(event.target)) return;
+ if (order.length === 0) return;
+ const at = order.indexOf(activeRef.current ?? "");
+ const step = event.key === "ArrowDown" ? 1 : -1;
+ const next = at === -1 ? (step === 1 ? 0 : order.length - 1) : (at + step + order.length) % order.length;
+ event.preventDefault();
+ if (order[next] !== activeRef.current) onOpenRef.current(order[next]);
+ return;
+ }
+ const jump = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
+ if (!jump || event.altKey || event.shiftKey) return;
+ const match = /^(?:Digit|Numpad)([1-9])$/.exec(event.code) ?? /^([1-9])$/.exec(event.key);
+ if (!match) return;
+ const id = order[Number(match[1]) - 1];
+ if (!id) return;
+ event.preventDefault();
+ clearHint();
+ if (id !== activeRef.current) onOpenRef.current(id);
+ };
+ const onKeyUp = (event: globalThis.KeyboardEvent) => {
+ if (event.key === "Control" || event.key === "Meta") clearHint();
+ };
+ window.addEventListener("keydown", onKey);
+ window.addEventListener("keyup", onKeyUp);
+ window.addEventListener("blur", clearHint);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ window.removeEventListener("keyup", onKeyUp);
+ window.removeEventListener("blur", clearHint);
+ if (hintTimer !== null) window.clearTimeout(hintTimer);
+ };
+ }, [keyboard]);
+
// --- Press-and-drag: the whole row is the handle. -----------------------
// One pointer gesture owns both actions. Native HTML drag competes with
// pointermove in WebView and can cancel the gesture before release.
@@ -359,58 +465,56 @@ export function RosterRail({
setDragId(pending.id);
setDropId(null);
setDropAfter(false);
+ setHover(null);
}
if (!sourceId) return;
- {
- const elements = rowElements();
- const sourceEl = elements.find((el) => el.getAttribute("data-agent-id") === sourceId);
- 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);
- }
- return;
+ const elements = rowElements();
+ const sourceEl = elements.find((el) => el.getAttribute("data-agent-id") === sourceId);
+ 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);
}
- }
- 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");
- if (!id || id === sourceId) continue;
- const rect = el.getBoundingClientRect();
- if (rect.height === 0) continue;
- if (event.clientY < rect.top + rect.height / 2) {
- target = { id, after: false };
- break;
- }
- }
- if (!target) {
- const others = elements.filter((el) => el.getAttribute("data-agent-id") !== sourceId);
- const last = others[others.length - 1];
- const lastId = last?.getAttribute("data-agent-id");
- if (lastId) target = { id: lastId, after: true };
- }
- if (target) {
- if (dropIdRef.current !== target.id || dropAfterRef.current !== target.after) {
- setDropId(target.id);
- setDropAfter(target.after);
- }
- } else if (dropIdRef.current !== null) {
- setDropId(null);
- setDropAfter(false);
- }
+ }
+ 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");
+ if (!id || id === sourceId) continue;
+ const rect = el.getBoundingClientRect();
+ if (rect.height === 0) continue;
+ if (event.clientY < rect.top + rect.height / 2) {
+ target = { id, after: false };
+ break;
+ }
+ }
+ if (!target) {
+ const others = elements.filter((el) => el.getAttribute("data-agent-id") !== sourceId);
+ const last = others[others.length - 1];
+ const lastId = last?.getAttribute("data-agent-id");
+ if (lastId) target = { id: lastId, after: true };
+ }
+ if (target) {
+ if (dropIdRef.current !== target.id || dropAfterRef.current !== target.after) {
+ setDropId(target.id);
+ setDropAfter(target.after);
+ }
+ } else if (dropIdRef.current !== null) {
+ setDropId(null);
+ setDropAfter(false);
+ }
+ if (event.cancelable) event.preventDefault();
};
const finish = (commit: boolean, event?: PointerEvent) => {
if (pointerDragRef.current && dragIdRef.current) {
@@ -474,250 +578,402 @@ export function RosterRail({
const openAgent = (agentId: string) => {
if (suppressClickRef.current) return;
+ setHover(null);
onOpen(agentId);
};
const openProfile = (agentId: string) => {
if (suppressClickRef.current) return;
+ setHover(null);
setProfileId(agentId);
};
+ // --- Hover card ----------------------------------------------------------
+ const hoverTimer = useRef<number | null>(null);
+ const endHover = useCallback(() => {
+ if (hoverTimer.current !== null) window.clearTimeout(hoverTimer.current);
+ hoverTimer.current = null;
+ setHover(null);
+ }, []);
+ const startHover = (agentId: string, element: HTMLElement) => {
+ if (dragIdRef.current || menu || !hoverCapable()) return;
+ if (hoverTimer.current !== null) window.clearTimeout(hoverTimer.current);
+ hoverTimer.current = window.setTimeout(() => {
+ hoverTimer.current = null;
+ if (!element.isConnected || dragIdRef.current) return;
+ setHover({ agentId, anchor: element.getBoundingClientRect() });
+ }, HOVER_CARD_MS);
+ };
+ useEffect(() => () => {
+ if (hoverTimer.current !== null) window.clearTimeout(hoverTimer.current);
+ }, []);
+
+ const timeLabel = (agentId: string) => {
+ const at = activity.get(agentId)?.lastMs;
+ return at ? formatRelative(at, now, language, t("society.shell.time_now")) : undefined;
+ };
+
const hiddenCount = agents.filter((agent) => hiddenIds.includes(agent.agentId)).length;
+ const needsYouCount = agents.filter(needsYou).length;
+ const unreadCount = agents.filter((agent) => unread.has(agent.agentId)).length;
+ const canCreateTeam = !sample && Boolean(onOpenGroup);
- return (
- <aside
- ref={railRef}
- data-testid="society-roster-rail"
- className={cn(
- "flex h-full min-h-0 flex-col border-border bg-sidebar",
- side === "left" ? "border-r border-border" : "border-l border-border",
- className ?? "w-[300px] shrink-0",
- )}
- >
- {header}
- <div className="flex items-center justify-between gap-2 px-3 pt-3">
- <div className="flex min-w-0 items-center gap-2">
- <h2 className="font-display text-sm font-semibold tracking-tight text-foreground">
- {t("society.roster.title")}
- </h2>
- {sample ? (
- <Badge variant="outline" className="text-xs">
- {t("society.sample_badge")}
- </Badge>
+ const renderRow = (agent: SocietyAgent, options: { draggable: boolean }) => {
+ const facts = activity.get(agent.agentId);
+ const isUnread = unread.has(agent.agentId);
+ const isDragging = dragId === agent.agentId;
+ const isDropTarget = options.draggable && dropId === agent.agentId && dragId !== agent.agentId;
+ return (
+ <li key={agent.agentId} className="relative">
+ {isDropTarget && !dropAfter && !groupReady ? <div aria-hidden className="as-drop-line top-0 -translate-y-1/2" /> : null}
+ <RosterRow
+ agent={agent}
+ displayName={display(agent)}
+ status={rosterStatus(agent, isUnread)}
+ preview={rosterPreview({ agent, draft: facts?.draft, lastMessage: facts?.lastMessage })}
+ timeLabel={timeLabel(agent.agentId)}
+ active={agent.agentId === activeAgentId}
+ unread={isUnread}
+ hidden={hiddenIds.includes(agent.agentId)}
+ reorderable={reorderable && options.draggable}
+ dragging={isDragging}
+ dropTarget={isDropTarget}
+ groupReady={options.draggable && groupHover?.kind === "agent" && groupHover.id === agent.agentId && groupReady}
+ menuOpen={menu?.agentId === agent.agentId}
+ shortcut={shortcutOf(agent.agentId)}
+ onPointerDown={(event) => (options.draggable ? onRowPointerDown(event, agent.agentId) : undefined)}
+ onClickCapture={onRowClickCapture}
+ onKeyDown={(event) => (options.draggable ? onRowKeyDown(event, agent.agentId) : undefined)}
+ onContextMenu={(event) => openMenu(event, agent.agentId)}
+ onOpen={() => openAgent(agent.agentId)}
+ onOpenProfile={() => openProfile(agent.agentId)}
+ onHoverStart={(element) => startHover(agent.agentId, element)}
+ onHoverEnd={endHover}
+ />
+ {options.draggable && 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="as-drop-line bottom-0 translate-y-1/2" /> : null}
+ </li>
+ );
+ };
+
+ const hoverAgent = hover ? agents.find((agent) => agent.agentId === hover.agentId) : undefined;
+ const hoverData: HoverCardData | null = hover && hoverAgent ? {
+ agent: hoverAgent,
+ displayName: display(hoverAgent),
+ status: rosterStatus(hoverAgent, unread.has(hoverAgent.agentId)),
+ reason: waitingReasonOf(hoverAgent),
+ lastMessage: activity.get(hoverAgent.agentId)?.lastMessage,
+ draft: activity.get(hoverAgent.agentId)?.draft,
+ timeLabel: timeLabel(hoverAgent.agentId),
+ anchor: hover.anchor,
+ } : null;
+
+ const overlays = (
+ <>
+ {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}
+ pinned={pinIds.includes(menu.agentId)} canPin={livePinCount < MAX_PINNED} onTogglePin={onTogglePin}
+ unread={unread.has(menu.agentId)} canMarkUnread={menu.agentId !== activeAgentId} onMarkUnread={markUnread} />}
+ {groupMenu && menuGroup && <GroupRosterActions key={groupMenu.groupId} group={menuGroup} x={groupMenu.x} y={groupMenu.y}
+ onEdit={() => setEditingGroupId(menuGroup.group_id)} onDismiss={() => setGroupMenu(null)} />}
+ {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)} />}
+ {editingGroup && <ChatGroupDialog group={editingGroup} agents={agents} onClose={() => setEditingGroupId(null)} onSaved={(id) => onOpenGroup?.(id)} />}
+ {hoverData && !menu && !dragId ? <RosterHoverCard data={hoverData} /> : null}
+ </>
+ );
+
+ const asideClass = cn(
+ "agent-section as-roster flex h-full min-h-0 flex-col border-border",
+ side === "left" ? "border-r border-border" : "border-l border-border",
+ className ?? (collapsed ? "w-16 shrink-0" : "w-[300px] shrink-0"),
+ );
+
+ if (collapsed) {
+ const railAgents = [...pinned, ...attention, ...(leadRow ? [leadRow] : []), ...rows];
+ return (
+ <aside ref={railRef} data-testid="society-roster-rail" data-collapsed="true" aria-label={t("society.roster.title")} className={asideClass}>
+ <div className="flex flex-col items-center gap-1.5 px-2 pb-2 pt-3">
+ {onToggleCollapsed ? (
+ <button type="button" onClick={onToggleCollapsed} aria-label={t("society.shell.roster_expand")} title={t("society.shell.roster_expand")}
+ className="as-ghost-button h-8 w-8 px-0" data-testid="roster-expand">
+ <PanelLeftOpen className="h-4 w-4" aria-hidden />
+ </button>
) : null}
+ <button type="button" onClick={onCreate} aria-label={t("society.shell.new_agent")} title={t("society.shell.new_agent")}
+ className="as-ink-button h-8 w-8 justify-center rounded-full px-0" data-testid="society-create-button">
+ <Plus className="h-4 w-4" aria-hidden />
+ </button>
</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>}
- <Button
- size="sm"
- variant="secondary"
- className="h-8 gap-1 px-2.5"
- onClick={onCreate}
- data-testid="society-create-button"
- >
+ <ScrollArea className="min-h-0 flex-1">
+ <ul className="flex flex-col items-center gap-1 px-2 pb-3">
+ {railAgents.map((agent) => (
+ <li key={agent.agentId}>
+ <button type="button" onClick={() => openAgent(agent.agentId)} onContextMenu={(event) => openMenu(event, agent.agentId)}
+ aria-label={display(agent)} title={display(agent)} aria-current={agent.agentId === activeAgentId ? "true" : undefined}
+ data-active={agent.agentId === activeAgentId ? "true" : undefined}
+ style={agentTint(agent)}
+ className="as-pin w-12 px-0 py-1.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <span className="as-avatar">
+ <AgentSwatch agent={agent} size={36} />
+ <StatusMark status={rosterStatus(agent, unread.has(agent.agentId))} />
+ {shortcutOf(agent.agentId) !== null ? <span className="as-shortcut-badge" aria-hidden>{shortcutOf(agent.agentId)}</span> : null}
+ </span>
+ </button>
+ </li>
+ ))}
+ {visibleGroups.length > 0 ? <li aria-hidden className="my-1 w-6 border-t border-border" /> : null}
+ {visibleGroups.map((group) => (
+ <li key={group.group_id}>
+ <button type="button" data-group-id={group.group_id} onClick={() => onOpenGroup?.(group.group_id)}
+ aria-label={group.name} title={group.name} aria-current={activeGroupId === group.group_id ? "true" : undefined}
+ data-active={activeGroupId === group.group_id ? "true" : undefined}
+ className="as-pin w-12 px-0 py-1.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <GroupFaces group={group} agents={agents} size={22} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </ScrollArea>
+ {overlays}
+ </aside>
+ );
+ }
+
+ const filterButton = (value: RosterFilter, label: string, count?: number) => (
+ <button key={value} type="button" aria-pressed={filter === value} onClick={() => setFilter(value)}
+ className="as-seg-item" data-testid={`roster-filter-${value}`}>
+ <span className="truncate">{label}</span>
+ {count ? <span className={value === "needs-you" ? "as-seg-count" : "as-seg-count text-muted-foreground"}>{count}</span> : null}
+ </button>
+ );
+
+ const nothingListed = !leadRow && rows.length === 0 && attention.length === 0 && pinned.length === 0 && visibleGroups.length === 0;
+ const showLoading = (teamsPending && rows.length === 0) || (loading && agents.length === 0);
+
+ return (
+ <aside ref={railRef} data-testid="society-roster-rail" className={asideClass}>
+ {header}
+ <div className="flex h-12 shrink-0 items-center gap-1.5 pl-4 pr-2.5">
+ <h2 className="truncate font-display text-[13px] font-semibold tracking-tight text-foreground-strong">
+ {t("society.roster.title")}
+ </h2>
+ {sample ? (
+ <Badge variant="outline" className="text-xs">
+ {t("society.sample_badge")}
+ </Badge>
+ ) : null}
+ <span className="ml-auto" />
+ {onToggleCollapsed ? (
+ <button type="button" onClick={onToggleCollapsed} aria-label={t("society.shell.roster_collapse")} title={t("society.shell.roster_collapse")}
+ className="as-ghost-button h-7 w-7 px-0" data-testid="roster-collapse">
+ <PanelLeftClose className="h-4 w-4" aria-hidden />
+ </button>
+ ) : null}
+ <button type="button" className="as-ink-button" onClick={onCreate} data-testid="society-create-button" title={t("society.shell.new_agent")}>
<Plus className="h-3.5 w-3.5" aria-hidden />
{t("society.roster.create")}
- </Button>
- </div>
+ </button>
+ </div>
+ <div className="flex flex-col gap-2 px-3">
+ <label className="relative block">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" aria-hidden />
+ <input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape" && query) {
+ e.preventDefault();
+ setQuery("");
+ }
+ }}
+ placeholder={t("society.roster.search")}
+ aria-label={t("society.roster.search")}
+ className="h-8 w-full rounded-lg border border-border bg-background pl-8 pr-2 text-[13px] text-foreground placeholder:text-muted-foreground focus-visible:border-border-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
+ />
+ </label>
+ {agents.length > 1 ? (
+ <div role="group" aria-label={t("society.shell.filter_label")} className="as-seg">
+ {filterButton("all", t("society.shell.filter_all"))}
+ {filterButton("needs-you", t("society.shell.filter_needs_you"), needsYouCount)}
+ {filterButton("unread", t("society.shell.filter_unread"), unreadCount)}
+ </div>
+ ) : null}
+ {hiddenCount > 0 && <button type="button" onClick={() => setShowHidden((value) => !value)}
+ className="-mx-1 flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <Eye className="h-3.5 w-3.5" aria-hidden />
+ {t(showHidden ? "society.roster.hide_hidden" : "society.roster.show_hidden").replace("{0}", String(hiddenCount))}
+ </button>}
</div>
- <label className="relative mx-3 mt-3 block">
- <Search
- className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
- aria-hidden
- />
- <input
- type="search"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- placeholder={t("society.roster.search")}
- aria-label={t("society.roster.search")}
- className="h-8 w-full rounded-md border border-border bg-background pl-8 pr-2 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"
- />
- </label>
- {hiddenCount > 0 && <button type="button" onClick={() => setShowHidden((value) => !value)}
- className="mx-3 mt-2 flex items-center gap-1.5 rounded-md px-2 py-1 text-left text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <Eye className="h-3.5 w-3.5" aria-hidden />
- {t(showHidden ? "society.roster.hide_hidden" : "society.roster.show_hidden").replace("{0}", String(hiddenCount))}
- </button>}
<ScrollArea className="mt-2 min-h-0 flex-1">
- {lead && leadVisible ? (
- <div className="flex justify-center px-2 pb-2">
- <div
- data-testid="society-lead-hero"
- onContextMenu={(event) => openMenu(event, lead.agentId)}
- className={cn(
- "flex flex-col items-center gap-1.5 rounded-xl bg-secondary/50 px-5 py-3 text-center transition-colors hover:bg-secondary/80",
- lead.agentId === activeAgentId && "bg-secondary",
- )}
- >
- <button type="button" onClick={() => openProfile(lead.agentId)} aria-label={t("society.profile_card.open").replace("{0}", societyDisplayName(lead, assistantName))} className="relative rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <AgentSwatch agent={lead} size={56} />
- {lead.state === "working" ? (
- <span
- role="status"
- aria-label={t("society.roster.thinking")}
- title={t("society.roster.thinking")}
- className="absolute -right-1 -top-1 grid h-5 w-5 place-items-center rounded-full bg-sidebar ring-2 ring-sidebar"
- >
- <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
+ <div className="flex flex-col gap-2.5 px-2 pb-3">
+ {pinned.length > 0 ? (
+ <div className="as-pins" role="list" aria-label={t("society.shell.pinned")} data-testid="roster-pins">
+ {pinned.map((agent) => (
+ <button key={agent.agentId} type="button" role="listitem" data-pinned-id={agent.agentId}
+ onClick={() => openAgent(agent.agentId)} onContextMenu={(event) => openMenu(event, agent.agentId)}
+ aria-current={agent.agentId === activeAgentId ? "true" : undefined}
+ data-active={agent.agentId === activeAgentId ? "true" : undefined}
+ title={display(agent)} style={agentTint(agent)}
+ className="as-pin focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <span className="as-avatar">
+ <AgentSwatch agent={agent} size={40} />
+ <StatusMark status={rosterStatus(agent, unread.has(agent.agentId))} />
+ {shortcutOf(agent.agentId) !== null ? <span className="as-shortcut-badge" aria-hidden>{shortcutOf(agent.agentId)}</span> : null}
</span>
- ) : unread.has(lead.agentId) ? (
- <span
- aria-label={t("society.roster.unread")}
- title={t("society.roster.unread")}
- className="absolute -right-0.5 -top-0.5 h-3 w-3 rounded-full bg-sky-400 ring-2 ring-sidebar"
- />
- ) : null}
- </button>
- <button type="button" onClick={() => openAgent(lead.agentId)} aria-current={lead.agentId === activeAgentId ? "true" : undefined} className="flex max-w-full items-center justify-center gap-1.5 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <span className="truncate text-sm font-medium text-foreground">{societyDisplayName(lead, assistantName)}</span>
- <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-xs">
- {t("society.tier.lead")}
- </Badge>
- </button>
+ <span className="as-pin-name">{display(agent)}</span>
+ </button>
+ ))}
</div>
- </div>
- ) : null}
- {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)} onContextMenu={(event) => openGroupMenu(event, 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.lead_agent_id
- ? `${t("society.lead.rail").replace("{0}", memberName(group.lead_agent_id))} · ${group.members.filter((id) => id !== group.lead_agent_id).map(memberName).join(", ")}`
- : group.members.map(memberName).join(", ")}</span>
- </span>
- </button>
- </li>)}
- </ul>}
- <ul ref={listRef} className="flex flex-col gap-0.5 px-2 pb-3">
- {(teamsPending || (loading && !leadVisible)) && rows.length === 0 ? (
- <li className="px-2 py-3 text-xs text-muted-foreground">{t("society.roster.loading")}</li>
) : null}
- {!loading && !teamsPending && !leadVisible && rows.length === 0 && visibleGroups.length === 0 ? (
- <li className="px-2 py-3 text-xs text-muted-foreground">{t("society.roster.empty")}</li>
+ {attention.length > 0 ? (
+ <RosterSection id="needs-you" title={t("society.shell.section_needs_you")} count={attention.length} tone="attention">
+ <ul className="flex flex-col gap-1" data-testid="roster-needs-you">
+ {attention.map((agent) => renderRow(agent, { draggable: false }))}
+ </ul>
+ </RosterSection>
) : null}
- {rows.map((agent) => {
- const isDragging = dragId === agent.agentId;
- const isDropTarget = dropId === agent.agentId && dragId !== agent.agentId;
- return (
- <li key={agent.agentId} className="relative">
- {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}
- <div
- data-agent-id={agent.agentId}
- onPointerDown={(event) => onRowPointerDown(event, agent.agentId)}
- onClickCapture={onRowClickCapture}
- onKeyDown={(event) => onRowKeyDown(event, agent.agentId)}
- onContextMenu={(event) => openMenu(event, agent.agentId)}
- title={reorderable ? `${t("society.roster.reorder")} · ${t("society.roster.reorder_keys")}` : undefined}
- aria-keyshortcuts={reorderable ? "Alt+ArrowUp Alt+ArrowDown" : undefined}
- className={cn(
- "flex w-full select-none items-center rounded-md px-2 text-left transition-colors hover:bg-secondary",
- reorderable ? "cursor-grab" : null,
- isDragging ? "cursor-grabbing opacity-40" : null,
- 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">
- <span className="relative flex">
- <AgentSwatch agent={agent} size={48} />
- {agent.tier !== "lead" ? <RuntimeBadge runtime={agent.runtime} className="absolute bottom-0.5 right-0.5" /> : null}
- </span>
- </button>
- <button type="button" onClick={() => openAgent(agent.agentId)} aria-current={agent.agentId === activeAgentId ? "true" : undefined} className="flex min-w-0 flex-1 select-none items-center gap-2.5 rounded-md py-2 pl-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <span className="min-w-0 flex-1">
- <span className="flex items-center gap-1.5">
- <span className="truncate text-sm font-medium text-foreground">{agent.name}</span>
- {agent.tier === "lead" ? (
- <Badge variant="secondary" className="px-1.5 py-0 text-xs">
- {t("society.tier.lead")}
- </Badge>
- ) : null}
- </span>
- <span className="block truncate text-xs text-muted-foreground">{agent.title}</span>
- </span>
- <RowStatus agent={agent} hasUnread={unread.has(agent.agentId)} />
- </button>
- </div>
- {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" />
+ {(visibleGroups.length > 0 || (canCreateTeam && browsing)) ? (
+ <RosterSection id="teams" title={t("society.shell.section_teams")} count={visibleGroups.length || undefined}>
+ <ul className="flex flex-col gap-1">
+ {visibleGroups.map((group) => {
+ const hovered = groupHover?.kind === "group" && groupHover.id === group.group_id;
+ const members = group.members.filter((id) => agents.some((agent) => agent.agentId === id));
+ return (
+ <li key={group.group_id}>
+ <button type="button" data-group-id={group.group_id} onClick={() => onOpenGroup?.(group.group_id)} onContextMenu={(event) => openGroupMenu(event, group.group_id)} aria-current={activeGroupId === group.group_id ? "true" : undefined}
+ data-active={activeGroupId === group.group_id ? "true" : undefined}
+ data-group-ready={hovered && groupReady ? "true" : undefined}
+ data-drop={hovered && !groupReady ? "true" : undefined}
+ className="as-row focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ data-testid={`society-group-${group.group_id}`}>
+ <span className="flex w-9 shrink-0 items-center justify-center">
+ <GroupFaces group={group} agents={agents} size={24} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="as-row-name block">{group.name}</span>
+ <span className="as-row-preview">{hovered
+ ? t(groupReady ? "society.groups.release_to_group" : "society.groups.hold_to_group")
+ : members.length === 0
+ ? t("society.shell.team_empty")
+ : group.lead_agent_id
+ ? `${t("society.lead.rail").replace("{0}", memberName(group.lead_agent_id))} · ${group.members.filter((id) => id !== group.lead_agent_id).map(memberName).join(", ")}`
+ : group.members.map(memberName).join(", ")}</span>
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ {canCreateTeam && browsing ? (
+ <li>
+ <button type="button" onClick={() => setCreatingGroup(true)} data-testid="society-create-group-button"
+ className="flex h-9 w-full items-center gap-2 rounded-[10px] px-2.5 text-left text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <span className="grid h-6 w-6 place-items-center rounded-full border border-dashed border-border-strong">
+ <UsersRound className="h-3.5 w-3.5" aria-hidden />
+ </span>
+ {t("society.groups.create")}
+ </button>
+ </li>
+ ) : null}
+ </ul>
+ </RosterSection>
+ ) : null}
+ {(leadRow || rows.length > 0) ? (
+ <RosterSection id="agents" title={t("society.shell.section_agents")} count={rows.length + (leadRow ? 1 : 0)}>
+ {leadRow ? (
+ <ul className="flex flex-col gap-1">
+ {renderRow(leadRow, { draggable: false })}
+ </ul>
) : null}
- </li>
- );
- })}
- </ul>
+ <ul ref={listRef} className={cn("flex flex-col gap-1", leadRow && rows.length > 0 && "mt-1")}>
+ {rows.map((agent) => renderRow(agent, { draggable: true }))}
+ </ul>
+ </RosterSection>
+ ) : <ul ref={listRef} className="hidden" />}
+ {showLoading ? (
+ <p className="px-2 py-3 text-xs text-muted-foreground">{t("society.roster.loading")}</p>
+ ) : null}
+ {/* Under "All" with no search, an empty list means everyone is
+ hidden; the show-hidden control above already says so. */}
+ {!showLoading && !loading && nothingListed && (agents.length === 0 || q !== "" || filter !== "all") ? (
+ <EmptyState
+ filter={filter}
+ searching={q !== ""}
+ noAgents={agents.length === 0}
+ onShowAll={() => setFilter("all")}
+ onClearSearch={() => setQuery("")}
+ onCreate={onCreate}
+ />
+ ) : null}
+ </div>
</ScrollArea>
{footer}
- {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} />}
- {groupMenu && menuGroup && <GroupRosterActions key={groupMenu.groupId} group={menuGroup} x={groupMenu.x} y={groupMenu.y}
- onEdit={() => setEditingGroupId(menuGroup.group_id)} onDismiss={() => setGroupMenu(null)} />}
- {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)} />}
- {editingGroup && <ChatGroupDialog group={editingGroup} agents={agents} onClose={() => setEditingGroupId(null)} onSaved={(id) => onOpenGroup?.(id)} />}
+ {overlays}
</aside>
);
}
-/**
- * The three states the roster dot can be in: thinking (a loading spinner
- * while `state` is working), fresh results (green until the row is opened),
- * or the plain backend state (grey idle, amber waiting, faint paused).
- */
-function RowStatus({ agent, hasUnread }: { agent: SocietyAgent; hasUnread: boolean }) {
+/** Up to three member faces, overlapped. */
+function GroupFaces({ group, agents, size }: { group: SocietyChatGroup; agents: SocietyAgent[]; size: number }) {
+ const members = group.members
+ .map((id) => agents.find((agent) => agent.agentId === id))
+ .filter((agent): agent is SocietyAgent => Boolean(agent))
+ .slice(0, 3);
+ if (members.length === 0) {
+ return <span className="grid place-items-center rounded-full border border-dashed border-border-strong text-muted-foreground" style={{ width: size, height: size }}>
+ <UsersRound className="h-3 w-3" aria-hidden />
+ </span>;
+ }
+ return (
+ <span className="flex items-center">
+ {members.map((member, index) => (
+ <span key={member.agentId} className={cn("rounded-full ring-2 ring-sidebar", index > 0 && "-ml-2.5")}>
+ <AgentSwatch agent={member} size={size} />
+ </span>
+ ))}
+ </span>
+ );
+}
+
+/** One sentence and one action: what would appear here and how it gets there. */
+function EmptyState({ filter, searching, noAgents, onShowAll, onClearSearch, onCreate }: {
+ filter: RosterFilter;
+ searching: boolean;
+ noAgents: boolean;
+ onShowAll: () => void;
+ onClearSearch: () => void;
+ onCreate: () => void;
+}) {
const t = useT();
- if (agent.state === "working") {
- const label = t("society.roster.thinking");
+ if (noAgents) {
return (
- <span
- role="status"
- aria-label={label}
- title={label}
- className="grid h-4 w-4 shrink-0 place-items-center"
- >
- <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" aria-hidden />
- </span>
+ <div className="as-empty" data-testid="roster-empty">
+ <p>{t("society.shell.empty_agents")}</p>
+ <button type="button" className="as-ink-button" onClick={onCreate}>
+ <Plus className="h-3.5 w-3.5" aria-hidden />{t("society.shell.new_agent")}
+ </button>
+ </div>
);
}
- if (hasUnread) {
- const label = t("society.roster.unread");
+ if (searching) {
return (
- <span
- className="h-2 w-2 shrink-0 rounded-full bg-sky-400"
- title={label}
- aria-label={label}
- />
+ <div className="as-empty" data-testid="roster-empty">
+ <p>{t("society.roster.empty")}</p>
+ <button type="button" className="as-ghost-button -ml-2" onClick={onClearSearch}>
+ <X className="h-3.5 w-3.5" aria-hidden />{t("society.shell.clear_search")}
+ </button>
+ </div>
);
}
return (
- <span
- className={cn("h-2 w-2 shrink-0 rounded-full", STATE_DOT[agent.state])}
- title={t(`society.state.${agent.state}`)}
- aria-label={t(`society.state.${agent.state}`)}
- />
+ <div className="as-empty" data-testid="roster-empty">
+ <p>{t(filter === "needs-you" ? "society.shell.empty_needs_you" : "society.shell.empty_unread")}</p>
+ <button type="button" className="as-ghost-button -ml-2" onClick={onShowAll}>{t("society.shell.show_all")}</button>
+ </div>
);
}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/RosterRow.tsx b/dodaios/ui/web/frontend/src/components/society/roster/RosterRow.tsx
new file mode 100644
index 0000000000..baef2d5a85
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/RosterRow.tsx
@@ -0,0 +1,204 @@
+/**
+ * One dense roster row: a 36px face with a corner status mark, the name with a
+ * relative time, and one preview line. The avatar opens the agent's profile,
+ * the rest of the row opens its chat, and the whole row is the drag handle.
+ */
+import type {
+ KeyboardEvent,
+ MouseEvent,
+ PointerEvent as ReactPointerEvent,
+} from "react";
+import { MoreHorizontal } from "lucide-react";
+
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+import { AgentSwatch } from "../AgentSwatch";
+import { RuntimeMark } from "../RuntimeBadge";
+import { agentTint } from "../agentTint";
+import type { SocietyAgent } from "../data";
+import type { RosterPreview, RosterStatus } from "./rosterPreview";
+
+export function StatusMark({ status, className }: { status: RosterStatus; className?: string }) {
+ const t = useT();
+ const label = statusLabel(status, t);
+ return (
+ <span
+ role={status === "working" ? "status" : undefined}
+ aria-label={label}
+ title={label}
+ data-status={status}
+ data-testid="roster-status"
+ className={cn("as-status", className)}
+ />
+ );
+}
+
+export function statusLabel(status: RosterStatus, t: (key: string) => string): string {
+ switch (status) {
+ case "needs-you":
+ return t("society.shell.status_needs_you");
+ case "working":
+ return t("society.roster.thinking");
+ case "unread":
+ return t("society.roster.unread");
+ case "paused":
+ return t("society.state.paused");
+ default:
+ return t("society.state.idle");
+ }
+}
+
+export function PreviewLine({ preview, className }: { preview: RosterPreview; className?: string }) {
+ const t = useT();
+ if (preview.kind === "waiting") {
+ return (
+ <span className={cn("as-row-preview", className)} data-kind="waiting" data-testid="roster-preview">
+ <span className="as-preview-tag">{t("society.shell.preview_needs_you")}</span>
+ {preview.text ? <> · {preview.text}</> : null}
+ </span>
+ );
+ }
+ if (preview.kind === "draft") {
+ return (
+ <span className={cn("as-row-preview", className)} data-kind="draft" data-testid="roster-preview">
+ <span className="as-preview-tag">{t("society.shell.preview_draft")}</span> {preview.text}
+ </span>
+ );
+ }
+ return (
+ <span className={cn("as-row-preview", className)} data-kind={preview.kind} data-testid="roster-preview">
+ {preview.text}
+ </span>
+ );
+}
+
+export interface RosterRowProps {
+ agent: SocietyAgent;
+ displayName: string;
+ status: RosterStatus;
+ preview: RosterPreview;
+ timeLabel?: string;
+ active: boolean;
+ unread: boolean;
+ hidden: boolean;
+ reorderable: boolean;
+ dragging: boolean;
+ dropTarget: boolean;
+ groupReady: boolean;
+ menuOpen: boolean;
+ /** 1–9 while the jump modifier is held; null otherwise. */
+ shortcut: number | null;
+ onPointerDown: (event: ReactPointerEvent) => void;
+ onClickCapture: (event: MouseEvent) => void;
+ onKeyDown: (event: KeyboardEvent) => void;
+ onContextMenu: (event: MouseEvent) => void;
+ onOpen: () => void;
+ onOpenProfile: () => void;
+ onHoverStart: (element: HTMLElement) => void;
+ onHoverEnd: () => void;
+}
+
+export function RosterRow({
+ agent,
+ displayName,
+ status,
+ preview,
+ timeLabel,
+ active,
+ unread,
+ hidden,
+ reorderable,
+ dragging,
+ dropTarget,
+ groupReady,
+ menuOpen,
+ shortcut,
+ onPointerDown,
+ onClickCapture,
+ onKeyDown,
+ onContextMenu,
+ onOpen,
+ onOpenProfile,
+ onHoverStart,
+ onHoverEnd,
+}: RosterRowProps) {
+ const t = useT();
+ const external = agent.runtime && agent.runtime !== "jarvis" ? agent.runtime : null;
+ return (
+ <div
+ data-agent-id={agent.agentId}
+ data-active={active ? "true" : undefined}
+ data-dragging={dragging ? "true" : undefined}
+ data-drop={dropTarget ? "true" : undefined}
+ data-group-ready={groupReady ? "true" : undefined}
+ data-menu-open={menuOpen ? "true" : undefined}
+ onPointerDown={onPointerDown}
+ onClickCapture={onClickCapture}
+ onKeyDown={onKeyDown}
+ onContextMenu={onContextMenu}
+ onPointerEnter={(event) => {
+ if (event.pointerType === "mouse" || event.pointerType === undefined) onHoverStart(event.currentTarget);
+ }}
+ onPointerLeave={onHoverEnd}
+ title={reorderable ? `${t("society.roster.reorder")} · ${t("society.shell.reorder_keys")}` : undefined}
+ aria-keyshortcuts={reorderable ? "Alt+Shift+ArrowUp Alt+Shift+ArrowDown" : undefined}
+ style={agentTint(agent)}
+ className={cn(
+ "as-row as-reveal-host select-none",
+ reorderable ? "cursor-grab" : null,
+ dragging ? "cursor-grabbing" : null,
+ hidden && "opacity-60",
+ )}
+ >
+ <button
+ type="button"
+ onClick={onOpenProfile}
+ aria-label={t("society.profile_card.open").replace("{0}", displayName)}
+ className="as-avatar rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <AgentSwatch agent={agent} size={36} />
+ <StatusMark status={status} />
+ {shortcut !== null ? <span className="as-shortcut-badge" aria-hidden>{shortcut}</span> : null}
+ </button>
+ <button
+ type="button"
+ onClick={onOpen}
+ aria-current={active ? "true" : undefined}
+ className="flex min-w-0 flex-1 select-none flex-col justify-center gap-0.5 self-stretch rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className={cn("as-row-name", unread && "font-semibold text-foreground-strong")}>{displayName}</span>
+ {external ? (
+ <span className="inline-flex shrink-0 [&_img]:size-3.5" title={t(`society.runtime.${external}`)}>
+ <RuntimeMark runtime={external} label={t(`society.runtime.${external}`)} />
+ </span>
+ ) : null}
+ {agent.tier === "lead" ? (
+ <span className="shrink-0 rounded-[5px] bg-secondary px-1.5 text-[10px] font-medium leading-4 text-muted-foreground">
+ {t("society.tier.lead")}
+ </span>
+ ) : null}
+ {timeLabel ? <span className="as-row-time ml-auto pl-1">{timeLabel}</span> : null}
+ </span>
+ {" "}
+ <PreviewLine preview={preview} />
+ </button>
+ <button
+ type="button"
+ aria-label={t("society.roster.menu")}
+ aria-haspopup="menu"
+ aria-expanded={menuOpen}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onContextMenu(event);
+ }}
+ className="as-reveal as-ghost-button -mr-1 h-7 min-w-7 shrink-0 px-0"
+ data-testid="roster-row-more"
+ >
+ <MoreHorizontal className="h-4 w-4" aria-hidden />
+ </button>
+ </div>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/RosterSection.tsx b/dodaios/ui/web/frontend/src/components/society/roster/RosterSection.tsx
new file mode 100644
index 0000000000..34d25ea5f4
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/RosterSection.tsx
@@ -0,0 +1,86 @@
+/**
+ * A titled group of roster rows ("Needs you", "Teams", "Agents"). The heading
+ * carries a count and folds the group; the fold is remembered per section.
+ */
+import { useCallback, useId, useState, type ReactNode } from "react";
+import { ChevronDown } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+const COLLAPSED_KEY = "society.roster.sections.collapsed.v1";
+
+function readCollapsed(): string[] {
+ try {
+ const value: unknown = JSON.parse(localStorage.getItem(COLLAPSED_KEY) ?? "[]");
+ return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+export function useSectionFold(sectionId: string): [boolean, () => void] {
+ const [folded, setFolded] = useState(() => readCollapsed().includes(sectionId));
+ const toggle = useCallback(() => {
+ setFolded((value) => {
+ const next = !value;
+ const stored = readCollapsed().filter((id) => id !== sectionId);
+ try {
+ localStorage.setItem(COLLAPSED_KEY, JSON.stringify(next ? [...stored, sectionId] : stored));
+ } catch {
+ // Private mode: the fold holds for this window.
+ }
+ return next;
+ });
+ }, [sectionId]);
+ return [folded, toggle];
+}
+
+export function RosterSection({
+ id,
+ title,
+ count,
+ tone,
+ action,
+ children,
+ className,
+}: {
+ id: string;
+ title: string;
+ count?: number;
+ /** "attention" colours the heading for the Needs-you group. */
+ tone?: "attention";
+ /** A small trailing control in the heading. */
+ action?: ReactNode;
+ children: ReactNode;
+ className?: string;
+}) {
+ const [folded, toggle] = useSectionFold(id);
+ const bodyId = useId();
+ return (
+ <section className={cn("flex flex-col", className)} data-testid={`roster-section-${id}`} aria-label={title}>
+ <div className="as-section-head as-reveal-host">
+ <button
+ type="button"
+ onClick={toggle}
+ aria-expanded={!folded}
+ aria-controls={bodyId}
+ className={cn(
+ "-ml-1 flex min-w-0 items-center gap-1 rounded px-1 py-0.5 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ tone === "attention" && "text-warning hover:text-warning",
+ )}
+ >
+ <span className="truncate">{title}</span>
+ {count !== undefined ? <span className="as-section-count">{count}</span> : null}
+ <ChevronDown
+ aria-hidden
+ className={cn("as-reveal h-3 w-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none", folded && "-rotate-90")}
+ />
+ </button>
+ {action ? <span className="ml-auto flex items-center">{action}</span> : null}
+ </div>
+ <div id={bodyId} hidden={folded}>
+ {children}
+ </div>
+ </section>
+ );
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/rosterPrefs.ts b/dodaios/ui/web/frontend/src/components/society/roster/rosterPrefs.ts
new file mode 100644
index 0000000000..bc64b0a2d3
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/rosterPrefs.ts
@@ -0,0 +1,78 @@
+/**
+ * The person's own arrangement of the roster, kept in this browser profile:
+ * which agents are hidden, the hand-made order, the pinned agents and the
+ * list filter. Every read survives bad or missing storage (private mode, a
+ * hand-edited value) by falling back to the default.
+ */
+import { useCallback, useState } from "react";
+
+export const HIDDEN_AGENTS_KEY = "society.roster.hidden-agent-ids";
+export const ORDER_KEY = "society.roster.order";
+export const PINNED_KEY = "society.roster.pinned.v1";
+export const FILTER_KEY = "society.roster.filter.v1";
+
+/** Two rows of four pinned tiles; a ninth pin would only push one off screen. */
+export const MAX_PINNED = 8;
+
+export type RosterFilter = "all" | "needs-you" | "unread";
+const FILTERS: readonly RosterFilter[] = ["all", "needs-you", "unread"];
+
+export function readIdList(key: string): string[] {
+ try {
+ const value: unknown = JSON.parse(localStorage.getItem(key) ?? "[]");
+ return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+export function writeIdList(key: string, ids: string[]): void {
+ try {
+ localStorage.setItem(key, JSON.stringify(ids));
+ } catch {
+ // Private mode: the arrangement holds for this window.
+ }
+}
+
+export function readFilter(): RosterFilter {
+ try {
+ const value = localStorage.getItem(FILTER_KEY);
+ return FILTERS.includes(value as RosterFilter) ? (value as RosterFilter) : "all";
+ } catch {
+ return "all";
+ }
+}
+
+/** A persisted id list with a setter that writes through. */
+export function usePersistedIds(key: string): [string[], (update: (current: string[]) => string[]) => void] {
+ const [ids, setIds] = useState(() => readIdList(key));
+ const update = useCallback((fn: (current: string[]) => string[]) => {
+ setIds((current) => {
+ const next = fn(current);
+ if (next === current) return current;
+ writeIdList(key, next);
+ return next;
+ });
+ }, [key]);
+ return [ids, update];
+}
+
+/** Pin or unpin; a new pin goes last, and the list never grows past `MAX_PINNED`. */
+export function togglePin(current: string[], agentId: string): string[] {
+ if (current.includes(agentId)) return current.filter((id) => id !== agentId);
+ if (current.length >= MAX_PINNED) return current;
+ return [...current, agentId];
+}
+
+export function useRosterFilter(): [RosterFilter, (filter: RosterFilter) => void] {
+ const [filter, setFilter] = useState(readFilter);
+ const update = useCallback((next: RosterFilter) => {
+ setFilter(next);
+ try {
+ localStorage.setItem(FILTER_KEY, next);
+ } catch {
+ // Private mode: the filter holds for this window.
+ }
+ }, []);
+ return [filter, update];
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts
new file mode 100644
index 0000000000..8b4c0409ef
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+
+import type { SocietyAgent } from "../data";
+import { formatRelative, needsYou, previewText, relativeStamp, rosterPreview, rosterStatus, waitingReasonOf } from "./rosterPreview";
+
+function agent(over: Partial<SocietyAgent> & Record<string, unknown> = {}): SocietyAgent {
+ return {
+ agentId: "a",
+ name: "Scout",
+ title: "Research scout",
+ state: "idle",
+ tier: "specialist",
+ ...over,
+ } as SocietyAgent;
+}
+
+const reason = { kind: "question", summary: "Which **folder** should I use?", session_id: "s1", ref_id: "q1" };
+
+describe("rosterPreview priority", () => {
+ it("puts the waiting reason above a draft and the last message", () => {
+ const preview = rosterPreview({ agent: agent({ waiting_reason: reason }), draft: "half a thought", lastMessage: "Done." });
+ expect(preview).toEqual({ kind: "waiting", text: "Which folder should I use?" });
+ });
+
+ it("falls back to the plain waiting state when the backend sends no reason", () => {
+ expect(rosterPreview({ agent: agent({ state: "waiting" }), draft: "draft", lastMessage: "Done." })).toEqual({ kind: "waiting", text: "" });
+ });
+
+ it("shows the person's draft above the last message", () => {
+ expect(rosterPreview({ agent: agent(), draft: " check the invoices ", lastMessage: "Done." })).toEqual({ kind: "draft", text: "check the invoices" });
+ });
+
+ it("shows the last message, then the role", () => {
+ expect(rosterPreview({ agent: agent(), lastMessage: "All three reports are in." })).toEqual({ kind: "message", text: "All three reports are in." });
+ expect(rosterPreview({ agent: agent() })).toEqual({ kind: "role", text: "Research scout" });
+ });
+
+ it("keeps the last message while the agent works; the corner mark shows the work", () => {
+ expect(rosterPreview({ agent: agent({ state: "working" }), lastMessage: "On it." })).toEqual({ kind: "message", text: "On it." });
+ });
+});
+
+describe("rosterStatus", () => {
+ it("ranks needs-you over working over unread", () => {
+ expect(rosterStatus(agent({ state: "working", waiting_reason: reason }), true)).toBe("needs-you");
+ expect(rosterStatus(agent({ state: "waiting" }), true)).toBe("needs-you");
+ expect(rosterStatus(agent({ state: "working" }), true)).toBe("working");
+ expect(rosterStatus(agent(), true)).toBe("unread");
+ expect(rosterStatus(agent({ state: "paused" }), false)).toBe("paused");
+ expect(rosterStatus(agent(), false)).toBe("idle");
+ });
+
+ it("reads the waiting reason in either spelling and ignores unknown kinds", () => {
+ expect(waitingReasonOf(agent({ waitingReason: { kind: "approval", summary: "Send the mail?", sessionId: "s" } })))
+ .toEqual({ kind: "approval", summary: "Send the mail?", sessionId: "s" });
+ expect(waitingReasonOf(agent({ waiting_reason: { kind: "something-else", summary: "x" } }))).toBeNull();
+ expect(needsYou(agent({ waiting_reason: null }))).toBe(false);
+ });
+});
+
+describe("previewText", () => {
+ it("drops ask blocks, routing markers, code and markdown", () => {
+ const raw = "Here is the **plan**.\n[to jarvis]\n```ts\nconst x = 1;\n```\nSee [the doc](https://example.test).\n```jarvis-ask\n{\"questions\": []}\n```";
+ expect(previewText(raw)).toBe("Here is the plan . See the doc.");
+ });
+
+ it("keeps a line that merely starts with a link", () => {
+ expect(previewText("[The report](https://example.test) is ready.")).toBe("The report is ready.");
+ });
+
+ it("caps long lines", () => {
+ const text = previewText("word ".repeat(100));
+ expect(text.length).toBeLessThanOrEqual(160);
+ expect(text.endsWith("…")).toBe(true);
+ });
+});
+
+describe("relative times", () => {
+ const now = Date.UTC(2026, 9, 26, 12, 0, 0);
+ it("buckets into now, minutes, hours, days and a date", () => {
+ expect(relativeStamp(now - 20_000, now)).toEqual({ unit: "now" });
+ expect(relativeStamp(now - 5 * 60_000, now)).toEqual({ unit: "minute", value: 5 });
+ expect(relativeStamp(now - 3 * 3_600_000, now)).toEqual({ unit: "hour", value: 3 });
+ expect(relativeStamp(now - 2 * 86_400_000, now)).toEqual({ unit: "day", value: 2 });
+ expect(relativeStamp(now - 30 * 86_400_000, now).unit).toBe("date");
+ });
+
+ it("formats short, localised labels", () => {
+ expect(formatRelative(now - 10_000, now, "en", "now")).toBe("now");
+ expect(formatRelative(now - 5 * 60_000, now, "en", "now")).toMatch(/^5\s?m/);
+ expect(formatRelative(now - 3 * 3_600_000, now, "en", "now")).toMatch(/^3\s?h/);
+ expect(formatRelative(now - 40 * 86_400_000, now, "en", "now")).toMatch(/Sep/);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts
new file mode 100644
index 0000000000..f4af7d9abd
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts
@@ -0,0 +1,149 @@
+/**
+ * What one roster row says about its agent, as pure functions.
+ *
+ * A row has one status (the corner mark on the avatar) and one preview line.
+ * Both follow a single vocabulary shared by the row, the hover card and the
+ * chat header:
+ *
+ * status: needs-you > working > unread > paused > idle
+ * preview: waiting reason > unsent draft > last message > role
+ *
+ * "Needs you" beats everything because it is the only state where the agent
+ * cannot move on without the person. A draft beats the last message because
+ * it is the person's own unsent words. Live work shows on the corner mark and
+ * in the chat header, so the preview keeps saying what was last said.
+ */
+import { hideAskBlocks } from "@/components/agentchat/askFence";
+
+import type { SocietyAgent } from "../data";
+
+export type WaitingKind = "question" | "approval" | "credential" | "proposal";
+
+/** Why an agent waits on the person (society agent payload `waiting_reason`). */
+export interface WaitingReason {
+ kind: WaitingKind;
+ summary: string;
+ sessionId?: string;
+ refId?: string;
+}
+
+const WAITING_KINDS: ReadonlySet<string> = new Set(["question", "approval", "credential", "proposal"]);
+
+function coerceReason(value: unknown): WaitingReason | null {
+ if (!value || typeof value !== "object") return null;
+ const raw = value as Record<string, unknown>;
+ const kind = typeof raw.kind === "string" && WAITING_KINDS.has(raw.kind) ? (raw.kind as WaitingKind) : null;
+ if (!kind) return null;
+ const sessionId = raw.sessionId ?? raw.session_id;
+ const refId = raw.refId ?? raw.ref_id;
+ return {
+ kind,
+ summary: typeof raw.summary === "string" ? raw.summary : "",
+ ...(typeof sessionId === "string" ? { sessionId } : {}),
+ ...(typeof refId === "string" ? { refId } : {}),
+ };
+}
+
+/**
+ * The agent's waiting reason when the backend sends one. Older backends do
+ * not; the row then falls back to the plain `waiting` state.
+ */
+export function waitingReasonOf(agent: SocietyAgent): WaitingReason | null {
+ const loose = agent as SocietyAgent & { waitingReason?: unknown; waiting_reason?: unknown };
+ return coerceReason(loose.waitingReason ?? loose.waiting_reason);
+}
+
+export function needsYou(agent: SocietyAgent): boolean {
+ return agent.state === "waiting" || waitingReasonOf(agent) !== null;
+}
+
+export type RosterStatus = "needs-you" | "working" | "unread" | "paused" | "idle";
+
+export function rosterStatus(agent: SocietyAgent, unread: boolean): RosterStatus {
+ if (needsYou(agent)) return "needs-you";
+ if (agent.state === "working") return "working";
+ if (unread) return "unread";
+ if (agent.state === "paused") return "paused";
+ return "idle";
+}
+
+export type PreviewKind = "waiting" | "draft" | "message" | "role";
+
+export interface RosterPreview {
+ kind: PreviewKind;
+ text: string;
+}
+
+export interface PreviewSources {
+ agent: SocietyAgent;
+ /** Unsent composer text for this agent's chat, if any. */
+ draft?: string;
+ /** The last message in the agent's chat (either side), if known. */
+ lastMessage?: string;
+}
+
+/** The hidden routing lines a society message carries (AgentChatPanel strips the same). */
+const MARKER_LINE = /^\s*\[(?:to jarvis\]|agent mentions\]|tools:)[^\n]*$/gm;
+const MAX_PREVIEW = 160;
+
+/** One line of plain text from a chat message: no ask block, markers or markdown. */
+export function previewText(raw: string | null | undefined): string {
+ if (!raw) return "";
+ const text = hideAskBlocks(raw)
+ .replace(/```[\s\S]*?(```|$)/g, " ")
+ .replace(MARKER_LINE, " ")
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
+ .replace(/[*_`>#~|]+/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+ return text.length > MAX_PREVIEW ? `${text.slice(0, MAX_PREVIEW - 1)}…` : text;
+}
+
+/** The single preview line, by the priority in the file comment. */
+export function rosterPreview({ agent, draft, lastMessage }: PreviewSources): RosterPreview {
+ const reason = waitingReasonOf(agent);
+ if (reason || agent.state === "waiting") {
+ return { kind: "waiting", text: previewText(reason?.summary) };
+ }
+ const unsent = previewText(draft);
+ if (unsent) return { kind: "draft", text: unsent };
+ const last = previewText(lastMessage);
+ if (last) return { kind: "message", text: last };
+ return { kind: "role", text: agent.title };
+}
+
+const MINUTE = 60_000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+export type RelativeStamp =
+ | { unit: "now" }
+ | { unit: "minute" | "hour" | "day"; value: number }
+ | { unit: "date"; ms: number };
+
+/** Bucket a timestamp the way a dense list shows it: now, 5m, 3h, 2d, then a date. */
+export function relativeStamp(ms: number, now: number): RelativeStamp {
+ const delta = Math.max(0, now - ms);
+ if (delta < MINUTE) return { unit: "now" };
+ if (delta < HOUR) return { unit: "minute", value: Math.floor(delta / MINUTE) };
+ if (delta < DAY) return { unit: "hour", value: Math.floor(delta / HOUR) };
+ if (delta < 7 * DAY) return { unit: "day", value: Math.floor(delta / DAY) };
+ return { unit: "date", ms };
+}
+
+/** Localised short form of `relativeStamp`; `nowLabel` comes from the locale file. */
+export function formatRelative(ms: number, now: number, locale: string, nowLabel: string): string {
+ const stamp = relativeStamp(ms, now);
+ if (stamp.unit === "now") return nowLabel;
+ try {
+ if (stamp.unit === "date") {
+ const sameYear = new Date(ms).getFullYear() === new Date(now).getFullYear();
+ return new Intl.DateTimeFormat(locale, sameYear ? { month: "short", day: "numeric" } : { year: "2-digit", month: "short" }).format(ms);
+ }
+ return new Intl.NumberFormat(locale, { style: "unit", unit: stamp.unit, unitDisplay: "narrow" }).format(stamp.value);
+ } catch {
+ if (stamp.unit === "date") return new Date(ms).toLocaleDateString();
+ return `${stamp.value}${stamp.unit[0]}`;
+ }
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/useRosterActivity.ts b/dodaios/ui/web/frontend/src/components/society/roster/useRosterActivity.ts
new file mode 100644
index 0000000000..44141f4e14
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/society/roster/useRosterActivity.ts
@@ -0,0 +1,76 @@
+/**
+ * The chat facts a roster row shows besides the agent's state: the last
+ * message, when it was sent, and any unsent draft.
+ *
+ * Nothing new is fetched per agent. Every specialist's chat is one session in
+ * the society chat store, whose session list already carries a preview and
+ * an update time; drafts live in the composer's draft store. The lead's chat
+ * is the front page's chat, so its row reads that store instead.
+ */
+import { useEffect, useMemo, useRef } from "react";
+import { useStore } from "zustand";
+
+import { composerDraftsFor } from "@/components/agentchat/composerDrafts";
+import { useAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";
+
+import type { SocietyAgent } from "../data";
+
+export interface RosterActivity {
+ lastMessage?: string;
+ lastMs?: number | null;
+ draft?: string;
+}
+
+export type RosterActivityMap = ReadonlyMap<string, RosterActivity>;
+
+/** Re-read the session list at most this often while agents finish work. */
+const REFRESH_GAP_MS = 2_500;
+
+export function useRosterActivity(agents: SocietyAgent[], societyStore: AgentChatStoreHook, enabled = true): RosterActivityMap {
+ const sessions = societyStore((state) => state.sessions);
+ const leadSessions = useAgentChatStore((state) => state.sessions);
+ const leadActive = useAgentChatStore((state) => state.activeSessionId);
+ const drafts = useStore(composerDraftsFor(societyStore), (state) => state.drafts);
+ const leadDrafts = useStore(composerDraftsFor(useAgentChatStore), (state) => state.drafts);
+
+ // A finished turn changes the last message: reload the list when an agent
+ // stops working, throttled so a busy team does not hammer the endpoint.
+ const working = agents.filter((agent) => agent.state === "working").map((agent) => agent.agentId).join(",");
+ const lastRefresh = useRef(0);
+ const previousWorking = useRef<string | null>(null);
+ useEffect(() => {
+ if (!enabled) return;
+ const first = previousWorking.current === null;
+ const someoneFinished = !first && previousWorking.current!.split(",").some((id) => id && !working.split(",").includes(id));
+ previousWorking.current = working;
+ if (!first && !someoneFinished) return;
+ const now = Date.now();
+ if (now - lastRefresh.current < REFRESH_GAP_MS) return;
+ lastRefresh.current = now;
+ void societyStore.getState().loadSessions();
+ }, [enabled, working, societyStore]);
+
+ return useMemo(() => {
+ const bySession = new Map(sessions.map((row) => [row.session_id, row]));
+ const out = new Map<string, RosterActivity>();
+ for (const agent of agents) {
+ if (agent.tier === "lead") {
+ const latest = leadSessions.reduce<(typeof leadSessions)[number] | null>(
+ (best, row) => (!best || row.updated_ms > best.updated_ms ? row : best), null);
+ out.set(agent.agentId, {
+ lastMessage: latest?.preview,
+ lastMs: latest?.updated_ms ?? agent.stats?.lastActiveMs,
+ draft: leadDrafts.get(leadActive)?.text,
+ });
+ continue;
+ }
+ const session = agent.chatSessionId ? bySession.get(agent.chatSessionId) : undefined;
+ out.set(agent.agentId, {
+ lastMessage: session?.preview,
+ lastMs: session?.updated_ms ?? agent.stats?.lastActiveMs,
+ draft: agent.chatSessionId ? drafts.get(agent.chatSessionId)?.text : undefined,
+ });
+ }
+ return out;
+ }, [agents, sessions, leadSessions, leadActive, drafts, leadDrafts]);
+}
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/useRosterUnread.ts b/dodaios/ui/web/frontend/src/components/society/roster/useRosterUnread.ts
index 7e3fe94691..0822da968d 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/useRosterUnread.ts
+++ b/dodaios/ui/web/frontend/src/components/society/roster/useRosterUnread.ts
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import type { SocietyAgent } from "../data";
@@ -34,7 +34,27 @@ export function useRosterUnread(
agents: SocietyAgent[],
activeAgentId: string | null,
): Set<string> {
+ return useRosterUnreadState(agents, activeAgentId).unread;
+}
+
+/**
+ * The same tracking plus a manual mark, for the row menu's "Mark as read" /
+ * "Mark as unread". The open agent cannot be marked unread: it is being read.
+ */
+export function useRosterUnreadState(
+ agents: SocietyAgent[],
+ activeAgentId: string | null,
+): { unread: Set<string>; mark: (agentId: string, unread: boolean) => void } {
const [unread, setUnread] = useState<Set<string>>(() => readStored());
+ const mark = useCallback((agentId: string, value: boolean) => {
+ setUnread((prev) => {
+ if (prev.has(agentId) === value) return prev;
+ const copy = new Set(prev);
+ if (value) copy.add(agentId);
+ else copy.delete(agentId);
+ return copy;
+ });
+ }, []);
const prevStates = useRef(new Map<string, string>());
const initialized = useRef(false);
@@ -96,5 +116,5 @@ export function useRosterUnread(
}
}, [unread]);
- return unread;
+ return { unread, mark };
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json b/dodaios/ui/web/frontend/src/i18n/locales/society/de.json
index ddac1fbd22..9e714eaed3 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/de.json
@@ -2131,6 +2131,42 @@
"copy_url": "URL kopieren",
"copy_header": "Header-Zeile kopieren"
}
+ },
+ "shell": {
+ "mode_verse": "Verse",
+ "new_agent": "Neuer Agent",
+ "roster_collapse": "Agentenliste einklappen",
+ "roster_expand": "Agentenliste ausklappen",
+ "resize_roster": "Breite der Agentenliste ändern",
+ "resize_details": "Breite des Detailbereichs ändern",
+ "filter_label": "Agenten anzeigen",
+ "filter_all": "Alle",
+ "filter_needs_you": "Braucht dich",
+ "filter_unread": "Ungelesen",
+ "pinned": "Angeheftete Agenten",
+ "section_needs_you": "Braucht dich",
+ "section_teams": "Teams",
+ "section_agents": "Agenten",
+ "team_empty": "Noch keine Mitglieder. Halte einen Agenten über dieses Team, um ihn hinzuzufügen.",
+ "status_needs_you": "Braucht dich",
+ "status_waiting": "Wartet auf dich",
+ "preview_needs_you": "Braucht dich",
+ "preview_draft": "Entwurf:",
+ "preview_working": "Arbeitet…",
+ "time_now": "jetzt",
+ "pin": "Oben anheften",
+ "unpin": "Lösen",
+ "pin_full": "Es sind schon acht Agenten angeheftet. Löse zuerst einen.",
+ "mark_read": "Als gelesen markieren",
+ "mark_unread": "Als ungelesen markieren",
+ "reorder_keys": "Alt + Umschalt + Pfeil hoch / runter verschiebt den Agenten",
+ "empty_agents": "Noch keine Agenten. Gib deinem ersten Agenten eine Aufgabe, dann erscheint er hier.",
+ "empty_needs_you": "Gerade braucht dich niemand. Fragen und Freigaben erscheinen hier.",
+ "empty_unread": "Du bist auf dem neuesten Stand. Neue Ergebnisse deiner Agenten erscheinen hier.",
+ "show_all": "Alle Agenten zeigen",
+ "clear_search": "Suche leeren",
+ "approval_legacy": "Bisherige Berechtigungen",
+ "approval_confirm": "Erneut klicken, um mehr ohne Nachfrage zu erlauben"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json b/dodaios/ui/web/frontend/src/i18n/locales/society/en.json
index b416b88bb0..964f38c245 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/en.json
@@ -2131,6 +2131,42 @@
"copy_url": "Copy URL",
"copy_header": "Copy header line"
}
+ },
+ "shell": {
+ "mode_verse": "Verse",
+ "new_agent": "New agent",
+ "roster_collapse": "Fold the agent list",
+ "roster_expand": "Unfold the agent list",
+ "resize_roster": "Resize the agent list",
+ "resize_details": "Resize the details pane",
+ "filter_label": "Show agents",
+ "filter_all": "All",
+ "filter_needs_you": "Needs you",
+ "filter_unread": "Unread",
+ "pinned": "Pinned agents",
+ "section_needs_you": "Needs you",
+ "section_teams": "Teams",
+ "section_agents": "Agents",
+ "team_empty": "No members yet. Hold an agent over this team to add it.",
+ "status_needs_you": "Needs you",
+ "status_waiting": "Waiting for you",
+ "preview_needs_you": "Needs you",
+ "preview_draft": "Draft:",
+ "preview_working": "Working…",
+ "time_now": "now",
+ "pin": "Pin to the top",
+ "unpin": "Unpin",
+ "pin_full": "Eight agents are pinned already. Unpin one first.",
+ "mark_read": "Mark as read",
+ "mark_unread": "Mark as unread",
+ "reorder_keys": "Alt + Shift + Arrow Up / Down moves the agent",
+ "empty_agents": "No agents yet. Give your first agent a job and it shows up here.",
+ "empty_needs_you": "Nothing needs you right now. Questions and approvals show up here.",
+ "empty_unread": "You are all caught up. New results from your agents show up here.",
+ "show_all": "Show all agents",
+ "clear_search": "Clear search",
+ "approval_legacy": "Existing permissions",
+ "approval_confirm": "Click again to allow more without asking"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json b/dodaios/ui/web/frontend/src/i18n/locales/society/es.json
index 21f33c6424..8cf0d6a230 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/es.json
@@ -2131,6 +2131,42 @@
"copy_url": "Copiar URL",
"copy_header": "Copiar línea de cabecera"
}
+ },
+ "shell": {
+ "mode_verse": "Verse",
+ "new_agent": "Nuevo agente",
+ "roster_collapse": "Plegar la lista de agentes",
+ "roster_expand": "Desplegar la lista de agentes",
+ "resize_roster": "Cambiar el ancho de la lista de agentes",
+ "resize_details": "Cambiar el ancho del panel de detalles",
+ "filter_label": "Mostrar agentes",
+ "filter_all": "Todos",
+ "filter_needs_you": "Te necesita",
+ "filter_unread": "Sin leer",
+ "pinned": "Agentes fijados",
+ "section_needs_you": "Te necesita",
+ "section_teams": "Equipos",
+ "section_agents": "Agentes",
+ "team_empty": "Aún no hay miembros. Mantén un agente sobre este equipo para añadirlo.",
+ "status_needs_you": "Te necesita",
+ "status_waiting": "Esperándote",
+ "preview_needs_you": "Te necesita",
+ "preview_draft": "Borrador:",
+ "preview_working": "Trabajando…",
+ "time_now": "ahora",
+ "pin": "Fijar arriba",
+ "unpin": "Desfijar",
+ "pin_full": "Ya hay ocho agentes fijados. Desfija uno primero.",
+ "mark_read": "Marcar como leído",
+ "mark_unread": "Marcar como no leído",
+ "reorder_keys": "Alt + Mayús + flecha arriba / abajo mueve el agente",
+ "empty_agents": "Aún no hay agentes. Dale una tarea a tu primer agente y aparecerá aquí.",
+ "empty_needs_you": "Ahora mismo nada te necesita. Las preguntas y aprobaciones aparecen aquí.",
+ "empty_unread": "Estás al día. Los nuevos resultados de tus agentes aparecen aquí.",
+ "show_all": "Mostrar todos los agentes",
+ "clear_search": "Borrar búsqueda",
+ "approval_legacy": "Permisos actuales",
+ "approval_confirm": "Vuelve a hacer clic para permitir más sin preguntar"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json
index e5383fa4c0..2df0c5471e 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json
@@ -2131,6 +2131,42 @@
"copy_url": "Copiar URL",
"copy_header": "Copiar linha de cabeçalho"
}
+ },
+ "shell": {
+ "mode_verse": "Verse",
+ "new_agent": "Novo agente",
+ "roster_collapse": "Recolher a lista de agentes",
+ "roster_expand": "Expandir a lista de agentes",
+ "resize_roster": "Ajustar a largura da lista de agentes",
+ "resize_details": "Ajustar a largura do painel de detalhes",
+ "filter_label": "Mostrar agentes",
+ "filter_all": "Todos",
+ "filter_needs_you": "Precisa de você",
+ "filter_unread": "Não lidos",
+ "pinned": "Agentes fixados",
+ "section_needs_you": "Precisa de você",
+ "section_teams": "Equipes",
+ "section_agents": "Agentes",
+ "team_empty": "Ainda sem membros. Segure um agente sobre esta equipe para adicioná-lo.",
+ "status_needs_you": "Precisa de você",
+ "status_waiting": "Esperando por você",
+ "preview_needs_you": "Precisa de você",
+ "preview_draft": "Rascunho:",
+ "preview_working": "Trabalhando…",
+ "time_now": "agora",
+ "pin": "Fixar no topo",
+ "unpin": "Desafixar",
+ "pin_full": "Já há oito agentes fixados. Desafixe um primeiro.",
+ "mark_read": "Marcar como lido",
+ "mark_unread": "Marcar como não lido",
+ "reorder_keys": "Alt + Shift + seta para cima / baixo move o agente",
+ "empty_agents": "Ainda não há agentes. Dê uma tarefa ao seu primeiro agente e ele aparecerá aqui.",
+ "empty_needs_you": "Nada precisa de você agora. Perguntas e aprovações aparecem aqui.",
+ "empty_unread": "Você está em dia. Novos resultados dos seus agentes aparecem aqui.",
+ "show_all": "Mostrar todos os agentes",
+ "clear_search": "Limpar busca",
+ "approval_legacy": "Permissões atuais",
+ "approval_confirm": "Clique de novo para permitir mais sem perguntar"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json
index dfe5cd2881..84d9fed87c 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json
@@ -2131,6 +2131,42 @@
"copy_url": "复制 URL",
"copy_header": "复制请求头"
}
+ },
+ "shell": {
+ "mode_verse": "Verse",
+ "new_agent": "新建智能体",
+ "roster_collapse": "收起智能体列表",
+ "roster_expand": "展开智能体列表",
+ "resize_roster": "调整智能体列表宽度",
+ "resize_details": "调整详情面板宽度",
+ "filter_label": "显示智能体",
+ "filter_all": "全部",
+ "filter_needs_you": "需要你",
+ "filter_unread": "未读",
+ "pinned": "已置顶的智能体",
+ "section_needs_you": "需要你",
+ "section_teams": "团队",
+ "section_agents": "智能体",
+ "team_empty": "还没有成员。把智能体拖到这个团队上停留片刻即可加入。",
+ "status_needs_you": "需要你",
+ "status_waiting": "正在等你",
+ "preview_needs_you": "需要你",
+ "preview_draft": "草稿:",
+ "preview_working": "工作中…",
+ "time_now": "刚刚",
+ "pin": "置顶",
+ "unpin": "取消置顶",
+ "pin_full": "已置顶八个智能体,请先取消一个。",
+ "mark_read": "标为已读",
+ "mark_unread": "标为未读",
+ "reorder_keys": "Alt + Shift + 上/下方向键移动智能体",
+ "empty_agents": "还没有智能体。给你的第一个智能体分配一项工作,它就会出现在这里。",
+ "empty_needs_you": "目前没有需要你处理的事。问题和审批会显示在这里。",
+ "empty_unread": "你已全部看完。智能体的新结果会显示在这里。",
+ "show_all": "显示全部智能体",
+ "clear_search": "清除搜索",
+ "approval_legacy": "现有权限",
+ "approval_confirm": "再次点击以允许更多操作而无需询问"
}
}
}
diff --git a/dodaios/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx b/dodaios/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx
index d05fbcb55c..6c55cb0ece 100644
--- a/dodaios/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx
+++ b/dodaios/ui/web/frontend/src/views/society/SocietyView.deferred.test.tsx
@@ -15,6 +15,7 @@ vi.mock("@/components/society/data", () => ({ useQuickCreateAgent: () => quick.c
useSocietyRoster: () => ({ data: { sample: false,
agents: [{ agentId: "lead", name: "Lead", tier: "lead", state: "idle" }] }, isLoading: false }) }));
vi.mock("@/components/society/roster/RosterRail", () => ({ RosterRail: () => null }));
+vi.mock("@/components/society/roster/useRosterActivity", () => ({ useRosterActivity: () => new Map() }));
vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ onCreate }: { onCreate: () => void }) => (
<><input aria-label="Existing chat draft" /><button onClick={onCreate}>Create agent</button></>
) }));
@@ -47,7 +48,7 @@ it("never evaluates closed dialog modules; creates agents without a dialog", asy
expect(screen.getByLabelText("Existing chat draft")).toBe(draft);
expect((draft as HTMLInputElement).value).toBe("Keep this draft");
- const worldTab = screen.getByRole("tab", { name: "society.world.mode_map" });
+ const worldTab = screen.getByRole("tab", { name: "society.shell.mode_verse" });
fireEvent.pointerEnter(worldTab);
await waitFor(() => expect(loaded.world).toBe(1));
expect(screen.queryByTestId("society-world-surface")).toBeNull();
diff --git a/dodaios/ui/web/frontend/src/views/society/SocietyView.test.tsx b/dodaios/ui/web/frontend/src/views/society/SocietyView.test.tsx
index ae46f2e3b1..94e3882394 100644
--- a/dodaios/ui/web/frontend/src/views/society/SocietyView.test.tsx
+++ b/dodaios/ui/web/frontend/src/views/society/SocietyView.test.tsx
@@ -68,7 +68,7 @@ it("switches to Map and back without losing the selected agent or draft", async
fireEvent.click(screen.getByText("Select specialist"));
const draft = screen.getByLabelText("Draft") as HTMLInputElement;
fireEvent.change(draft, { target: { value: "Unsent message" } });
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
const map = await screen.findByTestId("map");
expect(map.dataset.active).toBe("true");
fireEvent.click(screen.getByRole("tab", { name: "society.roster.title" }));
@@ -78,7 +78,7 @@ it("switches to Map and back without losing the selected agent or draft", async
expect(draft.value).toBe("Unsent message");
expect(screen.getByTestId("map")).toBe(map);
expect(map.dataset.active).toBe("false");
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
expect(screen.getByTestId("map")).toBe(map);
expect(map.dataset.active).toBe("true");
expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("false");
@@ -97,7 +97,7 @@ it("restores the most recently selected agent after the view is remounted", () =
it("opens map selections in Agents and keeps creation available", async () => {
render(<SocietyView />);
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
fireEvent.click(await screen.findByText("Map specialist"));
expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
expect(screen.getByText("Specialist")).toBeTruthy();
@@ -128,8 +128,8 @@ it("keeps the Map/Agents switch in the caption in both modes", async () => {
// straight under the caption, the switch rides centered in it.
expect(screen.queryByRole("button", { name: "settings_hub.back_to_app" })).toBeNull();
const captionSwitch = screen.getByTestId("mode-switch");
- expect(within(captionSwitch).getByRole("tab", { name: "society.world.mode_map" })).toBeTruthy();
- fireEvent.click(within(captionSwitch).getByRole("tab", { name: "society.world.mode_map" }));
+ expect(within(captionSwitch).getByRole("tab", { name: "society.shell.mode_verse" })).toBeTruthy();
+ fireEvent.click(within(captionSwitch).getByRole("tab", { name: "society.shell.mode_verse" }));
await screen.findByTestId("map");
// Map mode takes the native window fullscreen: the switch stays in the
// caption instead of shrinking into the map HUD, so Agents stays reachable.
@@ -151,7 +151,7 @@ it("navigates back through the window caption instead of a sections toggle", ()
it("leaves Map on Escape without requesting native fullscreen in a browser", async () => {
render(<SocietyView />);
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
await screen.findByTestId("map");
expect(setMapFullscreen).not.toHaveBeenCalledWith(true);
fireEvent.keyDown(document, { key: "Escape" });
@@ -166,7 +166,7 @@ it("shows no station shortcut in Agents mode", () => {
it("does not discard a Mars form when Escape belongs to its input", async () => {
render(<SocietyView />);
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
const field = await screen.findByLabelText("Mars draft");
fireEvent.change(field, { target: { value: "Unsent station draft" } });
fireEvent.keyDown(field, { key: "Escape" });
@@ -178,7 +178,7 @@ it("does not discard a Mars form when Escape belongs to its input", async () =>
it.each(["Mars draft", "Player viewport", "Follow viewport"])("preserves focused %s when the browser exits fullscreen without a keydown", async (target) => {
render(<SocietyView />);
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
const field = await screen.findByLabelText("Mars draft");
fireEvent.change(field, { target: { value: "Unsent station draft" } });
const focused = target === "Mars draft" ? field : screen.getByText(target);
@@ -194,7 +194,7 @@ it.each(["Mars draft", "Player viewport", "Follow viewport"])("preserves focused
it("still leaves the ordinary map when browser fullscreen exits", async () => {
render(<SocietyView />);
- fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));
+ fireEvent.click(screen.getByRole("tab", { name: "society.shell.mode_verse" }));
await screen.findByTestId("map");
fireEvent(document, new Event("fullscreenchange"));
expect(screen.getByTestId("society-world-surface").getAttribute("aria-hidden")).toBe("true");
diff --git a/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx b/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx
index 260fa11829..8ffb22407b 100644
--- a/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx
+++ b/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx
@@ -1,16 +1,13 @@
import { lazy, Suspense, useCallback, useMemo, useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useQueryClient } from "@tanstack/react-query";
-import { Building2, Users } from "lucide-react";
+import { Orbit, Users } from "lucide-react";
import { setMapFullscreen } from "@/lib/mapFullscreen";
import { inDesktopShell } from "@/lib/nativeDrop";
import { useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
-import {
- CAPTION_ICON_CLASS, CAPTION_ICON_STROKE, CAPTION_SEGMENT, CAPTION_SEGMENT_OFF, CAPTION_SEGMENT_ON,
- CAPTION_SEGMENT_PX, CAPTION_THUMB, CAPTION_TRACK,
-} from "@/components/layout/captionSwitch";
+import { CAPTION_ICON_STROKE, CAPTION_SEGMENT_OFF, CAPTION_SEGMENT_ON, CAPTION_TRACK } from "@/components/layout/captionSwitch";
import { AgentCardOverlay } from "@/components/society/card/AgentCardOverlay";
import { BrowserProfilesButton } from "@/components/society/browser/BrowserProfilesButton";
import { BUILDING_CARDS, isBuildingPlace, type BuildingPlace } from "@/components/society/card/buildingCards";
@@ -19,6 +16,7 @@ import type { PlaceId } from "@/components/society/world/islandLayout";
import { useQuickCreateAgent, useSocietyRoster } from "@/components/society/data";
import { isCreateCancelled } from "@/components/society/create/createAgentStore";
import { RosterRail } from "@/components/society/roster/RosterRail";
+import { useRosterActivity } from "@/components/society/roster/useRosterActivity";
import { useModelMenuData } from "@/components/society/chat/useModelMenuData";
import { ChatGroupPanel } from "@/components/society/chat/ChatGroupPanel";
import { useSocietyChatStore } from "@/components/society/chat/AgentChatPanel";
@@ -26,15 +24,23 @@ import { chatGroupsKnown, createSocietyChatGroup, updateSocietyChatGroup, useSoc
import { CanvasActivity } from "@/hooks/useCanvasAwake";
import { forgetLastAgentId, rememberLastAgentId, storedLastAgentId } from "./lastAgent";
-/** The page's two faces, in caption order: the Verse map, then the agent roster. */
+/** The page's two faces, in caption order: the agents, then the Verse. */
const MODES = [
- { value: "world", labelKey: "society.world.mode_map", Icon: Building2 },
- { value: "agents", labelKey: "society.roster.title", Icon: Users },
+ { value: "agents", labelKey: "society.roster.title", titleKey: "society.roster.title", Icon: Users },
+ { value: "world", labelKey: "society.shell.mode_verse", titleKey: "society.world.mode_map", Icon: Orbit },
] as const;
// Small and three.js-free: the fallback in front of the lazy Verse chunk.
import { VerseLoadingScreen, preloadLoadingArt } from "@/components/society/verse/VerseLoadingScreen";
+/** A labelled segment on the caption track: icon plus word, the "on" one lifted. */
+const MODE_SEGMENT =
+ "relative z-[1] flex h-full items-center gap-1.5 rounded-full border px-3 text-xs font-medium " +
+ "transition-[background-color,color,border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none " +
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
+const MODE_SEGMENT_ON =
+ "border-border-strong/60 bg-background shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.25)] dark:border-border-strong dark:bg-surface-raised";
+
const loadWorld = () => import("@/views/DodaiosAgentsView").then((m) => ({ default: m.DodaiosAgentsView }));
const JarvisAgentsBoard = lazy(loadWorld);
const preloadWorld = () => { preloadLoadingArt(); void loadWorld().catch((error) => console.debug("World preload unavailable", error)); };
@@ -74,6 +80,8 @@ export function SocietyView() {
() => agents.find((a) => a.agentId === openAgentId) ?? agents.find((a) => a.tier === "lead") ?? agents[0] ?? null,
[agents, openAgentId],
);
+ // The workspace reads its own; only the bare roster (nobody open) needs this.
+ const standaloneActivity = useRosterActivity(agents, useSocietyChatStore, !openAgent && !openGroupId);
const selectAgent = useCallback((agentId: string | null) => {
setOpenGroupId(null);
@@ -184,23 +192,20 @@ export function SocietyView() {
if (isBuildingPlace(place)) setOpenPlace(place);
}, []);
- // Icon-only, in the same caption look as the Agentic IDE's switch; the
- // names live on as the accessible label and the hover title.
- const modeIndex = MODES.findIndex((item) => item.value === mode);
+ // Labelled, in the caption look the Agentic IDE's switch uses: a word
+ // names each face, so the switch reads without hovering.
const modeSwitch = (
<div role="tablist" aria-label={t("society.world.mode_label")} className={CAPTION_TRACK}>
- <span aria-hidden className={CAPTION_THUMB}
- style={{ width: CAPTION_SEGMENT_PX, transform: `translateX(${Math.max(0, modeIndex) * CAPTION_SEGMENT_PX}px)` }} />
- {MODES.map(({ value, labelKey, Icon }) => {
- const label = t(labelKey);
- return <button key={value} type="button" role="tab" aria-selected={mode === value}
- aria-label={label} title={label} data-testid={`society-mode-${value}`}
+ {MODES.map(({ value, labelKey, titleKey, Icon }) => {
+ const on = mode === value;
+ return <button key={value} type="button" role="tab" aria-selected={on}
+ title={t(titleKey)} data-testid={`society-mode-${value}`}
onClick={() => switchMode(value)}
onPointerEnter={value === "world" ? preloadWorld : undefined}
onFocus={value === "world" ? preloadWorld : undefined}
- style={{ width: CAPTION_SEGMENT_PX }}
- className={cn(CAPTION_SEGMENT, mode === value ? CAPTION_SEGMENT_ON : CAPTION_SEGMENT_OFF)}>
- <Icon aria-hidden className={CAPTION_ICON_CLASS} strokeWidth={CAPTION_ICON_STROKE} />
+ className={cn(MODE_SEGMENT, on ? cn(CAPTION_SEGMENT_ON, MODE_SEGMENT_ON) : cn(CAPTION_SEGMENT_OFF, "border-transparent"))}>
+ <Icon aria-hidden className="h-3.5 w-3.5" strokeWidth={CAPTION_ICON_STROKE} />
+ <span>{t(labelKey)}</span>
</button>;
})}
</div>
@@ -242,7 +247,7 @@ export function SocietyView() {
onCreateAgent={createAgent} onDeleted={() => setOpenGroupId(null)}
onGroupAgents={groupAgents} onAddAgentToGroup={addAgentToGroup} />
) : openAgent ? (
- <AgentCardOverlay embedded agent={openAgent} roster={agents} rosterLoading={roster.isLoading} teamsPending={teamsPending}
+ <AgentCardOverlay embedded active={mode === "agents"} agent={openAgent} roster={agents} rosterLoading={roster.isLoading} teamsPending={teamsPending}
groups={groups} onSelectGroup={selectGroup}
onGroupAgents={sample ? undefined : groupAgents} onAddAgentToGroup={sample ? undefined : addAgentToGroup}
sample={sample} onSelectAgent={selectAgent} onCreate={createAgent}
@@ -252,7 +257,8 @@ export function SocietyView() {
groups={groups} onOpenGroup={selectGroup}
onGroupAgents={sample ? undefined : groupAgents} onAddAgentToGroup={sample ? undefined : addAgentToGroup}
activeAgentId={null} onOpen={selectAgent} onCreate={createAgent} side="left"
- className="w-full border-0 jarvis-nav-surface" />
+ activity={standaloneActivity} keyboard={mode === "agents"}
+ className="w-full border-0" />
)}
</div>
</div>