๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
๐ fix(agent-group): render server-runtime group broadcast as a streaming AgentCouncil (#16363)
Arvin Xu98707b6f5dee
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.mdindex 4d5c29a57bb..d97a7c79efd 100644--- a/.agents/skills/agent-testing/SKILL.md+++ b/.agents/skills/agent-testing/SKILL.md@@ -240,6 +240,16 @@ do not open a login page; verify agent-browser first, then request the NetworkEscalate, don't duplicate: verify a backend change with the CLI first; only adda UI pass when the change actually affects the UI.+**Verify the change runs where you think it does โ confirm runtime, don't assume.**+Some features have two execution paths and the UI silently picks one (e.g. group+orchestration: the chat UI defaults to the **client** runtime, while the fix may+live in the **server** runtime / `AGENT_RUNTIME_MODE=queue` durable-op path). A+test that exercises the wrong path can pass green without ever touching the code+under test. Before trusting a result, **prove which runtime ran** โ e.g. check for+a server `agent_operations` row, the QStash `/api/agent/run` steps, or server-only+log lines. If the UI won't take the server path, drive it directly (call the+server TRPC mutation / endpoint) so the server runtime actually executes.+### Environment support (local macOS vs cloud Linux)The decisive constraint per surface is **how evidence (screenshots) is@@ -291,7 +301,7 @@ Surface guides above carry the detailed workflows. Shared infrastructure:| Start / restart the local dev server | [references/dev-server.md](./references/dev-server.md) || `agent-browser` command reference | [references/agent-browser.md](./references/agent-browser.md) || osascript patterns (general macOS) | [references/osascript.md](./references/osascript.md) |-| Agent gateway probing | [references/agent-gateway.md](./references/agent-gateway.md) |+| Local gateway closed loop + probing | [references/agent-gateway.md](./references/agent-gateway.md) || Screen recording | [references/record-app-screen.md](./references/record-app-screen.md) |### Scripts@@ -348,10 +358,12 @@ Two hard rules worth front-loading:from `summary.conclusion`. So do NOT hand-build a ็จไพ table or a ่ๅด block in`report.md` โ they double up on the page. `report.md` is the narrative tailonly (่ท่ฟ / ๆฌ่ฝฎ้ช่ฏ / ่ฏๅ).-- **Visual evidence must render inline.** Screenshots and GIFs in `report.md`- must use Markdown image syntax like ``. Do not- use bare file paths, Markdown links, or local file links as the primary- visual evidence; those make the report unreadable without opening each asset.+- **Visual evidence lives in `result.json`, NOT in `report.md`.** Attach each+ screenshot/GIF to the relevant case via `cases[].evidence` (path or array of+ paths under `$DIR`); the verify page renders it next to that check. Do NOT+ embed images/GIFs in `report.md` (no ``) โ they would just+ double up with the per-case evidence the page already shows. `report.md` stays+ prose-only (่ท่ฟ / ๅคๆณจ / ๅค็ฐ).- **Final replies must include visual evidence links.** When a run includes UIscreenshots or GIFs, include the report directory and the most importantvisual artifacts in the final chat response. Each item must include a stable@@ -361,8 +373,8 @@ Two hard rules worth front-loading:Use repo-relative paths, not absolute paths.- **Time-based behavior needs a GIF, not a screenshot.** If a case assertschange over time (streaming output, a ticking timer, loading states,- animations), record it with `scripts/record-gif.sh` and embed the GIF โ- a static screenshot cannot prove the behavior.+ animations), record it with `scripts/record-gif.sh` and attach the GIF as that+ case's `evidence` โ a static screenshot cannot prove the behavior.## Step 4 โ Publish to LobeHub (mandatory)diff --git a/.agents/skills/agent-testing/references/agent-gateway.md b/.agents/skills/agent-testing/references/agent-gateway.mdindex 3e5fbf7b3b3..90525880b3a 100644--- a/.agents/skills/agent-testing/references/agent-gateway.md+++ b/.agents/skills/agent-testing/references/agent-gateway.md@@ -4,16 +4,77 @@ Captures store + DOM state at 200ms intervals so we can prove or disproveclaims like "ๅๅ tab ๅๆถๆฏๅๅฐไบๅพๆฉไปฅๅ". Built for gateway-mode chat butworks for any LobeHub streaming session.+## Running a LOCAL gateway for a real closed loop++> Use this when you need to verify the **browserโgateway** path end-to-end+> (gateway mode / Cloud Sandbox / group broadcast over WebSocket). The probe+> harness below assumes a gateway is already streaming to your browser โ this+> section is how you get one locally.++**Why the online gateway can't close the loop locally.** The online gateway+(`agent-gateway.lobehub.com`) verifies the browser's user JWT against the+**production** app's JWKS. A local dev instance signs that JWT with its **own**+`JWKS_KEY`, so the online gateway rejects the WS handshake with+`{"type":"auth_failed","reason":"signature verification failed"}` โ close+`1008`. The serverโgateway **push** still returns `200` (it uses the static+`AGENT_GATEWAY_SERVICE_TOKEN`, not JWKS) โ so events flow server-side but the+browser never receives them. That's why client / SSE / online-gateway are all+**not** a real local closed loop. Confirm the failure shape by hooking+`WebSocket` in the page and reading the first frame after the `auth` send.++**Fix โ run the gateway yourself.** The gateway worker lives in a **sibling+repo: look for `agent-gateway/` next to `lobehub/`** (same parent dir). It's a+Cloudflare Worker (`wrangler dev`, Durable Objects in local mode) whose+`verifyToken` checks JWTs against a configurable `JWKS_PUBLIC_KEY` secret. Point+that secret at **your local app's** public key and the local gateway trusts your+local JWT โ `auth_success` โ full local loop.++```bash+# 1. Generate agent-gateway/.dev.vars (public JWK extracted from JWKS_KEY ++# reuse of AGENT_GATEWAY_SERVICE_TOKEN). Source resolves to+# .records/env/gateway.env by default, else .env.local; override with+# JWKS_SOURCE=<env file>. (Managed agent-testing runs have NO .env.local.)+.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh++# 2. Start the worker (separate terminal) โ http://localhost:8787+cd ../agent-gateway && bun run dev+curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/health # โ 200++# 3. Decisive check โ does the local gateway accept the app's JWT?+node .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs+# โ RECV: {"type":"auth_success"} โ feasible++# 4. Point the APP at the local gateway and RESTART its dev server:+# AGENT_GATEWAY_URL=http://localhost:8787 (client โ ws://localhost:8787/ws)+# AGENT_GATEWAY_SERVICE_TOKEN=<unchanged> (matches gateway .dev.vars SERVICE_TOKEN)+# ENABLE_AGENT_GATEWAY=1 (โ serverConfig.enableGatewayMode)+```++Key facts the setup relies on: `JWKS_PUBLIC_KEY` is just `JWKS_KEY` with the+private fields (`d,p,q,dp,dq,qi`) stripped โ same `kid`, so signatures verify.+The app's gateway URL flows `AGENT_GATEWAY_URL` โ+`getServerGlobalConfig` โ `serverConfig.agentGatewayUrl`, and the client builds+the WS URL by swapping `http(s)โws(s)` and appending `/ws?operationId=โฆ`, so an+`http://localhost:8787` value Just Works. Server-side, the+`GatewayStreamNotifier` is wrapped whenever `AGENT_GATEWAY_URL &&+AGENT_GATEWAY_SERVICE_TOKEN` are set (`AgentRuntime/factory.ts`), and it+registers each op with the gateway via `POST /api/operations/init` carrying only+`{operationId, userId}` โ it does **not** upload a per-op public key, which is+exactly why the gateway must already trust the signing key via+`JWKS_PUBLIC_KEY`.+## Files`scripts/agent-gateway/`-| File | Role |-| --------------- | ---------------------------------------------------------------- |-| `probe.js` | Injects a 200ms sampler + `__PROBE_EVENT` marker + `__switchTab` |-| `probe-dump.js` | Stops the sampler and returns `{events, samples}` as JSON string |-| `tab-switch.js` | Runs N round-trip switches between two tabs, marks each step |-| `analyze.mjs` | Node post-processor: timeline + regression detection |+| File | Role |+| ------------------------- | ---------------------------------------------------------------- |+| `local-gateway-setup.sh` | Writes `agent-gateway/.dev.vars` from the app's `.env.local` |+| `local-gateway-probe.mjs` | Signs an app JWT, asserts the local gateway returns auth_success |+| `probe.js` | Injects a 200ms sampler + `__PROBE_EVENT` marker + `__switchTab` |+| `probe-dump.js` | Stops the sampler and returns `{events, samples}` as JSON string |+| `tab-switch.js` | Runs N round-trip switches between two tabs, marks each step |+| `analyze.mjs` | Node post-processor: timeline + regression detection |## Standard workflowdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs b/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjsnew file mode 100644index 00000000000..a41f0e64197--- /dev/null+++ b/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs@@ -0,0 +1,80 @@+#!/usr/bin/env node+// local-gateway-probe.mjs โ prove a LOCAL gateway accepts the app's JWT.+//+// Signs a user JWT with the app's local JWKS_KEY (the same key the browser+// uses) and opens the gateway WS auth handshake. Decisive feasibility check+// for the local closed loop: expect {"type":"auth_success"}. Against the+// ONLINE gateway the same JWT yields {"type":"auth_failed","reason":+// "signature verification failed"} โ that contrast is the whole point.+//+// JWKS_KEY source resolution (do NOT assume `.env.local` exists โ the managed+// agent-testing flow has no `.env.local`; the key lives in the dev env / a+// `.records/env/*.env` file). Order:+// 1. process.env.JWKS_KEY (export it before running)+// 2. JWKS_SOURCE=<file> (any env file with a JWKS_KEY= line)+// 3. .records/env/gateway.env (managed flow default)+//+// Run from the lobehub repo root (needs `jose` from its node_modules):+// JWKS_KEY="$JWKS_KEY" node .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs+// JWKS_SOURCE=.env.local node .../local-gateway-probe.mjs # explicit file+// GATEWAY_WS=ws://localhost:8787 node .../local-gateway-probe.mjs # override ws++import { existsSync, readFileSync } from 'node:fs';++import { importJWK, SignJWT } from 'jose';++const WS_BASE = process.env.GATEWAY_WS || 'ws://localhost:8787';++const fromFile = (p) => {+ if (!p || !existsSync(p)) return '';+ const m = readFileSync(p, 'utf8').match(/^JWKS_KEY=(.*)$/m);+ return m ? m[1].trim().replaceAll(/^['"]|['"]$/g, '') : '';+};+const jwksRaw =+ process.env.JWKS_KEY?.trim() ||+ fromFile(process.env.JWKS_SOURCE) ||+ fromFile(new URL('../../../../../.records/env/gateway.env', import.meta.url).pathname);+if (!jwksRaw) {+ console.error(+ 'โ no JWKS_KEY found โ export JWKS_KEY, or set JWKS_SOURCE=<env file>, or create .records/env/gateway.env',+ );+ process.exit(1);+}+const rsa = JSON.parse(jwksRaw).keys.find((k) => k.alg === 'RS256' && k.kty === 'RSA');+const key = await importJWK(rsa, 'RS256');++const token = await new SignJWT({ purpose: 'cli-sandbox' })+ .setProtectedHeader({ alg: 'RS256', kid: rsa.kid })+ .setSubject('user_local_probe')+ .setIssuedAt()+ .setExpirationTime('5m')+ .sign(key);+console.log('signed JWT kid=', rsa.kid, 'len=', token.length);++const ws = new WebSocket(`${WS_BASE}/ws?operationId=op_local_probe_001`);+const exit = (msg, code = 0) => {+ console.log(msg);+ try {+ ws.close();+ } catch {}+ setTimeout(() => process.exit(code), 100);+};+ws.onopen = () => {+ console.log('WS open โ', WS_BASE, 'โ sending auth');+ ws.send(JSON.stringify({ type: 'auth', token }));+};+ws.onmessage = (e) => {+ console.log('RECV:', e.data);+ if (/auth_success/.test(e.data))+ exit('โ local gateway accepts the app JWT โ closed loop is feasible');+ else if (/auth_failed/.test(e.data))+ exit('โ auth_failed โ JWKS_PUBLIC_KEY does not match the app JWKS_KEY', 1);+};+ws.onerror = (e) =>+ exit(+ 'โ WS error: ' ++ (e.message || e.type) ++ ' (is the gateway running? `bun run dev` in agent-gateway/)',+ 1,+ );+setTimeout(() => exit('โ timeout (no auth reply)', 1), 8000);diff --git a/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh b/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.shnew file mode 100755index 00000000000..587b6e5d938--- /dev/null+++ b/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh@@ -0,0 +1,78 @@+#!/usr/bin/env bash+# local-gateway-setup.sh โ wire up a LOCAL Agent Gateway for closed-loop E2E.+#+# Why: the ONLINE gateway (agent-gateway.lobehub.com) verifies the browser's+# user JWT against the PRODUCTION app's JWKS. A local dev instance signs that+# JWT with its OWN `JWKS_KEY`, so the online gateway rejects it with+# `auth_failed: signature verification failed`. The serverโgateway push still+# works (it uses the static AGENT_GATEWAY_SERVICE_TOKEN), but the browser can+# never receive events โ so client/SSE/online-gateway are all "not the real+# closed loop" for local dev.+#+# Fix: run the gateway worker yourself from the SIBLING `agent-gateway/` repo+# via `wrangler dev`, and point its `JWKS_PUBLIC_KEY` at YOUR local app's+# public key. Then the local gateway trusts your local JWT โ `auth_success` โ+# full browserโgateway loop, all local.+#+# This script extracts the public JWK from the app's `.env.local` JWKS_KEY,+# reuses the app's AGENT_GATEWAY_SERVICE_TOKEN, and writes `agent-gateway/.dev.vars`.+# It then prints the app-side env you must set + how to start the worker.+#+# Usage (from the lobehub repo root):+# .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh++set -euo pipefail++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../.." && pwd)"+GATEWAY_DIR="$(cd "$REPO_ROOT/.." && pwd)/agent-gateway"+PORT="${GATEWAY_PORT:-8787}"++# JWKS_KEY + AGENT_GATEWAY_SERVICE_TOKEN source (do NOT assume .env.local โ+# the managed agent-testing flow has no .env.local; the values live in+# .records/env/gateway.env). Override with JWKS_SOURCE=<env file>.+APP_ENV="${JWKS_SOURCE:-}"+if [ -z "$APP_ENV" ]; then+ for cand in "$REPO_ROOT/.records/env/gateway.env" "$REPO_ROOT/.env.local"; do+ [ -f "$cand" ] && { APP_ENV="$cand"; break; }+ done+fi++[ -d "$GATEWAY_DIR" ] || { echo "โ sibling agent-gateway repo not found at: $GATEWAY_DIR"; echo " clone it next to lobehub (same parent dir)."; exit 1; }+[ -n "$APP_ENV" ] && [ -f "$APP_ENV" ] || { echo "โ no env file with JWKS_KEY found (set JWKS_SOURCE=<file>, or create .records/env/gateway.env)"; exit 1; }+echo "โน๏ธ reading JWKS_KEY + AGENT_GATEWAY_SERVICE_TOKEN from: $APP_ENV"++node -e '+const fs = require("fs");+const env = fs.readFileSync(process.argv[1], "utf8");+const pick = (k) => { const m = env.match(new RegExp("^"+k+"=(.*)$","m")); return m ? m[1].trim().replace(/^['"'"'"]|['"'"'"]$/g,"") : ""; };+const jwksRaw = pick("JWKS_KEY");+const svc = pick("AGENT_GATEWAY_SERVICE_TOKEN");+if (!jwksRaw) { console.error("โ JWKS_KEY missing in .env.local"); process.exit(1); }+if (!svc) { console.error("โ AGENT_GATEWAY_SERVICE_TOKEN missing in .env.local"); process.exit(1); }+const jwks = JSON.parse(jwksRaw);+// strip private fields โ public JWK set (gateway only verifies signatures)+const pub = { keys: jwks.keys.map(k => { const { d, p, q, dp, dq, qi, ...rest } = k; return rest; }) };+fs.writeFileSync(process.argv[2], `JWKS_PUBLIC_KEY=${JSON.stringify(pub)}\nSERVICE_TOKEN=${svc}\n`);+const kid = pub.keys.find(k => k.alg === "RS256")?.kid;+console.log("โ wrote " + process.argv[2]);+console.log(" JWKS_PUBLIC_KEY kid =", kid, "(public only, no private d)");+console.log(" SERVICE_TOKEN head =", svc.slice(0, 10) + "โฆ");+' "$APP_ENV" "$GATEWAY_DIR/.dev.vars"++cat <<EOF++โโ Next steps โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+1) Start the local gateway worker (separate terminal):+ cd "$GATEWAY_DIR" && bun run dev # wrangler dev โ http://localhost:$PORT+ Sanity: curl -s -o /dev/null -w '%{http_code}\\n' http://localhost:$PORT/health # โ 200++2) Point the APP at the local gateway, then RESTART the dev server:+ AGENT_GATEWAY_URL=http://localhost:$PORT # client builds ws://localhost:$PORT/ws+ AGENT_GATEWAY_SERVICE_TOKEN=<unchanged> # same value already in .env.local+ ENABLE_AGENT_GATEWAY=1 # drives serverConfig.enableGatewayMode++3) In the browser, send a message. Expect the gateway WS to reply+ {"type":"auth_success"} (NOT auth_failed) and stream events.+ Probe auth in isolation with the harness in references/agent-gateway.md.+โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+EOFdiff --git a/.agents/skills/agent-testing/scripts/report-init.sh b/.agents/skills/agent-testing/scripts/report-init.shindex 2f6564ba822..6bacd36dcfd 100755--- a/.agents/skills/agent-testing/scripts/report-init.sh+++ b/.agents/skills/agent-testing/scripts/report-init.sh@@ -29,13 +29,10 @@ DATE_ISO=$(date '+%Y-%m-%dT%H:%M:%S%z')# summary.conclusion + summary.score), so DON'T repeat any of them here or they# double up. Keep only non-duplicate detail: repro commands, caveats, follow-ups.cat > "$DIR/report.md" << EOF-<!-- Rendered as the verify page's "Details" tail. The page already shows the- title / scope / checks / conclusion / score, so DON'T add an H1 title or- repeat them here โ write only the non-duplicate comment below. -->-## ๅคๆณจ / ่ฏดๆ-<!-- ๅค็ฐๅฝไปคใๆณจๆไบ้กนใไป้่ท่ฟ้กน๏ผๆฒกๆๅๅโๆ โใ -->+<!-- ๅค็ฐๅฝไปคใๆณจๆไบ้กนใไป้่ท่ฟ้กน๏ผๆฒกๆๅๅโๆ โใไธ่ฆ่ดดๅพ็/GIFโโ่ง่ง่ฏๆฎๆพๅจ+ result.json ็ cases[].evidence ้๏ผ้กต้ขไผๆธฒๆ๏ผreport.md ้้ๅคไผ้ๅคๅฑ็คบใ -->\`\`\`bash# commanddiff --git a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.tsindex cac291eefdc..ce5a64cca75 100644--- a/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts+++ b/apps/server/src/modules/AgentRuntime/RuntimeExecutors.ts@@ -441,6 +441,14 @@ const buildServerAgentMemberRunner = (const expectedMembers = members.length;if (expectedMembers === 0) return { started: false, startedCount: 0 };+ // In-group multi-member actions (broadcast) render as an AgentCouncil: each+ // member speaks DIRECTLY under the group tool message and the UI groups them+ // into one parallel-streaming block. This mirrors the client broadcast tree+ // (`metadata.agentCouncil` + member messages parented to the tool message),+ // so it reuses the same conversation-flow council path. No per-member receipt+ // anchors โ the member barrier counts completed member messages instead.+ const isCouncil = mode === 'in_group' && expectedMembers > 1;+// 1. Group tool placeholder โ the parked tool call the supervisor op waits// on. Stamped with the barrier target + finish disposition so the resume// path (and verify watchdog) resolve resume-vs-finish on their own.@@ -448,6 +456,7 @@ const buildServerAgentMemberRunner = (agentId,content: '',groupId,+ ...(isCouncil ? { metadata: { agentCouncil: true } } : {}),parentId: parentMessageId,plugin: chatToolPayload as any,pluginState: { expectedMembers, onComplete, status: 'pending' },@@ -458,7 +467,11 @@ const buildServerAgentMemberRunner = (});// 2. Per-member anchors. A single member collapses onto the group tool- // message; multiple members each get a child anchor under it.+ // message; multiple members each get a child anchor under it. These+ // anchors drive the K=N completion barrier; for councils the member+ // responses themselves attach to the group tool message (see+ // execAgentMember), so the UI groups them while the anchors stay+ // barrier-only and are filtered out of the council member set.const anchorIds: string[] = [];if (expectedMembers === 1) {anchorIds.push(groupTool.id);@@ -498,6 +511,9 @@ const buildServerAgentMemberRunner = (mode,onComplete,parentOperationId: ctx.operationId,+ // The supervisor assistant message owning this tool call โ council+ // members parent their response here (siblings of the council tool).+ supervisorMessageId: parentMessageId,timeout,topicId,});diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex f740588efb3..66dc3041437 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -290,6 +290,14 @@ export interface ExecGroupMemberParams {onComplete: GroupActionOnComplete;/** Parent (supervisor) operation id. */parentOperationId: string;+ /**+ * Supervisor ASSISTANT message id that owns the group-management tool call.+ * In-group council members parent their response to THIS message โ so the+ * member assistants are siblings of the council tool under the supervisor+ * turn and the renderer groups them into one council โ while the per-member+ * anchors stay under `groupToolMessageId` for the K=N barrier.+ */+ supervisorMessageId?: string;/** Per-member timeout (ms), isolated mode. */timeout?: number;/** Group topic id. */diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 87193a53a82..361dd9212f0 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -3482,6 +3482,7 @@ export class AiAgentService {instruction,onComplete,parentOperationId,+ supervisorMessageId,topicId,} = params;@@ -3527,6 +3528,17 @@ export class AiAgentService {// shared group conversation (no isolation thread). The bridge backfills the// member anchor (a short receipt) and resumes/finishes the supervisor.//+ // The member response attaches to the SUPERVISOR ASSISTANT message that owns+ // this group-management tool call (`supervisorMessageId`), NOT to the tool+ // message. For a multi-member broadcast the member assistants are therefore+ // siblings of the `agentCouncil` tool under one supervisor turn, and the+ // renderer groups them into a single parallel-streaming council card. The tool+ // message stays a pure result and the per-member anchors stay under it for the+ // K=N barrier only. This keeps the tool node clean and lets parallel speak/+ // broadcast turns render without the UI discontinuity the old tool-parented+ // shape caused. Falls back to the group tool message if no supervisor id was+ // threaded through (e.g. single-member collapses onto the tool anyway).+ //// The supervisor instruction is injected as an EPHEMERAL user message// (`suppressUserMessage` + `ephemeralUserMessage`): it drives the member's// response but is NOT persisted as a `role: 'user'` row, mirroring the@@ -3549,7 +3561,7 @@ export class AiAgentService {parentOperationId,}),],- parentMessageId: anchorMessageId,+ parentMessageId: supervisorMessageId ?? groupToolMessageId,parentOperationId,prompt: speakerInstruction,suppressUserMessage: true,diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.tsindex 6d361f79df8..c8671898409 100644--- a/packages/conversation-flow/src/__tests__/parse.test.ts+++ b/packages/conversation-flow/src/__tests__/parse.test.ts@@ -411,28 +411,115 @@ describe('parse', () => {});describe('AgentCouncil Mode', () => {- it('should parse simple agentCouncil (broadcast) correctly', () => {+ // The council renders as a `council` block INSIDE the supervisor's assistant+ // group (parallel columns), not as a separate top-level agentCouncil message.+ const findCouncilBlock = (result: ReturnType<typeof parse>): any => {+ for (const msg of result.flatList) {+ const block = (msg as any).children?.find(+ (b: any) => Array.isArray(b?.council) && b.council.length > 0,+ );+ if (block) return block;+ }+ return undefined;+ };++ it('should render a simple broadcast as an in-bubble council block', () => {const result = parse(inputs.agentCouncil.simple);- expect(serializeParseResult(result)).toEqual(outputs.agentCouncil.simple);+ // No separate agentCouncil message; the council is a block in the group bubble.+ expect(result.flatList.some((m) => m.role === 'agentCouncil')).toBe(false);+ const council = findCouncilBlock(result);+ expect(council).toBeDefined();+ expect(council.council.map((m: any) => m.id)).toEqual([+ 'msg-agent-backend-1',+ 'msg-agent-devops-1',+ 'msg-agent-architect-1',+ ]);});- it('should parse agentCouncil with supervisor final reply correctly', () => {- const result = parse(inputs.agentCouncil.withSupervisorReply);+ // Regression (server runtime tree): the server-side group orchestration parents+ // per-member completion anchors (`role: 'tool'`) under the broadcast tool message+ // for its K=N barrier, alongside the member assistant responses. Those anchors are+ // bookkeeping, not council members โ the council block must hold exactly the+ // assistant members and the anchors must never surface anywhere.+ it('should ignore server-runtime barrier anchors and keep only assistant council members', () => {+ const broadcastToolId = 'msg-broadcast-tool-1';+ const anchors = [0, 1, 2].map((i) => ({+ content: '',+ createdAt: 1_704_067_202_500 + i,+ id: `msg-anchor-m${i}`,+ metadata: {},+ parentId: broadcastToolId,+ pluginState: { status: 'pending' },+ role: 'tool' as const,+ tool_call_id: `call_broadcast_1::m${i}`,+ updatedAt: 1_704_067_202_500 + i,+ }));+ // Anchors are created before the members fork, so they sort first under the tool.+ const messages = [...inputs.agentCouncil.simple, ...anchors];++ const result = parse(messages as any);++ const council = findCouncilBlock(result);+ expect(council).toBeDefined();+ // Exactly the 3 assistant members โ no anchors mixed in.+ expect(council.council.map((m: any) => m.id)).toEqual([+ 'msg-agent-backend-1',+ 'msg-agent-devops-1',+ 'msg-agent-architect-1',+ ]);+ // None of the anchors leak into the flat list (e.g. as orphan tool messages).+ const flatIds = result.flatList.map((m) => m.id);+ for (const anchor of anchors) expect(flatIds).not.toContain(anchor.id);+ });- // The critical assertions:- // 1. flatList should have 4 items: user, supervisor(+tool), agentCouncil(3 agents), supervisor-summary- expect(result.flatList).toHaveLength(4);- expect(result.flatList[0].role).toBe('user');- expect(result.flatList[1].role).toBe('supervisor'); // supervisor with tools gets role='supervisor'- expect(result.flatList[2].role).toBe('agentCouncil');- expect(result.flatList[3].role).toBe('supervisor'); // supervisor final reply- expect(result.flatList[3].id).toBe('msg-supervisor-summary');+ // Regression (new server runtime tree): broadcast members are parented to the+ // SUPERVISOR ASSISTANT message (siblings of the council tool), not to the tool.+ // The per-member barrier anchors stay UNDER the council tool. The council block+ // must still hold exactly the assistant members and never surface the anchors.+ it('should build the council block when members are siblings of the council tool (assistant-parented)', () => {+ const supervisorId = 'msg-supervisor-1';+ const broadcastToolId = 'msg-broadcast-tool-1';+ const memberIds = ['msg-agent-backend-1', 'msg-agent-devops-1', 'msg-agent-architect-1'];+ // Re-parent the members onto the supervisor assistant (the new shape).+ const base = inputs.agentCouncil.simple.map((m) =>+ memberIds.includes(m.id) ? { ...m, parentId: supervisorId } : m,+ );+ // Barrier anchors live under the council tool, created before members stream.+ const anchors = [0, 1, 2].map((i) => ({+ content: '',+ createdAt: 1_704_067_202_500 + i,+ id: `msg-anchor-m${i}`,+ metadata: {},+ parentId: broadcastToolId,+ pluginState: { status: 'completed' },+ role: 'tool' as const,+ tool_call_id: `call_broadcast_1::m${i}`,+ updatedAt: 1_704_067_202_500 + i,+ }));++ const result = parse([...base, ...anchors] as any);++ const council = findCouncilBlock(result);+ expect(council).toBeDefined();+ expect(council.council.map((m: any) => m.id)).toEqual(memberIds);+ // The supervisor bubble still renders, and the anchors never leak.+ const flatIds = result.flatList.map((m) => m.id);+ expect(flatIds).toContain(supervisorId);+ for (const anchor of anchors) expect(flatIds).not.toContain(anchor.id);+ });- // 2. agentCouncil should have 3 members (not 4, supervisor summary is separate)- expect((result.flatList[2] as any).members).toHaveLength(3);+ it('should render the supervisor final reply after the in-bubble council', () => {+ const result = parse(inputs.agentCouncil.withSupervisorReply);- expect(serializeParseResult(result)).toEqual(outputs.agentCouncil.withSupervisorReply);+ // flatList: user, supervisor group (tool-use + council block), supervisor summary.+ expect(result.flatList).toHaveLength(3);+ expect(result.flatList[0].role).toBe('user');+ expect(result.flatList[1].role).toBe('supervisor');+ expect(result.flatList[2].id).toBe('msg-supervisor-summary');+ // No separate agentCouncil message; the council is a block with 3 members.+ expect(result.flatList.some((m) => m.role === 'agentCouncil')).toBe(false);+ expect(findCouncilBlock(result)?.council).toHaveLength(3);});// Regression: the supervisor's post-council reply must surface no matter which council@@ -443,9 +530,7 @@ describe('parse', () => {'should surface supervisor final reply when it parents to council member %s',(memberId) => {const messages = inputs.agentCouncil.withSupervisorReply.map((message) =>- message.id === 'msg-supervisor-summary'- ? { ...message, parentId: memberId }- : message,+ message.id === 'msg-supervisor-summary' ? { ...message, parentId: memberId } : message,);const result = parse(messages);diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.tsindex 22445bf0ee2..edd6de482a9 100644--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts@@ -69,33 +69,12 @@ export class FlatListBuilder {): void {const children = this.childrenMap.get(parentId) ?? [];- // Pre-loop check: AgentCouncil mode on parent (tool message with multiple assistant children)- // This handles the case when we continue from a tool message that triggered broadcast+ // Broadcast councils now render in-bubble (a `council` block inside the+ // supervisor's assistant group), so there is no separate agentCouncil message+ // to emit when recursing into a council tool โ its members were already+ // collected and marked processed by collectCouncilMembers.if (parentId) {const parentMessage = this.messageMap.get(parentId);- if (parentMessage && this.isAgentCouncilMode(parentMessage) && children.length > 1) {- // Create agentCouncil virtual message from the parent tool message- const agentCouncilMessage = this.createAgentCouncilMessageFromChildIds(- parentMessage,- children,- allMessages,- processedIds,- );- flatList.push(agentCouncilMessage);-- // Continue from each member's children to surface the supervisor's post-council reply.- // The reply attaches to exactly ONE member, but which member is non-deterministic:- // broadcast agents finish near-simultaneously so their createdAt values tie, and the- // writer anchors the reply to the createdAt-last member while childrenMap preserves- // input-array order โ the two can disagree. Walking only children.at(-1) would strand- // the reply (and everything after it) whenever they disagree. Members are already in- // processedIds, so recursing into every member only emits the reply chain; the- // processedIds guard keeps it from duplicating anything.- for (const memberId of children) {- this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);- }- return;- }// Pre-loop check: Tasks aggregation (multiple task messages with same parentId)// This handles the case when multiple async tasks are spawned from the same tool message@@ -263,6 +242,10 @@ export class FlatListBuilder {allMessages,);+ // A broadcast turn renders its members as one in-bubble council block.+ // Gather them before building the group so they embed inside it.+ const council = this.collectCouncilMembers(allToolMessages, allMessages, processedIds);+// Create assistantGroup virtual messageconst groupMessage = this.createAssistantGroupMessage(assistantChain[0],@@ -270,6 +253,7 @@ export class FlatListBuilder {allToolMessages,signalBlocks,taskCompletionMessages,+ council?.members,);flatList.push(groupMessage);@@ -283,6 +267,13 @@ export class FlatListBuilder {processedIds.add(completion.id);}+ // Surface the supervisor's post-council reply (attached to one member).+ if (council) {+ for (const memberId of council.memberIds) {+ this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);+ }+ }+this.continueAfterAssistantGroup(assistantChain,allToolMessages,@@ -342,22 +333,6 @@ export class FlatListBuilder {continue;}- // Priority 3b: AgentCouncil mode (from message metadata, typically on tool messages)- if (this.isAgentCouncilMode(message) && childMessages.length > 1) {- // Create agentCouncil virtual message with proper handling of AssistantGroups- const agentCouncilMessage = this.createAgentCouncilMessageFromChildIds(- message,- childMessages,- allMessages,- processedIds,- );- flatList.push(agentCouncilMessage);-- // AgentCouncil doesn't continue - all columns are parallel endpoints- // The conversation continues after the supervisor completes orchestration- continue;- }-// Priority 3d: User message with branches (multiple assistant children)// Branch indicator should be on the active assistant child messageif (message.role === 'user' && nonToolChildMessages.length > 1) {@@ -514,11 +489,17 @@ export class FlatListBuilder {processedIds,);+ // A broadcast turn embeds its members as an in-bubble council block.+ const council = this.collectCouncilMembers(allToolMessages, allMessages, processedIds);+// Create assistantGroup virtual messageconst groupMessage = this.createAssistantGroupMessage(assistantChain[0],assistantChain,allToolMessages,+ undefined,+ undefined,+ council?.members,);flatList.push(groupMessage);@@ -526,6 +507,12 @@ export class FlatListBuilder {assistantChain.forEach((m) => processedIds.add(m.id));allToolMessages.forEach((m) => processedIds.add(m.id));+ if (council) {+ for (const memberId of council.memberIds) {+ this.buildFlatListRecursive(memberId, flatList, processedIds, allMessages);+ }+ }+this.continueAfterAssistantGroup(assistantChain,allToolMessages,@@ -567,6 +554,64 @@ export class FlatListBuilder {}}+ /**+ * New-shape AgentCouncil: a supervisor turn whose tool call carries+ * `agentCouncil` metadata renders its broadcast members โ the ASSISTANT+ * children of the supervisor message, siblings of the council tool โ as one+ * council group. The council tool's OWN children are server-runtime barrier+ * anchors (`role: 'tool'`), never council members; they are marked processed+ * so they don't surface as standalone tool bubbles.+ *+ * Returns true when a council was emitted. The legacy shape (members parented+ * directly under the tool message) carries no member siblings on the+ * supervisor message, so this returns false and the `buildFlatListRecursive`+ * council pre-loop handles it instead.+ */+ /**+ * Gather a broadcast turn's council members so they render as one in-bubble+ * `council` block inside the supervisor's assistant group (instead of a+ * separate top-level `agentCouncil` message). Members are the assistant+ * siblings of the `agentCouncil` tool (new server shape) or โ for the legacy+ * client shape โ the tool's own assistant children. The per-member barrier+ * anchors under the tool are bookkeeping and are marked processed.+ *+ * Returns the built member messages + their ids (already marked processed), or+ * undefined when this turn has no multi-member council.+ */+ private collectCouncilMembers(+ allToolMessages: Message[],+ allMessages: Message[],+ processedIds: Set<string>,+ ): { memberIds: string[]; members: Message[] } | undefined {+ const councilTool = allToolMessages.find((tool) => this.isAgentCouncilMode(tool));+ if (!councilTool) return undefined;++ const supervisorId = councilTool.parentId;+ let memberIds = supervisorId+ ? this.councilMemberChildIds(this.childrenMap.get(supervisorId) ?? []).filter(+ (id) => !processedIds.has(id),+ )+ : [];+ if (memberIds.length <= 1) {+ memberIds = this.councilMemberChildIds(this.childrenMap.get(councilTool.id) ?? []).filter(+ (id) => !processedIds.has(id),+ );+ }+ if (memberIds.length <= 1) return undefined;++ // Reuse the member-building (handles AssistantGroup members) and mark them+ // processed; we only keep the resulting members for the in-bubble block.+ const councilVirtual = this.createAgentCouncilMessageFromChildIds(+ councilTool,+ memberIds,+ allMessages,+ processedIds,+ );+ for (const anchorId of this.childrenMap.get(councilTool.id) ?? []) processedIds.add(anchorId);++ return { memberIds, members: (councilVirtual as { members?: Message[] }).members ?? [] };+ }+private buildFlatListRecursiveForChild(parentId: string,childId: string,@@ -628,6 +673,17 @@ export class FlatListBuilder {return (message.metadata as any)?.agentCouncil === true;}+ /**+ * The council members under a broadcast tool message are its non-tool children+ * (the member assistant responses). The server runtime also parents per-member+ * barrier anchors (`role: 'tool'`) under the same tool message; those are+ * completion bookkeeping, not council members, so they are excluded here. On+ * the client the tool message has only assistant children, so this is a no-op.+ */+ private councilMemberChildIds(childIds: string[]): string[] {+ return childIds.filter((id) => this.messageMap.get(id)?.role !== 'tool');+ }+/*** Create compare virtual message from child IDs with AssistantGroup support*/@@ -733,8 +789,16 @@ export class FlatListBuilder {const members: Message[] = [];const memberIds: string[] = [];- // Process each child (member)+ // Council members are the non-tool children; the server runtime's per-member+ // barrier anchors (role: 'tool') are excluded. Mark those anchors processed+ // so they don't surface later as orphan tool messages.+ const memberChildIds = this.councilMemberChildIds(childIds);for (const childId of childIds) {+ if (!memberChildIds.includes(childId)) processedIds.add(childId);+ }++ // Process each child (member)+ for (const childId of memberChildIds) {const childMessage = this.messageMap.get(childId);if (!childMessage) continue;@@ -783,7 +847,7 @@ export class FlatListBuilder {const agentCouncilId = `agentCouncil-${parentMessage.id}-${memberIdsStr}`;// Calculate timestamps from all member messages- const allMemberMessages = childIds.map((id) => this.messageMap.get(id)).filter(Boolean);+ const allMemberMessages = memberChildIds.map((id) => this.messageMap.get(id)).filter(Boolean);const createdAt =allMemberMessages.length > 0? Math.min(...allMemberMessages.map((m) => m!.createdAt))@@ -846,6 +910,7 @@ export class FlatListBuilder {sourceToolName: string;}[],taskCompletionMessages?: Message[],+ councilMembers?: Message[],): Message {const children: AssistantContentBlock[] = [];@@ -950,6 +1015,16 @@ export class FlatListBuilder {children.push(childBlock);}+ // Broadcast members render as one in-bubble AgentCouncil block (parallel+ // columns), placed after the supervisor's tool-use block.+ if (councilMembers && councilMembers.length > 1) {+ children.push({+ content: '',+ council: councilMembers as unknown as AssistantContentBlock['council'],+ id: `council-${firstAssistant.id}`,+ } as AssistantContentBlock);+ }+const aggregated = this.messageTransformer.aggregateMetadata(children);// Collect all non-usage/performance metadata from all childrendiff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex c007c3eee83..d74d54cc911 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -246,6 +246,11 @@ export interface MessageMetadata {acceptedPredictionTokens?: number;activeBranchIndex?: number;activeColumn?: boolean;+ /**+ * Marks a `role: 'tool'` message (a group broadcast tool call) as an+ * AgentCouncil: its member responses render as one parallel-streaming block.+ */+ agentCouncil?: boolean;/*** Message collapse state* true: collapsed, false/undefined: expandeddiff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.tsindex f9c93936971..a9b2f1689f0 100644--- a/packages/types/src/message/ui/chat.ts+++ b/packages/types/src/message/ui/chat.ts@@ -87,6 +87,13 @@ export interface TaskBlock {export interface AssistantContentBlock {content: string;+ /**+ * Multi-agent broadcast members rendered inline as a single AgentCouncil block+ * (parallel columns) within the supervisor's assistant group โ instead of a+ * separate top-level `agentCouncil` message. Set on a dedicated council block+ * that carries no own content/tools.+ */+ council?: UIChatMessage[];error?: ChatMessageError | null;fileList?: ChatFileItem[];id: string;diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsxindex 13894fa9b35..2f6b4d1fd1d 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx@@ -22,6 +22,13 @@ vi.mock('antd-style', () => ({}),}));+// Mock the council list so importing Group doesn't pull in the AgentCouncil+// render chain (โ shared-tool-ui inspectors โ antd-style `keyframes`), which is+// out of scope for this unit test.+vi.mock('../../AgentCouncil/components/CouncilList', () => ({+ default: ({ members }: { members?: unknown[] }) => <div>council:{members?.length ?? 0}</div>,+}));+vi.mock('../../../store', () => ({messageStateSelectors: {isAssistantGroupItemGenerating: () => () => mockIsGenerating,diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsxindex d8261f8193c..5592b393547 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.tsx@@ -8,6 +8,7 @@ import ContentLoading from '@/features/Conversation/Messages/components/ContentLimport type { AssistantContentBlock } from '@/types/index';import { messageStateSelectors, useConversationStore } from '../../../store';+import CouncilList from '../../AgentCouncil/components/CouncilList';import { MessageAggregationContext } from '../../Contexts/MessageAggregationContext';import { POST_TOOL_FINAL_ANSWER_SCORE_THRESHOLD } from '../constants';import {@@ -86,6 +87,7 @@ const WORKFLOW_DOM_ID_SUFFIX = '__workflow';const isEmptyBlock = (block: RenderableAssistantContentBlock) =>(!block.content || block.content === LOADING_FLAT) &&(!block.tools || block.tools.length === 0) &&+ (!block.council || block.council.length === 0) &&!block.error &&!block.reasoning;@@ -469,6 +471,20 @@ const Group = memo<GroupChildrenProps>(}const item = segment.block;++ // AgentCouncil block: broadcast members rendered as parallel columns inside+ // the supervisor's bubble.+ if (item.council && item.council.length > 0) {+ return (+ <CouncilList+ activeTab={0}+ displayMode={'horizontal'}+ key={item.renderKey ?? `${id}.${item.id}.${index}`}+ members={item.council}+ />+ );+ }+if (!isGenerating && isEmptyBlock(item)) return null;return (