Skip to content

Real-time context window tracking via Claude Code hooks #90

@sagarsrc

Description

@sagarsrc

Summary

Capture real-time context window usage data from Claude Code via hooks and display it in supertrace with a visual progress bar per session.

Problem

Currently, supertrace captures token usage from Claude Code transcripts, but the Claude API doesn't return context window percentage. This data IS available internally in Claude Code and exposed via hooks/statusline.

Proposed Solution

Use Claude Code hooks to capture and send context window data to supertrace backend.

Hook JSON Data Available

{
  "hook_event_name": "Status",
  "session_id": "abc123...",
  "transcript_path": "/path/to/transcript.jsonl",
  "model": {
    "id": "claude-opus-4-5-20251101",
    "display_name": "Opus 4.5"
  },
  "context_window": {
    "used_percentage": 42.5,
    "remaining_percentage": 57.5,
    "context_window_size": 200000,
    "total_input_tokens": 15234,
    "total_output_tokens": 4521,
    "current_usage": {
      "input_tokens": 8500,
      "output_tokens": 1200,
      "cache_creation_input_tokens": 5000,
      "cache_read_input_tokens": 2000
    }
  },
  "cost": {
    "total_cost_usd": 0.01234,
    "total_duration_ms": 45000
  }
}

Implementation

Backend:

  • New endpoint POST /api/sessions/{session_id}/context to receive context data
  • Store context window snapshots in database (new table or extend sessions)
  • Match incoming data to existing sessions via session_id or transcript_path
  • Endpoint GET /api/sessions/{session_id}/context to retrieve latest context data

Hook Script:

  • Create hook script that POSTs JSON to supertrace backend
  • Configure to run on PreToolUse hook event
  • Handle connection errors gracefully (don't block Claude Code)

Frontend:

  • Progress bar component showing context window usage (battery-style)
  • Color-coded: green (<50%), yellow (50-75%), red (>75%)
  • Display in session header/sidebar
  • Show model name from hook data
  • Real-time updates when new data arrives

Example Progress Bar:

[████░░░░] 45% context used • Opus 4.5

Benefits

  • Real-time visibility into context window usage per session
  • Proactive warning before context exhaustion
  • Better session monitoring and debugging
  • Model info display per session

Additional Context

  • Hook data is the same JSON that Claude Code statusline receives
  • Session matching can use session_id or transcript_path (both available)
  • Only need periodic updates (PreToolUse), not every event

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

In Review

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions