claude-devtools:chatgroup-architecture
This slash command provides a reference guide to the ChatGroup architecture, a flat-list message handling system that converts raw JSON conversation data through multiple processing stages (classification, chunking, enhancement) into renderable user, system, and AI chat groups. Use it when working with the MessageClassifier, ChunkBuilder, ChunkFactory, groupTransformer, or related utilities to understand how individual user messages, system messages, and buffered AI responses flow through the rendering pipeline.
mkdir -p ~/.claude/commands && curl -fsSL https://raw.githubusercontent.com/matt1398/claude-devtools/HEAD/.claude/commands/devtools/chatgroup-architecture.md -o ~/.claude/commands/claude-devtools-chatgroup-architecture.mdchatgroup-architecture.md
# ChatGroup Architecture
How conversation data flows from raw JSONL messages to rendered chat groups.
## Core Design Principle
Chat groups are **independent items in a flat chronological list**, not paired turns.
There is no UserTurn/AITurn pairing — each group stands alone.
```typescript
// src/renderer/types/groups.ts
export type ChatItem =
| { type: 'user'; group: UserGroup }
| { type: 'system'; group: SystemGroup }
| { type: 'ai'; group: AIGroup }
| { type: 'compact'; group: CompactGroup };
export interface SessionConversation {
sessionId: string;
items: ChatItem[]; // Flat chronological list
totalUserGroups: number;
totalSystemGroups: number;
totalAIGroups: number;
totalCompactGroups: number;
}
```
## Pipeline Overview
```
Raw JSONL messages
→ MessageClassifier (classify into user/system/ai/hardNoise)
→ ChunkBuilder (buffer AI messages, flush on user/system boundary)
→ ChunkFactory (build EnhancedAIChunk with SemanticSteps)
→ groupTransformer (chunks → flat ChatItem[] conversation)
→ aiGroupEnhancer (AIGroup → EnhancedAIGroup with displayItems, linkedTools, lastOutput)
→ React components render
```
Primary source files:
- `src/main/services/parsing/MessageClassifier.ts`
- `src/main/services/analysis/ChunkBuilder.ts`
- `src/main/services/analysis/ChunkFactory.ts`
- `src/renderer/utils/groupTransformer.ts`
- `src/renderer/utils/aiGroupEnhancer.ts`
- `src/renderer/utils/displayItemBuilder.ts`
- `src/renderer/types/groups.ts`
- `src/main/types/chunks.ts`
## Data Models
### UserGroup
```typescript
// src/renderer/types/groups.ts
interface UserGroup {
id: string;
message: ParsedMessage;
timestamp: Date;
content: UserGroupContent;
index: number; // Ordering index within session
}
interface UserGroupContent {
text?: string; // Plain text (commands removed)
rawText?: string; // Original text
commands: CommandInfo[]; // Extracted /commands
images: ImageData[]; // Attached images
fileReferences: FileReference[]; // @file.ts mentions
}
```
Renders right-aligned blue bubble. Contains markdown text, slash commands, images, and file references.
### AIGroup
```typescript
interface AIGroup {
id: string;
turnIndex: number; // 0-based (for turn navigation)
startTime: Date;
endTime: Date;
durationMs: number;
steps: SemanticStep[]; // Core semantic steps
tokens: AIGroupTokens;
summary: AIGroupSummary; // For collapsed view
status: AIGroupStatus; // 'complete' | 'interrupted' | 'error' | 'in_progress'
processes: Process[]; // Subagent processes
chunkId: string;
metrics: SessionMetrics;
responses: ParsedMessage[]; // All assistant + internal messages
isOngoing?: boolean; // True for last group in ongoing session
}
```
### EnhancedAIGroup
The renderer enhances `AIGroup` before rendering:
```typescript
interface EnhancedAIGroup extends AIGroup {
lastOutput: AIGroupLastOutput | null; // Always-visible output
displayItems: AIGroupDisplayItem[]; // Flattened chronological items
linkedTools: Map<string, LinkedToolItem>; // Tool call/result pairs
itemsSummary: string; // "2 thinking, 4 tool calls, 3 subagents"
mainModel: ModelInfo | null;
subagentModels: ModelInfo[];
claudeMdStats: ClaudeMdStats | null;
}
```
Enhancement happens in `src/renderer/utils/aiGroupEnhancer.ts`:
1. `findLastOutput` — extracts the final visible output (text, tool result, interruption, plan exit, ongoing)
2. `linkToolCallsToResults` — pairs tool calls with their results into `LinkedToolItem`
3. `buildDisplayItems` — flattens steps into chronological `AIGroupDisplayItem[]`
4. `buildSummary` — generates human-readable summary string
5. `extractMainModel` / `extractSubagentModels` — extracts model info
### AIGroupDisplayItem
```typescript
type AIGroupDisplayItem =
| { type: 'thinking'; content: string; timestamp: Date; tokenCount?: number }
| { type: 'tool'; tool: LinkedToolItem }
| { type: 'subagent'; subagent: Process }
| { type: 'output'; content: string; timestamp: Date; tokenCount?: number }
| { type: 'slash'; slash: SlashItem }
| { type: 'teammate_message'; teammateMessage: TeammateMessage };
```
Display items are sorted chronologically in `src/renderer/utils/displayItemBuilder.ts`.
### LinkedToolItem
```typescript
interface LinkedToolItem {
id: string;
name: string;
input: Record<string, unknown>;
callTokens?: number;
result?: {
content: string | unknown[];
isError: boolean;
toolUseResult?: ToolUseResultData;
tokenCount?: number;
};
inputPreview: string; // First 100 chars
outputPreview?: string; // First 200 chars
startTime: Date;
endTime?: Date;
durationMs?: number;
isOrphaned: boolean; // No result received
sourceModel?: string;
skillInstructions?: string; // For Skill tool calls
skillInstructionsTokenCount?: number;
}
```
### AIGroupLastOutput
Always-visible output below the AI group header:
```typescript
interface AIGroupLastOutput {
type: 'text' | 'tool_result' | 'interruption' | 'ongoing' | 'plan_exit';
text?: string;
toolName?: string;
toolResult?: string;
isError?: boolean;
interruptionMessage?: string;
planContent?: string;
planPreamble?: string;
timestamp: Date;
}
```
### SystemGroup
```typescript
interface SystemGroup {
id: string;
message: ParsedMessage;
timestamp: Date;
commandOutput: string;
commandName?: string;
}
```
Renders left-aligned with neutral gray styling. Monospace pre with ANSI escape codes cleaned.
### CompactGroup
```typescript
interface CompactGroup {
id: string;
timestamp: Date;
message: ParsedMessage;
tokenDelta?: CompactionTokenDelta;
startingPhaseNumber?: number;
}
```
Visual boundary for context compaction events.
## Backend: Chunk Building
### Message Classification
`src/main/services/parsing/MessageClassifier.Use this agent when CLAUDE.md files or .claude/rules/ files may have drifted from the actual codebase state. This includes after significant refactors, feature additions, file renames, directory restructuring, or when you suspect documentation no longer matches reality. Use proactively after any large code change.\\n\\nExamples:\\n\\n- Example 1:\\n user: \"Refactor the services directory to split analysis into separate modules\"\\n assistant: \"I've completed the refactoring of the services directory. Let me now launch the claude-md-auditor agent to ensure all CLAUDE.md files reflect these structural changes.\"\\n <commentary>\\n Since a significant refactor was performed that likely changed file paths, exports, and directory structure documented in CLAUDE.md files, use the Task tool to launch the claude-md-auditor agent.\\n </commentary>\\n\\n- Example 2:\\n user: \"Add a new notifications feature with hooks, components, and a store slice\"\\n assistant: \"The notifications feature is now implemented. I'll use the claude-md-auditor agent to update the documentation to include the new files and patterns.\"\\n <commentary>\\n A new feature was added with multiple new files across components, hooks, and store slices. The CLAUDE.md files likely need updating to document these additions. Use the Task tool to launch the claude-md-auditor agent.\\n </commentary>\\n\\n- Example 3:\\n user: \"Rename isRealUserMessage to isParsedRealUserMessage across the codebase\"\\n assistant: \"The rename is complete across all source and test files. Now I'll launch the claude-md-auditor agent to update any documentation references to the old function name.\"\\n <commentary>\\n A function was renamed which is likely documented in CLAUDE.md type guard tables and conventions sections. Use the Task tool to launch the claude-md-auditor agent to fix stale references.\\n </commentary>\\n\\n- Example 4:\\n user: \"Can you audit the CLAUDE.md files to make sure they're up to date?\"\\n assistant: \"I'll launch the claude-md-auditor agent to systematically verify all documentation against the actual codebase.\"\\n <commentary>\\n The user explicitly requested a documentation audit. Use the Task tool to launch the claude-md-auditor agent.\\n </commentary>
Use this agent when the user wants to fix all code quality issues in the project, including linting, formatting, and unused code detection. This agent runs `pnpm fix` followed by `pnpm quality` in a loop, delegating each iteration to a subagent, until all issues are resolved.\\n\\nExamples:\\n\\n- User: \"Fix all the quality issues\"\\n Assistant: \"I'll launch the quality-fixer agent to iteratively fix all linting, formatting, and quality issues.\"\\n (Uses Task tool to launch quality-fixer agent)\\n\\n- User: \"Run quality checks and fix everything\"\\n Assistant: \"Let me use the quality-fixer agent to handle that.\"\\n (Uses Task tool to launch quality-fixer agent)\\n\\n- User: \"Make sure the code passes all checks\"\\n Assistant: \"I'll use the quality-fixer agent to ensure all quality checks pass.\"\\n (Uses Task tool to launch quality-fixer agent)\\n\\n- After completing a large refactor or feature implementation:\\n Assistant: \"Now that the changes are complete, let me launch the quality-fixer agent to ensure everything passes quality checks.\"\\n (Uses Task tool to launch quality-fixer agent)
Design system and visual language — theming, CSS variables, Tailwind config, component styling patterns, icon usage, animations, and z-index layers. Use when creating or modifying UI components, working with the dark/light theme, or debugging visual issues.
Explains what "Visible Context" is — the 6 trackable token categories, what falls outside tracking, how it's displayed, and why it matters. Use when someone asks about visible context, token attribution, or context window usage.
Markdown search logic — how in-session and cross-session search works. Use when working on SearchBar, search highlighting, searchHighlightUtils, markdownTextSearch, or SessionSearcher.
Navigation and scroll orchestration — tab navigation, error highlights, search scrolling, auto-scroll coordination, and common bug patterns. Use when working on useTabNavigationController, scroll restore, or navigation requests.