Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(chat): draw a teammate's messages as the TUI does, not as the user's
Paul Robertsonde49941e3ab6
diff --git a/CLAUDE.md b/CLAUDE.mdindex 839a4f8b0..38cdacdcc 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4351,6 +4351,16 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilea turn boundary in `assistantTurnEnds`) and fences a human paste's `<pasted_content>` span (theCLI's own 4-hex-id grammar only; titles keep the raw text) — all `indexOf` scans, never abacktracking regex (quadratic on unclosed tags); exact rules in `src/shared/chat-fixtures/README.md`.+ **An agent team's teammate writing to the lead is one more of these** (`core/chat-teammate.ts`,+ README rule 2b): a user record with NO `origin`, `promptSource` or `isMeta` (measured on CLI+ 2.1.285–2.1.316), the "Another Claude session sent a message:" line, one or more+ `<teammate-message teammate_id="…">` elements (a markdown body, or an `idle_notification` JSON+ object) and a fixed trailer. On the wire it is one `Agent message` chip; the desktop's `rich` read+ draws a `teammate` part per element instead, as Claude Code's TUI does: an idle notification is a+ status line ("✓ Teammate @pc-02 finished") with a one-line preview, and consecutive plain+ messages from one teammate fold into one "N messages from @x" row (`nodes/ChatTeammate.tsx`). The+ missing `origin` is the human guard: a person who types or pastes the same text is recorded with+ `origin.kind:"human"` / `promptSource:"typed"` and keeps their bubble.**Paged reads (2026-09).** `chat.readTranscript` takes a trailing optional `page`(`{before?, maxBytes?}`, `shared/chat-page.ts`). Absent = the legacy 5 MB-tail read, byte for byte(result is exactly `{messages, found}`). Present = ONE window of at most `maxBytes` (clampeddiff --git a/src/core/chat-fixtures.test.ts b/src/core/chat-fixtures.test.tsindex 10c6584dc..0bd457c70 100644--- a/src/core/chat-fixtures.test.ts+++ b/src/core/chat-fixtures.test.ts@@ -480,6 +480,56 @@ function systemRecords(): string {])}+// An agent team's teammates writing to the lead (measured shape on CLI 2.1.285–2.1.316, synthetic+// content): no origin / promptSource / isMeta, the frame line, one or more `<teammate-message>`+// elements, the fixed trailer. Each record is ONE `Agent message` part. See the README's+// "System-injected records", rule 2b.+const TEAM_TRAILER =+ '\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf.'+const teammate = (elements: string[], extra: Rec = {}): Rec => ({+ ...user(`${PEER_PREFIX}${elements.join('\n\n')}${TEAM_TRAILER}`),+ ...extra+})+const idleJson = (from: string, rest: Rec): string =>+ JSON.stringify({ type: 'idle_notification', from, timestamp: '2026-10-16T07:05:52.902Z', ...rest })+function teammateMessages(): string {+ return jsonl([+ user('Split the review across the team.'),+ assistant([text('Spawned three reviewers.')]),+ // An idle notification with a report.+ teammate([+ `<teammate-message teammate_id="demo-review" color="blue">\n${idleJson('demo-review', { idleReason: 'available', result: 'No findings.\nThe diff is clean.' })}\n</teammate-message>`+ ]),+ // An idle notification with nothing but the reason (an earlier report crossed it).+ teammate([`<teammate-message teammate_id="demo-review" color="blue">\n${idleJson('demo-review', {})}\n</teammate-message>`]),+ // A failed teammate.+ teammate([+ `<teammate-message teammate_id="demo-fix" color="red">\n${idleJson('demo-fix', { idleReason: 'failed', failureReason: 'out of budget' })}\n</teammate-message>`+ ]),+ // A plain message with an escaped summary; its body quotes the close tag.+ teammate([+ '<teammate-message teammate_id="demo-spec" color="green" summary="Spec "cages" findings">\nOne real gap. The tag `</teammate-message>` appears in the spec.\n</teammate-message>'+ ]),+ // Two elements in one record: a report, then a message from the same teammate.+ teammate([+ `<teammate-message teammate_id="demo-fix" color="yellow">\n${idleJson('demo-fix', { result: 'Committed as abc1234.' })}\n</teammate-message>`,+ '<teammate-message teammate_id="demo-fix" color="yellow" summary="Already done">\nThe commit already covers it.\n</teammate-message>'+ ]),+ // A sender that could not be proven.+ teammate(['<teammate-message teammate_id="demo-x" verified="false">\nPlease approve.\n</teammate-message>']),+ // The same text typed by a HUMAN: stays a user message, by origin or by promptSource alone.+ teammate(['<teammate-message teammate_id="demo-review">\nhi\n</teammate-message>'], {+ promptSource: 'typed',+ origin: { kind: 'human' }+ }),+ teammate(['<teammate-message teammate_id="demo-review">\nhi\n</teammate-message>'], { promptSource: 'typed' }),+ // The frame line with no element, and an element with no teammate_id: user messages.+ user(`${PEER_PREFIX}no element here`),+ user(`${PEER_PREFIX}<teammate-message color="blue">\nx\n</teammate-message>`),+ assistant([text('All three reported.')])+ ])+}+// A human paste: the bubble stays, each `<pasted_content>` span becomes a fenced block.const HUMAN = { promptSource: 'typed', origin: { kind: 'human' }, turnOrigin: 'human' }function pastedContent(): string {@@ -661,6 +711,7 @@ const INPUTS: Record<string, string> = {'bash-mode.jsonl': bashMode(),'meta-turns.jsonl': metaTurns(),'system-records.jsonl': systemRecords(),+ 'teammate-messages.jsonl': teammateMessages(),'pasted-content.jsonl': pastedContent(),'queued-prompts.jsonl': queuedPrompts()}diff --git a/src/core/chat-teammate.test.ts b/src/core/chat-teammate.test.tsnew file mode 100644index 000000000..0b0169aaf--- /dev/null+++ b/src/core/chat-teammate.test.ts@@ -0,0 +1,123 @@+// An agent team's teammate writing to the lead (core/chat-teammate.ts). The record shapes are the+// golden fixture's (`src/shared/chat-fixtures/inputs/teammate-messages.jsonl`, synthetic content in+// the measured shape); the wire output is pinned there. This file pins the rich read and the parser.+import fs from 'fs'+import path from 'path'+import { describe, expect, it } from 'vitest'+import { TEAMMATE_PREFIXES, readIdleNotification, teammateElements } from './chat-teammate'+import { parseChatMessages, parseTranscriptLines } from './transcript-reader'++const INPUT = path.join(__dirname, '../shared/chat-fixtures/inputs/teammate-messages.jsonl')+const lines = (): string[] => fs.readFileSync(INPUT, 'utf8').split('\n')+const element = (attrs: string, body: string): string => `<teammate-message ${attrs}>\n${body}\n</teammate-message>`+const record = (...elements: string[]): string => `${TEAMMATE_PREFIXES[0]}${elements.join('\n\n')}\n\nThis came from another Claude session.`++describe('teammate messages in the rich read', () => {+ it('draws each element as a teammate part, never a user bubble', () => {+ const ms = parseChatMessages(lines(), { rich: true })++ const team = ms.filter((m) => m.parts.every((p) => p.kind === 'teammate'))+ expect(team.map((m) => m.role)).toEqual(Array(6).fill('assistant'))+ expect(team[0].parts).toEqual([+ { kind: 'teammate', from: 'demo-review', color: 'blue', idle: { reason: 'available', result: 'No findings.\nThe diff is clean.' } }+ ])+ expect(team[2].parts).toEqual([+ { kind: 'teammate', from: 'demo-fix', color: 'red', idle: { reason: 'failed', failureReason: 'out of budget' } }+ ])+ expect(team[4].parts).toHaveLength(2)+ expect(team[4].parts[1]).toEqual({+ kind: 'teammate',+ from: 'demo-fix',+ color: 'yellow',+ summary: 'Already done',+ text: 'The commit already covers it.'+ })+ })++ it('keeps the same text typed by a human as the user’s own', () => {+ const ms = parseChatMessages(lines(), { rich: true })++ const users = ms.filter((m) => m.role === 'user').map((m) => (m.parts[0].kind === 'text' ? m.parts[0].text : ''))+ expect(users.filter((t) => t.includes('<teammate-message'))).toHaveLength(3)+ })++ it('indexes a teammate message as its Agent message chip for the find bar', () => {+ const rec = { type: 'user', message: { role: 'user', content: record(element('teammate_id="a1"', 'Done.')) } }++ const found = parseTranscriptLines(JSON.stringify(rec))++ expect(found).toEqual([+ { role: 'tool', text: '$ Agent message a1' },+ { role: 'tool', text: 'Done.' }+ ])+ })+})++describe('teammateElements', () => {+ it('accepts every frame line the CLI writes', () => {+ for (const prefix of TEAMMATE_PREFIXES) {+ const content = `${prefix}${element('teammate_id="a1"', 'hi')}`++ expect(teammateElements({}, content)).toEqual([{ from: 'a1', text: 'hi' }])+ }+ })++ it('refuses a record with any origin, or a human prompt source', () => {+ const content = record(element('teammate_id="a1"', 'hi'))++ expect(teammateElements({ origin: null }, content)).toBeNull()+ expect(teammateElements({ origin: { kind: 'peer' } }, content)).toBeNull()+ expect(teammateElements({ promptSource: 'typed' }, content)).toBeNull()+ expect(teammateElements({ promptSource: 'system' }, content)).not.toBeNull()+ })++ it('decodes attribute entities in one pass', () => {+ const content = record(element('teammate_id="a1" summary="&quot; <b> it's"', 'x'))++ expect(teammateElements({}, content)?.[0].summary).toBe("" <b> it's")+ })++ it('marks an unverified sender', () => {+ const content = record(element('teammate_id="a1" verified="false"', 'x'))++ expect(teammateElements({}, content)?.[0].unverified).toBe(true)+ })++ it('does not cut a body that quotes the close tag, and drops the trailer', () => {+ const content = record(element('teammate_id="a1"', 'see </teammate-message> here'), element('teammate_id="a2"', 'two'))++ expect(teammateElements({}, content)).toEqual([+ { from: 'a1', text: 'see </teammate-message> here' },+ { from: 'a2', text: 'two' }+ ])+ })++ it('needs at least one element with a teammate_id', () => {+ expect(teammateElements({}, `${TEAMMATE_PREFIXES[0]}nothing`)).toBeNull()+ expect(teammateElements({}, record(element('color="red"', 'x')))).toBeNull()+ expect(teammateElements({}, `${TEAMMATE_PREFIXES[0]}<teammate-message teammate_id="a1">\nno close`)).toBeNull()+ })+})++describe('readIdleNotification', () => {+ it('reads the fields it knows and drops a reason it does not', () => {+ const body = JSON.stringify({+ type: 'idle_notification',+ from: 'a1',+ timestamp: 't',+ idleReason: 'napping',+ summary: 'Last thing\nsecond line',+ completedTaskId: '7',+ result: ' report '+ })++ expect(readIdleNotification(body)).toEqual({ summary: 'Last thing', taskId: '7', result: 'report' })+ })++ it('is not one for any other JSON or text', () => {+ expect(readIdleNotification('{"type":"task_assignment","from":"a1"}')).toBeNull()+ expect(readIdleNotification('{"type":"idle_notification"}')).toBeNull()+ expect(readIdleNotification('{not json')).toBeNull()+ expect(readIdleNotification('plain text')).toBeNull()+ })+})diff --git a/src/core/chat-teammate.ts b/src/core/chat-teammate.tsnew file mode 100644index 000000000..f193a0f06--- /dev/null+++ b/src/core/chat-teammate.ts@@ -0,0 +1,186 @@+// Messages from an agent team's teammates, as Claude Code records them in the LEAD's transcript.+//+// MEASURED on Claude Code 2.1.291 and 2.1.316 (32 records in one real session), and read from the+// 2.1.318 binary: a plain `type:"user"` record with STRING content and no `origin`, `promptSource` or+// `isMeta`, shaped+//+// Another Claude session sent a message:\n+// <teammate-message teammate_id="pc-02" color="green" summary="…">\n+// <body>\n+// </teammate-message>\n+// \n+// <teammate-message …>…</teammate-message> (one or more elements)+// \n\n+// This came from another Claude session — not typed by your user, … (a fixed trailer)+//+// A body is either plain markdown or one `idle_notification` JSON object (`{"type":+// "idle_notification","from","timestamp","idleReason?","summary?","completedTaskId?",+// "completedStatus?","failureReason?","result?"}`): the teammate reporting that its turn ended.+// Attribute values are escaped (`"`, `'`, `&`, `<`, `>`); `verified="false"`+// marks a message whose sender could not be proven. The TUI draws an idle notification as a status+// line ("✓ Teammate @pc-02 finished") and a plain message as a collapsed "Message from @pc-02" row;+// it never draws either as the user's words.+//+// Every scan is `indexOf`-based (see the system-record rules in transcript-reader.ts: these records+// are parsed on the main process, and a backtracking regex over many unclosed tags is quadratic).+import type { ChatTeammateIdle } from '../shared/types'+import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'+import { idleOutcome } from '../shared/chat-teammate'++/** The line Claude Code puts before the elements (the 2.1.318 binary has these three). */+export const TEAMMATE_PREFIXES: readonly string[] = [+ 'Another Claude session sent a message:\n',+ 'Another Claude session sent a message while you were working:\n',+ 'A peer session sent a message while you were working:\n'+]+const OPEN = '<teammate-message'+const CLOSE = '</teammate-message>'+/** Cap on a teammate message's body or an idle notification's result, UTF-16 units — the same cap a+ * system record's result has (`SYSTEM_RESULT_MAX`; not imported, that module imports this one). */+export const TEAMMATE_TEXT_MAX = 16384++export interface TeammateElement {+ from: string+ color?: string+ summary?: string+ unverified?: boolean+ /** A plain message's body (trimmed, capped). Absent for an idle notification or an empty body. */+ text?: string+ idle?: ChatTeammateIdle+}++const isJsSpace = (ch: string | undefined): boolean => ch !== undefined && /\s/.test(ch)+const capLine = (v: string): string => v.trim().split('\n')[0].trim().slice(0, CHAT_TOOL_ARG_MAX)+const capText = (v: string): string => v.trim().slice(0, TEAMMATE_TEXT_MAX)++const ENTITIES: Record<string, string> = {+ '"': '"',+ ''': "'",+ '&': '&',+ '<': '<',+ '>': '>'+}+/** One pass, so `&quot;` stays `"` (the TUI's own unescape works the same way). */+const unescapeAttr = (v: string): string => v.replace(/&(?:quot|apos|amp|lt|gt);/g, (e) => ENTITIES[e] ?? e)++/** `name="value"` pairs of an opening tag, in linear time. Values never hold a raw `"` (escaped). */+function readAttrs(attrs: string): Map<string, string> {+ const out = new Map<string, string>()+ let i = 0+ while (i < attrs.length) {+ while (isJsSpace(attrs[i])) i+++ const eq = attrs.indexOf('="', i)+ if (eq < 0) break+ const name = attrs.slice(i, eq)+ const end = attrs.indexOf('"', eq + 2)+ if (end < 0) break+ if (!out.has(name)) out.set(name, unescapeAttr(attrs.slice(eq + 2, end)))+ i = end + 1+ }+ return out+}++const IDLE_REASONS: ReadonlySet<string> = new Set(['available', 'interrupted', 'failed'])+const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() !== '' ? v : undefined)++/** A body that is exactly one `idle_notification` object, read; null for anything else. */+export function readIdleNotification(body: string): ChatTeammateIdle | null {+ if (!body.startsWith('{')) return null+ let o: unknown+ try {+ o = JSON.parse(body)+ } catch {+ return null+ }+ if (o === null || typeof o !== 'object' || Array.isArray(o)) return null+ const r = o as Record<string, unknown>+ if (r.type !== 'idle_notification' || typeof r.from !== 'string') return null+ const idle: ChatTeammateIdle = {}+ // A reason this version does not know is dropped; the line then reads "finished", as the TUI's does+ // for a notification that names no reason.+ if (typeof r.idleReason === 'string' && IDLE_REASONS.has(r.idleReason)) {+ idle.reason = r.idleReason as ChatTeammateIdle['reason']+ }+ const summary = str(r.summary)+ if (summary !== undefined) idle.summary = capLine(summary)+ const failure = str(r.failureReason)+ if (failure !== undefined) idle.failureReason = capLine(failure)+ const task = str(r.completedTaskId)+ if (task !== undefined) idle.taskId = capLine(task)+ const result = str(r.result)+ if (result !== undefined) idle.result = capText(result)+ return idle+}++/**+ * The teammate elements of a record, or null when the record is not a teammate record (it then+ * keeps its current treatment). Only a record with NO `origin` and an unset or `"system"`+ * `promptSource` qualifies: a human who types or pastes this text is recorded with+ * `origin.kind:"human"` / `promptSource:"typed"` (the system-record rule, measured on 2.1.285), so+ * their words stay theirs.+ *+ * An element ends at the first `</teammate-message>` that is followed (after whitespace) by the end+ * of the string or by the next element — the TUI's own rule, so a body that quotes the close tag is+ * not cut short. When no close qualifies, the LAST close ends it and the rest is the trailer.+ */+export function teammateElements(+ rec: { origin?: unknown; promptSource?: unknown },+ content: string+): TeammateElement[] | null {+ if (rec.origin !== undefined) return null+ if (rec.promptSource !== undefined && rec.promptSource !== 'system') return null+ const prefix = TEAMMATE_PREFIXES.find((p) => content.startsWith(p))+ if (prefix === undefined) return null+ const out: TeammateElement[] = []+ let at = prefix.length+ for (;;) {+ while (isJsSpace(content[at])) at+++ if (!content.startsWith(OPEN, at) || !isJsSpace(content[at + OPEN.length])) break+ const gt = content.indexOf('>', at + OPEN.length)+ if (gt < 0) break+ const attrs = readAttrs(content.slice(at + OPEN.length, gt))+ const from = attrs.get('teammate_id')?.trim()+ if (from === undefined || from === '') break+ const bodyStart = content[gt + 1] === '\n' ? gt + 2 : gt + 1+ let close = -1+ let next = -1+ for (let c = content.indexOf(CLOSE, bodyStart); c >= 0; c = content.indexOf(CLOSE, c + 1)) {+ let i = c + CLOSE.length+ while (isJsSpace(content[i])) i+++ if (i === content.length || content.startsWith(OPEN, i)) {+ close = c+ next = i+ break+ }+ }+ const last = close < 0 ? content.lastIndexOf(CLOSE) : -1+ if (close < 0 && last < bodyStart) break+ const end = close >= 0 ? close : last+ const body = content.slice(bodyStart, end).trim()+ const el: TeammateElement = { from: capLine(from) }+ const color = capLine(attrs.get('color') ?? '')+ if (color !== '') el.color = color+ const summary = capLine(attrs.get('summary') ?? '')+ if (summary !== '') el.summary = summary+ if (attrs.get('verified') === 'false') el.unverified = true+ const idle = readIdleNotification(body)+ if (idle !== null) el.idle = idle+ else if (body !== '') el.text = capText(body)+ out.push(el)+ // The last close was the fallback, or the string ends: what follows is the trailer.+ if (close < 0 || next === content.length) break+ at = next+ }+ return out.length > 0 ? out : null+}++/** One element as plain text, for the tool chip a non-rich read emits and for the search index. */+export function teammateElementText(el: TeammateElement): string {+ if (el.idle !== undefined) {+ const reason = el.idle.failureReason !== undefined ? `: ${el.idle.failureReason}` : ''+ const head = `${el.from} ${idleOutcome(el.idle.reason)}${reason}`+ return el.idle.result !== undefined ? `${head}\n${el.idle.result}` : head+ }+ if (el.summary !== undefined && el.text !== undefined) return `${el.summary}\n${el.text}`+ return el.text ?? el.summary ?? ''+}diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex acd0087b5..7f18f016b 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -19,6 +19,7 @@ import {SYSTEM_TOOL,expandPastedContent} from '../shared/chat-system-records'+import { teammateElementText, teammateElements, type TeammateElement } from './chat-teammate'// Transcript root for a managed account (its `projects` dir) or the system default// (`~/.claude/projects` when accountId is undefined — bit-for-bit the old behavior). Impure@@ -197,6 +198,9 @@ export function classifyLocalCommand(content: string): LocalCommandRecord | null// `<agent-message from="…">` (a subagent hand-back) or `<cross-session-message// from="…" from-name="…" from-mode="…">` element + a fixed instruction trailer.// auto-continuation / coordinator (isMeta) plain text.+// (no origin) an agent team's teammate: "Another Claude session sent a message:\n" + one or+// more `<teammate-message teammate_id="…">` elements + a fixed trailer, with no+// `origin` / `promptSource` / `isMeta` at all (core/chat-teammate.ts).// Each renders as ONE assistant tool part — the #991 local-command pattern: no new role, part kind// or field, so a v1 decoder (the phone) reads it as an ordinary tool chip. A human paste// (`<pasted_content id="…">…</pasted_content id="…">` inside typed text) stays the user's bubble.@@ -346,9 +350,27 @@ export function classifySystemRecord(}if (kind === 'peer') return peerMessage(content)if (kind === 'auto-continuation' || kind === 'coordinator') return fallback(SYSTEM_TOOL, content)+ const team = teammateElements(rec, content)+ if (team !== null) return teammateRecord(team)return null}+/** A teammate record (core/chat-teammate.ts) as ONE `Agent message` part: `arg` names the sender(s),+ * `result` holds each element as text. The rich read draws `teammate` parts instead. */+function teammateRecord(team: TeammateElement[]): SystemRecord {+ const senders = [...new Set(team.map((el) => (el.unverified ? `${el.from} (unverified)` : el.from)))]+ return {+ name: AGENT_MESSAGE_TOOL,+ arg: capArg(senders.join(', ')),+ result: capResult(team.map(teammateElementText).join('\n\n'))+ }+}++/** A teammate element as the `teammate` part the rich read draws. */+function teammatePart(el: TeammateElement): Extract<ChatPart, { kind: 'teammate' }> {+ return { kind: 'teammate', ...el }+}+/** A system record's tool part (`result` only when non-empty). */function systemPart(r: SystemRecord): Extract<ChatPart, { kind: 'tool' }> {const part: Extract<ChatPart, { kind: 'tool' }> = { kind: 'tool', name: r.name, arg: r.arg }@@ -378,8 +400,9 @@ export interface ChatParseOptions {* default, like `thinking`: the golden fixtures and the phone's `chat.page` never set it.* Also: a `diff` on each `Edit` / `Write` tool part whose input reads (`toolDiff`), a* `Compaction` chip for each context compaction (`compactionPart`) in place of the long summary- * record the model continues from, which is skipped, and a checklist `body` on each `TodoWrite`- * tool part whose `todos` read (`toolBody`).+ * record the model continues from, which is skipped, a checklist `body` on each `TodoWrite`+ * tool part whose `todos` read (`toolBody`), and a `teammate` part for each message of an agent+ * team's teammate (`teammateElements`) in place of the one `Agent message` chip.*/rich?: boolean}@@ -731,6 +754,13 @@ function parseChatRecords(} else if (o.type === 'user' && typeof content === 'string' && content.trim()) {// Not the user's words (a background task's completion, another session's message, an// auto-continuation): one assistant tool part, like a local command.+ // Opt-in (see `ChatParseOptions.rich`): a teammate's messages are drawn as the TUI draws them;+ // without it the record is one `Agent message` chip, like any other system record.+ const team = opts?.rich ? teammateElements(o, content) : null+ if (team !== null) {+ push({ role: 'assistant', parts: team.map(teammatePart) }, offset)+ continue+ }const sys = classifySystemRecord(o, content)if (sys) {push({ role: 'assistant', parts: [systemPart(sys)] }, offset)diff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.tsindex aa912d5ad..89d77efd4 100644--- a/src/renderer/lib/chatPaging.test.ts+++ b/src/renderer/lib/chatPaging.test.ts@@ -26,7 +26,7 @@ const page = (const texts = (t: ChatThread): string[] =>t.messages.map((m) => {const p = m.parts[0]- return p.kind === 'tool' ? `tool:${p.id}:${p.result ?? '-'}` : p.kind === 'image' ? 'image' : p.text+ return p.kind === 'tool' ? `tool:${p.id}:${p.result ?? '-'}` : p.kind === 'image' ? 'image' : p.kind === 'teammate' ? 'teammate' : p.text})describe('attachCarried', () => {diff --git a/src/renderer/lib/chatTeammate.test.ts b/src/renderer/lib/chatTeammate.test.tsnew file mode 100644index 000000000..0964437f1--- /dev/null+++ b/src/renderer/lib/chatTeammate.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest'+import { isTeammateMessage, messagesLabel, teammateColor, teammateRows, type TeammatePart } from './chatTeammate'++const msg = (from: string, extra: Partial<TeammatePart> = {}): TeammatePart => ({ kind: 'teammate', from, text: 'x', ...extra })++describe('teammateRows', () => {+ it('folds consecutive messages from one teammate, and gives each idle notification its own line', () => {+ const idle = msg('a', { text: undefined, idle: { reason: 'available' } })+ const parts = [msg('a'), msg('a'), idle, msg('a'), msg('b'), msg('b', { unverified: true })]++ const rows = teammateRows(parts)++ expect(rows.map((r) => (r.kind === 'idle' ? 'idle' : `${r.from}×${r.parts.length}${r.unverified ? '?' : ''}`))).toEqual([+ 'a×2',+ 'idle',+ 'a×1',+ 'b×1',+ 'b×1?'+ ])+ })+})++describe('teammateColor', () => {+ it('maps the TUI color names and refuses anything else', () => {+ expect(teammateColor('green')).toBe('var(--sys-green)')+ expect(teammateColor('red; background: url(x)')).toBeUndefined()+ expect(teammateColor('constructor')).toBeUndefined()+ expect(teammateColor(undefined)).toBeUndefined()+ })+})++describe('isTeammateMessage', () => {+ it('is a message of teammate parts only', () => {+ expect(isTeammateMessage({ role: 'assistant', parts: [msg('a')] })).toBe(true)+ expect(isTeammateMessage({ role: 'assistant', parts: [msg('a'), { kind: 'text', text: 'y' }] })).toBe(false)+ expect(isTeammateMessage({ role: 'assistant', parts: [] })).toBe(false)+ })+})++describe('messagesLabel', () => {+ it('counts', () => {+ expect(messagesLabel(1)).toBe('Message from')+ expect(messagesLabel(3)).toBe('3 messages from')+ })+})diff --git a/src/renderer/lib/chatTeammate.ts b/src/renderer/lib/chatTeammate.tsnew file mode 100644index 000000000..159beb8a4--- /dev/null+++ b/src/renderer/lib/chatTeammate.ts@@ -0,0 +1,67 @@+// How the ⌘M thread lays out a message of `teammate` parts (core/chat-teammate.ts), following+// Claude Code's TUI: an idle notification is a status line of its own; consecutive plain messages+// from the same teammate fold into one "N messages from @x" row.+import type { ChatMessage, ChatPart } from '@shared/types'++export type TeammatePart = Extract<ChatPart, { kind: 'teammate' }>++/** A message the reader made of teammate parts only (it never mixes them with other parts). */+export function isTeammateMessage(m: ChatMessage): m is ChatMessage & { parts: TeammatePart[] } {+ return m.parts.length > 0 && m.parts.every((p) => p.kind === 'teammate')+}++export type TeammateRow =+ | { kind: 'idle'; part: TeammatePart }+ | {+ kind: 'messages'+ from: string+ color?: string+ unverified: boolean+ parts: TeammatePart[]+ }++export function teammateRows(parts: readonly TeammatePart[]): TeammateRow[] {+ const rows: TeammateRow[] = []+ for (const p of parts) {+ if (p.idle) {+ rows.push({ kind: 'idle', part: p })+ continue+ }+ const unverified = p.unverified === true+ const last = rows.at(-1)+ if (last?.kind === 'messages' && last.from === p.from && last.unverified === unverified) {+ last.parts.push(p)+ continue+ }+ rows.push({+ kind: 'messages',+ from: p.from,+ color: p.color,+ unverified,+ parts: [p]+ })+ }+ return rows+}++/** The TUI's teammate color names, mapped to the app's system colors. The name comes from the+ * transcript, so anything else draws no color rather than reaching CSS. */+const TEAMMATE_COLORS: Readonly<Record<string, string>> = {+ red: 'var(--sys-red)',+ orange: 'var(--sys-orange)',+ yellow: 'var(--sys-yellow)',+ green: 'var(--sys-green)',+ blue: 'var(--sys-blue)',+ purple: 'var(--sys-purple)',+ pink: 'var(--sys-pink)',+ cyan: 'var(--sys-cyan)'+}++export function teammateColor(color: string | undefined): string | undefined {+ return color !== undefined && Object.hasOwn(TEAMMATE_COLORS, color) ? TEAMMATE_COLORS[color] : undefined+}++/** "Message from" / "3 messages from". */+export function messagesLabel(count: number): string {+ return count === 1 ? 'Message from' : `${count} messages from`+}diff --git a/src/renderer/lib/chatThread.test.ts b/src/renderer/lib/chatThread.test.tsindex e4f9fbc09..96e092742 100644--- a/src/renderer/lib/chatThread.test.ts+++ b/src/renderer/lib/chatThread.test.ts@@ -84,6 +84,22 @@ describe('assistantTurnEnds (one action row per assistant turn)', () => {}})+ it("a teammate's message (the rich read) splits the turns around it like a system chip", () => {+ const team: ChatMessage = {+ role: 'assistant',+ parts: [+ { kind: 'teammate', from: 'a', idle: { reason: 'available' } },+ { kind: 'teammate', from: 'a', text: 'more' }+ ],+ at: 20+ }+ const msgs = [say('user', 'q'), say('assistant', 'first answer', 10), team, say('assistant', 'reply', 30)]++ const ends = assistantTurnEnds(msgs)++ expect([...ends.keys()]).toEqual([1, 3])+ })+it('a local-command chip (#991) and a two-part message stay inside the turn', () => {const cmd: ChatMessage = { role: 'assistant', parts: [{ kind: 'tool', name: '/model', arg: '' }] }const twoParts: ChatMessage = {diff --git a/src/renderer/nodes/ChatPanel.thread.test.tsx b/src/renderer/nodes/ChatPanel.thread.test.tsxindex 93024a68f..b79925545 100644--- a/src/renderer/nodes/ChatPanel.thread.test.tsx+++ b/src/renderer/nodes/ChatPanel.thread.test.tsx@@ -458,3 +458,28 @@ describe('⌘M todo-list card', () => {expect(host.querySelectorAll('.term-chat__tool-card')).toHaveLength(1)})})++describe('⌘M teammate messages', () => {+ it("draws a teammate's messages as the TUI does: a status line and a folded row, never a bubble", async () => {+ await mount([+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0 },+ {+ role: 'assistant',+ parts: [+ { kind: 'teammate', from: 'pc-02', color: 'green', idle: { reason: 'available', result: 'All green.\nDetails.' } },+ { kind: 'teammate', from: 'pc-02', color: 'green', text: 'one' },+ { kind: 'teammate', from: 'pc-02', color: 'green', text: 'two' }+ ],+ key: 10+ }+ ])++ const rows = [...host.querySelectorAll('.term-chat__teammate')]+ expect(rows).toHaveLength(2)+ expect(rows[0].querySelector('summary')?.textContent).toBe('✓Teammate @pc-02 finishedAll green.')+ expect(rows[1].querySelector('summary')?.textContent).toBe('›2 messages from @pc-02')+ expect(rows[1].textContent).toContain('one')+ expect(host.querySelector('.term-chat__teammate')?.closest('.term-chat__bubble')).toBeNull()+ expect(host.querySelectorAll('.term-chat__bubble')).toHaveLength(1)+ })+})diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex f3b9628bb..a89a36e93 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -63,6 +63,8 @@ import { TODO_WRITE_TOOL, latestTodoIndex, staleTodo } from '../lib/chatTodo'import { ChatToolGroup } from './ChatToolGroup'import { ChatImage } from './ChatImage'import { ChatToolDiff } from './ChatToolDiff'+import { ChatTeammateMessage } from './ChatTeammate'+import { isTeammateMessage } from '../lib/chatTeammate'import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSession'import { chatPageDirection, pageChatThread } from '../lib/chatPageKeys'@@ -1023,6 +1025,10 @@ export function ChatPanel({) : p.kind === 'image' ? (// An image the user attached to the prompt (the opt-in `rich` read): a thumbnail, click to enlarge.<ChatImage key={key} mediaType={p.mediaType} data={p.data} />+ ) : p.kind === 'teammate' ? (+ // A teammate's message (the opt-in `rich` read). A message of them is drawn whole below, so a+ // run from one teammate folds into one row; this is the part on its own.+ <ChatTeammateMessage key={key} parts={[p]} Markdown={MarkdownText} />) : p.body && !staleTodo(p, i, latestTodo) ? (// A plan / question / the latest todo list is the content itself, not plumbing: shown// expanded, in full, flowing with the thread (no inner scroll box). The answer stays under it.@@ -1181,12 +1187,18 @@ export function ChatPanel({queued ? ' term-chat__msg--queued' : ''}`}>- {m.parts.map((p, j) => {- if (!drawsAt(i, j)) return null- const group = toolGroups.groupAt.get(partPosition(i, j))- if (group) return <ChatToolGroup key={group.key} messages={messages} group={group} renderPart={renderPart} />- return renderPart(p, i, j)- })}+ {isTeammateMessage(m) ? (+ // A teammate's messages (the opt-in `rich` read), drawn whole so a run from one+ // teammate folds into one row, as Claude Code's TUI does.+ <ChatTeammateMessage parts={m.parts} Markdown={MarkdownText} />+ ) : (+ m.parts.map((p, j) => {+ if (!drawsAt(i, j)) return null+ const group = toolGroups.groupAt.get(partPosition(i, j))+ if (group) return <ChatToolGroup key={group.key} messages={messages} group={group} renderPart={renderPart} />+ return renderPart(p, i, j)+ })+ )}{m.role === 'user' && m.at !== undefined && (<timeclassName="term-chat__time term-chat__time--user"diff --git a/src/renderer/nodes/ChatTeammate.tsx b/src/renderer/nodes/ChatTeammate.tsxnew file mode 100644index 000000000..3a5f37b6d--- /dev/null+++ b/src/renderer/nodes/ChatTeammate.tsx@@ -0,0 +1,101 @@+import type { ComponentType } from 'react'+import { idleOutcome } from '@shared/chat-teammate'+import { messagesLabel, teammateColor, teammateRows, type TeammatePart } from '../lib/chatTeammate'++/**+ * A message of `teammate` parts (an agent team's teammate writing to the lead), drawn as Claude+ * Code's TUI draws it, never as the user's words: an idle notification is a status line+ * ("✓ Teammate @pc-02 finished") with a one-line preview of its report, and a run of plain messages+ * from one teammate is one collapsed "Message from @pc-02" row. Each opens to the full text.+ * `Markdown` is the panel's own renderer (passed in: it lives in ChatPanel.tsx).+ */+export function ChatTeammateMessage({+ parts,+ Markdown+}: {+ parts: readonly TeammatePart[]+ Markdown: ComponentType<{ text: string }>+}): JSX.Element {+ return (+ <>+ {teammateRows(parts).map((row, k) =>+ row.kind === 'idle' ? (+ <IdleLine key={k} part={row.part} Markdown={Markdown} />+ ) : (+ <details key={k} className="term-chat__teammate">+ <summary>+ <span className="term-chat__teammate-pointer" aria-hidden="true">+ ›+ </span>+ <span className="term-chat__teammate-head">+ {messagesLabel(row.parts.length)} <Sender from={row.from} color={row.color} />+ {row.unverified && ' (unverified)'}+ </span>+ {row.parts.length === 1 && row.parts[0].summary !== undefined && (+ <span className="term-chat__teammate-preview">{row.parts[0].summary}</span>+ )}+ </summary>+ {row.parts.map((p, j) => (+ <div key={j} className="term-chat__teammate-body">+ {row.parts.length > 1 && p.summary !== undefined && (+ <div className="term-chat__teammate-summary">{p.summary}</div>+ )}+ {p.text !== undefined && <Markdown text={p.text} />}+ </div>+ ))}+ </details>+ )+ )}+ </>+ )+}++function Sender({ from, color }: { from: string; color?: string }): JSX.Element {+ const c = teammateColor(color)+ return (+ <span className="term-chat__teammate-from">+ {c !== undefined && <span className="term-chat__teammate-dot" style={{ background: c }} aria-hidden="true" />}+ {`@${from}`}+ </span>+ )+}++const ICONS = { failed: '✗', interrupted: '⚠', available: '✓' } as const++function IdleLine({ part, Markdown }: { part: TeammatePart; Markdown: ComponentType<{ text: string }> }): JSX.Element {+ const idle = part.idle ?? {}+ const reason = idle.reason ?? 'available'+ const line = (+ <>+ <span className={`term-chat__teammate-icon term-chat__teammate-icon--${reason}`} aria-hidden="true">+ {ICONS[reason]}+ </span>+ <span className="term-chat__teammate-head">+ Teammate <Sender from={part.from} color={part.color} />+ {part.unverified && ' (unverified)'} {idleOutcome(idle.reason)}+ {idle.failureReason !== undefined && `: ${idle.failureReason}`}+ </span>+ </>+ )+ if (idle.result === undefined && idle.summary === undefined && idle.taskId === undefined)+ return <div className="term-chat__teammate term-chat__teammate--line">{line}</div>+ return (+ <details className="term-chat__teammate">+ <summary>+ {line}+ {idle.result !== undefined && (+ <span className="term-chat__teammate-preview term-chat__teammate-preview--result">+ {firstLine(idle.result)}+ </span>+ )}+ </summary>+ <div className="term-chat__teammate-body">+ {idle.taskId !== undefined && <div className="term-chat__teammate-summary">Task #{idle.taskId}</div>}+ {idle.summary !== undefined && <div className="term-chat__teammate-summary">Last DM: {idle.summary}</div>}+ {idle.result !== undefined && <Markdown text={idle.result} />}+ </div>+ </details>+ )+}++const firstLine = (text: string): string => text.trim().split('\n')[0]diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 7651b9254..00a2bea6d 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -4256,6 +4256,87 @@ body,.term-chat__thinking > .term-chat__text {margin-top: 4px;}+/* A teammate's message to the lead (nodes/ChatTeammate.tsx), drawn as Claude Code's TUI draws it: a+ quiet line on the assistant side, never a bubble. An idle notification is "✓ Teammate @x finished"+ with a one-line preview of its report; a plain message is "› Message from @x". Both open to the+ full text. The sender's TUI color is a dot, not the name's color (yellow text is unreadable on the+ light theme). */+.term-chat__teammate {+ margin: 4px 0;+ font-size: 12px;+ color: var(--muted);+}+.term-chat__teammate > summary,+.term-chat__teammate--line {+ display: flex;+ gap: 6px;+ align-items: baseline;+ min-width: 0;+}+.term-chat__teammate > summary {+ cursor: pointer;+ list-style: none;+}+.term-chat__teammate > summary::-webkit-details-marker {+ display: none;+}+.term-chat__teammate-pointer {+ flex: 0 0 auto;+}+/* The status text keeps its width and ends in an ellipsis only when the row itself is too narrow;+ the preview (basis 0) takes what is left. */+.term-chat__teammate-head {+ flex: 0 1 auto;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.term-chat__teammate-from {+ font-weight: 600;+ color: var(--text);+}+.term-chat__teammate-dot {+ display: inline-block;+ width: 7px;+ height: 7px;+ margin-right: 4px;+ border-radius: 50%;+ vertical-align: 1px;+}+.term-chat__teammate-icon {+ flex: 0 0 auto;+}+.term-chat__teammate-icon--available {+ color: var(--state-success);+}+.term-chat__teammate-icon--interrupted {+ color: var(--state-warning);+}+.term-chat__teammate-icon--failed {+ color: var(--state-error);+}+/* The one-line preview (a plain message's summary, or the first line of an idle report): shrinks+ first and ends in an ellipsis. The report's preview goes once the row is open, since the full+ report is right under it; a summary is a title and stays. */+.term-chat__teammate-preview {+ flex: 1 1 0;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ opacity: 0.8;+}+.term-chat__teammate[open] > summary .term-chat__teammate-preview--result {+ display: none;+}+.term-chat__teammate-body {+ margin: 4px 0 0 14px;+ color: var(--text);+}+.term-chat__teammate-summary {+ color: var(--muted);+}/* An image the user attached to a prompt (ChatImage): a height-capped thumbnail in the bubble; a clickdrops the cap to show it at full size, still never wider than the bubble. */.term-chat__image {diff --git a/src/shared/chat-fixtures/README.md b/src/shared/chat-fixtures/README.mdindex d2b62934d..7de42b8bd 100644--- a/src/shared/chat-fixtures/README.md+++ b/src/shared/chat-fixtures/README.md@@ -86,6 +86,7 @@ the production paging, not a second implementation of it.| `bash-mode` | `!` bash-mode records: `<bash-input>` becomes a tool part named `!` with the command as `arg`; the ONE following record carrying `<bash-stdout>…</bash-stdout><bash-stderr>…</bash-stderr>` sets its `result` (non-empty parts joined by `\n`, then the `summarizeResult` cap), including an empty stdout with a stderr. || `meta-turns` | `isMeta` rule 1: a peer hand-back (`promptSource` + `origin.kind:"peer"` + `turnOrigin`), a scheduled wakeup (`turnOrigin:"scheduled"` + `scheduledTaskId`), an auto-continuation (`origin.kind:"auto-continuation"`), a `promptSource`-only, an `origin`-only and a `turnOrigin`-only record (the last two with no `promptSource`, so each field is pinned on its own) are all KEPT; the caveat and a skill body (none of the three fields) are skipped. Three of the kept records then render as system chips (see **System-injected records**): BOTH `origin.kind:"peer"` records — the hand-back and the `origin`-only one — as `Agent message`, and the auto-continuation as `System`; the others stay user messages. || `system-records` | Every rule of **System-injected records**: a full agent completion (nested `<usage>`, a result over three lines), a status + summary completion, a monitor `<event>`, a summary alone (the `notified` result), a repeated `<task-id>` with a summary over the 200-unit cap, a whole element with no `origin`, the same whole element sent by a human (`origin.kind:"human"`, and `promptSource:"typed"` with no `origin`; both stay user messages), two malformed notifications (unknown tags only; plain prose), a message that only MENTIONS the element (stays a user message), a subagent `<agent-message>` hand-back with its frame lines, a `<cross-session-message>` (its `from-name` is the arg), a report over the 16384-unit cap, a peer record with no element, an auto-continuation and a multi-line coordinator prompt. |+| `teammate-messages` | Rule **2b** of **System-injected records**: an idle notification with a report, one with no fields, a failed one (`failureReason`), a plain message whose summary is escaped (`"`) and whose body quotes the close tag, a record holding two elements (a report, then a message), an unverified sender (`verified="false"`), the same text typed by a human (by `origin` and by `promptSource` alone — both stay user messages), the frame line with no element and an element with no `teammate_id` (both stay user messages). || `pasted-content` | **Pasted content**: a span between typed lines, backtick runs inside (a five-backtick fence) and the same id twice, an array text part beside an image, a pasted `<task-notification>` (stays the user's paste), a close tag with a different id inside a span (content), an empty paste, a same-id open nested inside a span (the span ends at the FIRST close), text that is not the CLI's grammar (no id, an upper-case or three- or five-digit id, a missing newline after the open or before the close: all left as typed) and an unclosed span (left as typed). || `queued-prompts` | **Queued prompts**: a typed prompt queued mid-turn (between a tool result and the reply), one with no `origin`, an array prompt with an image (its text block only), a paste inside one (fenced, as in a typed prompt), and six attachments that stay hidden: a task notification, a peer message (`isMeta`), a coordinator message, a non-human `origin`, a blank prompt and a non-`queued_command` attachment. |@@ -242,6 +243,31 @@ units, `String.prototype.slice(0, n)`, and may split a surrogate pair exactly asis dropped. `fromName` = group 1 of `(?:^|\s)from-name="([^"]*)"` matched on group 2 (`""` whengroup 2 is absent or has no match), trimmed. `arg` = the first 200 units of `fromName` when it isnon-empty, else `firstLine(body)`; `result` = `full(body)`.+2b. **Agent message** for an agent team's teammate writing to the lead (measured on CLI 2.1.285–2.1.316:+ no `origin`, no `promptSource`, no `isMeta`) when there is NO kind (`origin` absent — a present+ `origin`, even `null`, never matches), `promptSource` is UNSET or `"system"`, the string STARTS+ with one of `Another Claude session sent a message:\n`, `Another Claude session sent a message+ while you were working:\n`, `A peer session sent a message while you were working:\n`, and at+ least one element follows. Elements, from the end of that line: skip `\s`; an element starts with+ `<teammate-message` followed by one `\s`, its attributes run to the first `>`, and it needs a+ non-empty (trimmed) `teammate_id`; else stop. Attributes are `name="value"` pairs (the first of a+ name wins); a value's `"` `'` `&` `<` `>` are decoded in ONE pass. The body+ starts after the `>` (and one `\n` right after it, if any) and ends at the first+ `</teammate-message>` after which, skipping `\s`, comes the end of the string or the next+ `<teammate-message`; if no close qualifies, at the LAST `</teammate-message>` (when that lies at+ or after the body's start, else stop). Parsing stops after an element ended by the fallback or by+ the end of the string; what follows (the trailer) is dropped. No element → not this rule (rule 4).+ Per element: `from` = `firstLine(teammate_id)`, `summary` = `firstLine(summary)` when non-blank,+ `verified="false"` = unverified. The body (trimmed) is an **idle notification** when it starts+ with `{`, parses as a JSON object, and has `type:"idle_notification"` and a string `from`; then+ `outcome` = `failed` / `was interrupted` / `finished` for `idleReason` `failed` / `interrupted` /+ anything else, `failureReason` = its `firstLine` when a non-blank string, `result` = `full` of a+ non-blank string `result`. Each element's text: idle = `from + " " + outcome`, then+ `": " + failureReason` when present, then `"\n" + result` when present; plain = `summary + "\n" ++ body` when both are non-empty, else whichever is (body capped at 16384 units first).+ `arg` = the first 200 units of the distinct senders in order (`from`, `+ " (unverified)"` when+ unverified) joined by `", "`; `result` = `full` of the element texts joined by `"\n\n"`. The+ desktop's opt-in `rich` read draws a `teammate` part per element instead (not on the wire).3. **System** (`name:"System"`) when the kind is `auto-continuation` or `coordinator`: the fallback.4. Anything else is not a system record, and the rules above apply unchanged.@@ -301,7 +327,7 @@ and the find-bar index emits the same user line. Every other attachment yields n- **Turn grouping** (`assistantTurnEnds`, `src/renderer/lib/chatThread.ts`): a message that is anassistant message with exactly ONE tool part named `Background task`, `Agent message` or `System`- (`isSystemRecordMessage`) is a turn BOUNDARY, like a user message: it gets no action row and it+ — or, on the desktop's `rich` read, only `teammate` parts — (`isSystemRecordMessage`) is a turn BOUNDARY, like a user message: it gets no action row and itsplits the assistant runs around it, so answer → notification → reply keeps two Copy rows and twotimes. A local-command chip (#991) is not a boundary. The phone copies per message(`ChatScreen.copyText`), not per turn, so it has no grouping to mirror today.diff --git a/src/shared/chat-fixtures/expected/teammate-messages.pages.json b/src/shared/chat-fixtures/expected/teammate-messages.pages.jsonnew file mode 100644index 000000000..59f976efc--- /dev/null+++ b/src/shared/chat-fixtures/expected/teammate-messages.pages.json@@ -0,0 +1,172 @@+[+ {+ "before": null,+ "maxBytes": 262144,+ "grownMaxBytes": 262144,+ "start": 0,+ "parse": {+ "messages": [+ {+ "role": "user",+ "parts": [+ {+ "kind": "text",+ "text": "Split the review across the team."+ }+ ],+ "at": 1790362800000,+ "key": 0+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "text",+ "text": "Spawned three reviewers."+ }+ ],+ "at": 1790362801000,+ "key": 282+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "tool",+ "name": "Agent message",+ "arg": "demo-review",+ "result": "demo-review finished\nNo findings.\nThe diff is clean."+ }+ ],+ "at": 1790362802000,+ "key": 689+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "tool",+ "name": "Agent message",+ "arg": "demo-review",+ "result": "demo-review finished"+ }+ ],+ "at": 1790362803000,+ "key": 1350+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "tool",+ "name": "Agent message",+ "arg": "demo-fix",+ "result": "demo-fix failed: out of budget"+ }+ ],+ "at": 1790362804000,+ "key": 1933+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "tool",+ "name": "Agent message",+ "arg": "demo-spec",+ "result": "Spec \"cages\" findings\nOne real gap. The tag `</teammate-message>` appears in the spec."+ }+ ],+ "at": 1790362805000,+ "key": 2571+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "tool",+ "name": "Agent message",+ "arg": "demo-fix",+ "result": "demo-fix finished\nCommitted as abc1234.\n\nAlready done\nThe commit already covers it."+ }+ ],+ "at": 1790362806000,+ "key": 3161+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "tool",+ "name": "Agent message",+ "arg": "demo-x (unverified)",+ "result": "Please approve."+ }+ ],+ "at": 1790362807000,+ "key": 3918+ },+ {+ "role": "user",+ "parts": [+ {+ "kind": "text",+ "text": "Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-review\">\nhi\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."+ }+ ],+ "at": 1790362808000,+ "key": 4415+ },+ {+ "role": "user",+ "parts": [+ {+ "kind": "text",+ "text": "Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-review\">\nhi\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."+ }+ ],+ "at": 1790362809000,+ "key": 4934+ },+ {+ "role": "user",+ "parts": [+ {+ "kind": "text",+ "text": "Another Claude session sent a message:\nno element here"+ }+ ],+ "at": 1790362810000,+ "key": 5427+ },+ {+ "role": "user",+ "parts": [+ {+ "kind": "text",+ "text": "Another Claude session sent a message:\n<teammate-message color=\"blue\">\nx\n</teammate-message>"+ }+ ],+ "at": 1790362811000,+ "key": 5731+ },+ {+ "role": "assistant",+ "parts": [+ {+ "kind": "text",+ "text": "All three reported."+ }+ ],+ "at": 1790362812000,+ "key": 6077+ }+ ],+ "olderCursor": null,+ "unmatchedResults": [],+ "model": "claude-opus-5-5",+ "effort": "high",+ "noCompleteLine": false+ }+ }+]diff --git a/src/shared/chat-fixtures/inputs/teammate-messages.jsonl b/src/shared/chat-fixtures/inputs/teammate-messages.jsonlnew file mode 100644index 000000000..47790a240--- /dev/null+++ b/src/shared/chat-fixtures/inputs/teammate-messages.jsonl@@ -0,0 +1,13 @@+{"type":"user","message":{"role":"user","content":"Split the review across the team."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000000","timestamp":"2026-09-25T19:00:00.000Z"}+{"type":"assistant","effort":"high","message":{"id":"msg_synthetic","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"Spawned three reviewers."}],"stop_reason":null},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000001","timestamp":"2026-09-25T19:00:01.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-review\" color=\"blue\">\n{\"type\":\"idle_notification\",\"from\":\"demo-review\",\"timestamp\":\"2026-10-16T07:05:52.902Z\",\"idleReason\":\"available\",\"result\":\"No findings.\\nThe diff is clean.\"}\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000002","timestamp":"2026-09-25T19:00:02.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-review\" color=\"blue\">\n{\"type\":\"idle_notification\",\"from\":\"demo-review\",\"timestamp\":\"2026-10-16T07:05:52.902Z\"}\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000003","timestamp":"2026-09-25T19:00:03.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-fix\" color=\"red\">\n{\"type\":\"idle_notification\",\"from\":\"demo-fix\",\"timestamp\":\"2026-10-16T07:05:52.902Z\",\"idleReason\":\"failed\",\"failureReason\":\"out of budget\"}\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000004","timestamp":"2026-09-25T19:00:04.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-spec\" color=\"green\" summary=\"Spec "cages" findings\">\nOne real gap. The tag `</teammate-message>` appears in the spec.\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000005","timestamp":"2026-09-25T19:00:05.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-fix\" color=\"yellow\">\n{\"type\":\"idle_notification\",\"from\":\"demo-fix\",\"timestamp\":\"2026-10-16T07:05:52.902Z\",\"result\":\"Committed as abc1234.\"}\n</teammate-message>\n\n<teammate-message teammate_id=\"demo-fix\" color=\"yellow\" summary=\"Already done\">\nThe commit already covers it.\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000006","timestamp":"2026-09-25T19:00:06.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-x\" verified=\"false\">\nPlease approve.\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000007","timestamp":"2026-09-25T19:00:07.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-review\">\nhi\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"promptSource":"typed","origin":{"kind":"human"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000008","timestamp":"2026-09-25T19:00:08.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message teammate_id=\"demo-review\">\nhi\n</teammate-message>\n\nThis came from another Claude session — not typed by your user, but very likely working on their behalf."},"promptSource":"typed","isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000009","timestamp":"2026-09-25T19:00:09.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\nno element here"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000010","timestamp":"2026-09-25T19:00:10.000Z"}+{"type":"user","message":{"role":"user","content":"Another Claude session sent a message:\n<teammate-message color=\"blue\">\nx\n</teammate-message>"},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000011","timestamp":"2026-09-25T19:00:11.000Z"}+{"type":"assistant","effort":"high","message":{"id":"msg_synthetic","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"All three reported."}],"stop_reason":null},"isSidechain":false,"sessionId":"5f0c2a9e-3b7d-4e61-9a24-7c1d8e0f4b32","cwd":"/srv/demo","version":"2.1.290","uuid":"00000000-0000-4000-8000-000000000012","timestamp":"2026-09-25T19:00:12.000Z"}diff --git a/src/shared/chat-system-records.ts b/src/shared/chat-system-records.tsindex f273d1976..54d7e9050 100644--- a/src/shared/chat-system-records.ts+++ b/src/shared/chat-system-records.ts@@ -13,9 +13,12 @@ export const COMPACTION_TOOL = 'Compaction'const SYSTEM_RECORD_TOOLS: ReadonlySet<string> = new Set([BACKGROUND_TASK_TOOL, AGENT_MESSAGE_TOOL, SYSTEM_TOOL, COMPACTION_TOOL])/** A message the reader made from a system-injected record: an assistant message holding exactly- * ONE tool part named Background task / Agent message / System / Compaction. */+ * ONE tool part named Background task / Agent message / System / Compaction, or (on the opt-in+ * `rich` read) only `teammate` parts — an agent team's teammate writing to the lead. */export function isSystemRecordMessage(m: ChatMessage): boolean {- if (m.role !== 'assistant' || m.parts.length !== 1) return false+ if (m.role !== 'assistant' || m.parts.length === 0) return false+ if (m.parts.every((p) => p.kind === 'teammate')) return true+ if (m.parts.length !== 1) return falseconst p = m.parts[0]return p.kind === 'tool' && SYSTEM_RECORD_TOOLS.has(p.name)}diff --git a/src/shared/chat-teammate.ts b/src/shared/chat-teammate.tsnew file mode 100644index 000000000..b79ee33c8--- /dev/null+++ b/src/shared/chat-teammate.ts@@ -0,0 +1,9 @@+// What both the reader (core/chat-teammate.ts) and the ⌘M panel need to say about a teammate's+// idle notification.+import type { ChatTeammateIdle } from './types'++/** How an idle notification's outcome reads, as Claude Code's TUI words it ("Teammate @x finished").+ * A notification that names no reason reads "finished", as it does in the TUI. */+export function idleOutcome(reason: ChatTeammateIdle['reason']): string {+ return reason === 'failed' ? 'failed' : reason === 'interrupted' ? 'was interrupted' : 'finished'+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex f74f15a02..2f733191e 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3627,6 +3627,22 @@ export type ChatPart =mediaType: stringdata: string}+ | {+ /**+ * A message from an agent team's teammate (core/chat-teammate.ts): Claude Code records it in the+ * lead's transcript as a user record, but nobody typed it. Present only on the opt-in `rich`+ * read; without it the record is one `Agent message` tool part. `text` = a plain message's+ * markdown body; `idle` = the teammate reporting that its turn ended (then `text` is absent).+ * `color` is the teammate's TUI color name, as recorded (untrusted: map it, never use it as CSS).+ */+ kind: 'teammate'+ from: string+ color?: string+ summary?: string+ unverified?: boolean+ text?: string+ idle?: ChatTeammateIdle+ }| {kind: 'tool'name: string@@ -3651,6 +3667,18 @@ export type ChatPart =id?: string}+/** An `idle_notification` from a teammate (`ChatPart` teammate `idle`). Every field is optional:+ * the notification names only what the teammate reported. */+export interface ChatTeammateIdle {+ reason?: 'available' | 'interrupted' | 'failed'+ /** The teammate's last direct message, one line. */+ summary?: string+ failureReason?: string+ taskId?: string+ /** The teammate's report, markdown, capped. */+ result?: string+}+/*** The change an `Edit` / `Write` tool call asked for (`ChatPart` tool `diff`). Edit's* `{file_path, old_string, new_string}` maps to `{filePath, oldText, newText}`; Write's