Repository navigation
feat: add onTrace handler for runtime and UI error/event tracking - #2025
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
1 Skipped Deployment
|
WalkthroughA new tracing feature is introduced across multiple CopilotKit packages, enabling structured event and error tracking via an Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CopilotKit (React)
participant CopilotContext
participant useCopilotRuntimeClient
participant CopilotRuntime
participant onTrace Handler
User->>CopilotKit (React): Passes onTrace callback
CopilotKit (React)->>CopilotContext: Provides onTrace in context
CopilotContext->>useCopilotRuntimeClient: Supplies onTrace
useCopilotRuntimeClient->>CopilotRuntime: Passes onTrace to runtime
CopilotRuntime-->>onTrace Handler: Emits trace events (e.g., error, request, agent_state)
onTrace Handler-->>CopilotRuntime: Handles trace event (async or sync)
Suggested reviewers
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
onTrace handler for runtime and UI error/event tracking
…ty - Add CopilotTraceEvent interfaces with rich debugging context, implement runtime-side tracing with publicApiKey gating, add UI-side error tracing, include comprehensive test coverage, and fix tsup build config to exclude test files
5545b14 to
7e117d0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
docs/content/docs/reference/components/CopilotKit.mdx (1)
108-125: Fix minor grammar issue and LGTM on documentation structure.The documentation for the
onTraceproperty is comprehensive and well-structured. However, there's a minor grammar issue that should be addressed.- Requires publicApiKey: Tracing only works when publicApiKey is provided. + Requires publicApiKey: Tracing only works when a publicApiKey is provided.The rest of the documentation is excellent - clear parameter description, proper usage example, and appropriate premium feature callouts.
CopilotKit/packages/react-core/src/components/copilot-provider/__tests__/copilotkit-trace.test.tsx (3)
17-34: Remove misleading comments and approve test logic.The test logic for validating trace event structure is sound, but the "RED: Will fail" comment should be removed as it's misleading.
- it("should validate trace event structure", () => { - // RED: Will fail - validating event structure + it("should validate trace event structure", () => { const mockEvent: CopilotTraceEvent = {The actual test validates the proper structure of trace events with required fields and expected values.
36-51: Remove misleading comment and LGTM on event type validation.Good test coverage of all supported trace event types. The comment should be cleaned up.
- it("should validate trace event types", () => { - // RED: Will fail - ensuring all event types are valid + it("should validate trace event types", () => { const validTypes: CopilotTraceEvent["type"][] = [The test properly validates all expected event types including "error", "request", "agent_state", etc.
55-72: Clean up comments and approve handler testing.The tests for both synchronous and asynchronous trace handlers are well-structured. Remove the misleading "RED: Will fail" comments.
Apply this cleanup:
- it("should accept trace handler with proper signature", () => { - // RED: Will fail - testing handler function signature + it("should accept trace handler with proper signature", () => { const handler: CopilotTraceHandler = (traceEvent: CopilotTraceEvent) => { console.log("Trace:", traceEvent.type); }; expect(typeof handler).toBe("function"); }); it("should handle async trace handlers", async () => { - // RED: Will fail - testing async handler support const asyncHandler: CopilotTraceHandler = async (traceEvent: CopilotTraceEvent) => {Good coverage of both sync and async handler patterns.
CopilotKit/packages/shared/src/types/trace.ts (1)
15-32: Consider more specific types for request/response fieldsThe
bodyfields in request and response are typed asany, and headers useRecord<string, string>which may not handle multi-value headers correctly.Consider these type improvements:
request?: { operation: string; method?: string; url?: string; path?: string; - headers?: Record<string, string>; - body?: any; + headers?: Record<string, string | string[]>; + body?: unknown; startTime: number; }; response?: { status?: number; statusText?: string; - headers?: Record<string, string>; - body?: any; + headers?: Record<string, string | string[]>; + body?: unknown; endTime: number; latency: number; };This provides better type safety while maintaining flexibility. The
unknowntype is safer thananyas it requires explicit type checking before use.CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (1)
1455-1487: Consider making trace method fire-and-forgetThe
tracemethod is marked asasyncand returnsPromise<void>, but all its callers useawait. Since trace errors are caught internally and shouldn't block the main flow, consider making it fire-and-forget.- private async trace( + private trace( type: CopilotTraceEvent["type"], context: CopilotRequestContext, error?: any, publicApiKey?: string, - ): Promise<void> { + ): void { if (!this.onTrace) return; if (!publicApiKey) { if (!this.hasWarnedAboutTracing) { console.warn( "CopilotKit: onTrace handler provided but requires publicApiKey for tracing to work. " + "This is a CopilotKit Cloud feature. See: https://docs.copilotkit.ai/cloud", ); this.hasWarnedAboutTracing = true; } return; } try { const traceEvent: CopilotTraceEvent = { type, timestamp: Date.now(), context, ...(error && { error }), }; - await this.onTrace(traceEvent); + // Fire and forget - don't block on trace completion + Promise.resolve(this.onTrace(traceEvent)).catch((traceError) => { + console.error("Error in onTrace handler:", traceError); + }); - } catch (traceError) { - // Don't let trace errors break the main flow - console.error("Error in onTrace handler:", traceError); } }Then remove all
awaitcalls tothis.trace()throughout the file.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
CopilotKit/.changeset/late-eyes-drive.md(1 hunks)CopilotKit/packages/react-core/src/components/copilot-provider/__tests__/copilotkit-trace.test.tsx(1 hunks)CopilotKit/packages/react-core/src/components/copilot-provider/copilotkit-props.tsx(2 hunks)CopilotKit/packages/react-core/src/components/copilot-provider/copilotkit.tsx(2 hunks)CopilotKit/packages/react-core/src/context/copilot-context.tsx(3 hunks)CopilotKit/packages/react-core/src/hooks/use-copilot-runtime-client.ts(4 hunks)CopilotKit/packages/react-core/tsup.config.ts(1 hunks)CopilotKit/packages/runtime/src/lib/runtime/__tests__/copilot-runtime-trace.test.ts(1 hunks)CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts(11 hunks)CopilotKit/packages/shared/src/types/index.ts(1 hunks)CopilotKit/packages/shared/src/types/trace.ts(1 hunks)docs/content/docs/reference/classes/CopilotRuntime.mdx(1 hunks)docs/content/docs/reference/components/CopilotKit.mdx(1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/content/docs/reference/components/CopilotKit.mdx
[uncategorized] ~111-~111: You might be missing the article “a” here.
Context: ...s publicApiKey: Tracing only works when publicApiKey is provided. This is a premium Copilo...
(AI_EN_LECTOR_MISSING_DETERMINER_A)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Test (20.x)
- GitHub Check: Test (18.x)
🔇 Additional comments (21)
CopilotKit/packages/shared/src/types/index.ts (1)
5-5: LGTM - Clean export additionThe export statement correctly follows the existing pattern and enables other packages to access the new trace types.
CopilotKit/.changeset/late-eyes-drive.md (1)
1-8: Well-documented changesetThe changeset properly documents the new tracing feature across all affected packages with appropriate patch-level version bumps and a clear description.
CopilotKit/packages/react-core/src/context/copilot-context.tsx (3)
1-1: Correct import additionThe
CopilotTraceHandlerimport is properly added to support the new tracing functionality.
222-225: Well-documented interface extensionThe
onTraceproperty is properly typed as optional and includes clear documentation describing its purpose for debugging and observability.
296-296: Consistent context initializationThe
onTraceproperty is correctly initialized asundefinedin the empty context, maintaining consistency with other optional properties.CopilotKit/packages/react-core/tsup.config.ts (1)
4-9: Improved build configuration with negative globsThe change to use negative glob patterns in the entry array is a clean approach to exclude test files from production builds. The patterns comprehensively cover standard test file conventions (.test., tests directories, and .spec.).
CopilotKit/packages/react-core/src/components/copilot-provider/copilotkit.tsx (2)
275-275: Correct prop propagation to runtime clientThe
onTraceprop is properly passed touseCopilotRuntimeClient, enabling UI-side error and event tracing.
444-444: Proper context value inclusionThe
onTraceprop is correctly included in the context provider value, making it accessible to downstream components that consume the context.docs/content/docs/reference/classes/CopilotRuntime.mdx (1)
141-157: LGTM! Well-structured and consistent documentation.The documentation for the
onTraceconstructor parameter is comprehensive and maintains consistency with the CopilotKit component documentation. The usage example clearly demonstrates how to integrate tracing at the runtime level, and the premium feature requirements are properly documented.CopilotKit/packages/react-core/src/components/copilot-provider/copilotkit-props.tsx (2)
4-4: LGTM! Proper import for tracing functionality.The import statement correctly brings in the
CopilotTraceHandlertype from the shared package, enabling proper type safety for the new tracing feature.
119-137: LGTM! Well-documented and properly typed interface extension.The
onTraceproperty addition is excellent:
- Comprehensive JSDoc documentation with clear requirements
- Proper TypeScript typing with
CopilotTraceHandler- Optional property maintains backwards compatibility
- Includes helpful usage example
- Consistent with other property documentation patterns
CopilotKit/packages/react-core/src/components/copilot-provider/__tests__/copilotkit-trace.test.tsx (1)
12-15: Clarify the purpose of "RED: Will fail" comments.The comment "RED: Will fail - testing type compatibility" is unclear. Are these tests expected to fail, or are they placeholder comments that should be removed?
If these are actual failing tests, they should be fixed. If they're just placeholder comments, they should be cleaned up for production code.
- it("should accept CopilotTraceHandler type", () => { - // RED: Will fail - testing type compatibility + it("should accept CopilotTraceHandler type", () => { const handler: CopilotTraceHandler = mockTrace; expect(handler).toBeDefined(); });CopilotKit/packages/runtime/src/lib/runtime/__tests__/copilot-runtime-trace.test.ts (4)
1-21: LGTM! Well-structured imports and test setup.The test imports all necessary types from the shared package and sets up a proper test structure with mock handlers. Good organization with clear describe blocks.
22-66: Excellent comprehensive type validation tests.The tests thoroughly validate:
- CopilotTraceEvent structure with all required fields
- All supported event types (error, request, response, agent_state, action, message, performance)
- Proper error handling with CopilotKitError integration
This provides robust type safety validation for the tracing feature.
83-95: LGTM! Proper testing of publicApiKey gating logic.The test correctly validates the gating mechanism that ensures tracing only works when both
onTracehandler andpublicApiKeyare present. This is crucial for the premium feature requirement.expect(shouldTrace(mockTraceHandler, "ck_pub_test")).toBe(true); expect(shouldTrace(mockTraceHandler, undefined)).toBe(false); expect(shouldTrace(undefined, "ck_pub_test")).toBe(false);Covers all the necessary boolean logic scenarios.
97-164: Outstanding comprehensive context validation test.This test validates the complete trace context structure with all possible fields:
- Request/response metadata (method, URL, headers, timing)
- Agent information (name, node, state)
- Message details and counts
- Technical environment data
- Performance metrics
- Custom metadata
This thorough validation ensures the trace events contain all the rich debugging context promised in the PR objectives.
CopilotKit/packages/react-core/src/hooks/use-copilot-runtime-client.ts (2)
104-105: Good error tracing integrationThe tracing is properly integrated into all error handling paths without blocking the main error flow. The fire-and-forget pattern for trace calls is appropriate here.
Also applies to: 113-114, 131-132
33-61: I’ll locate the helper and its surrounding context to see how request timing is handled.#!/bin/bash # Find the hook file and show traceUIError with context file=$(fd use-copilot-runtime-client.ts) echo "Inspecting: $file" rg -n "traceUIError" -C15 "$file"CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (3)
281-298: Well-implemented trace handler initializationThe documentation is comprehensive with a clear example, and the warning flag pattern prevents console spam. Good implementation.
Also applies to: 311-312, 347-347
729-737: Good error standardization patternExcellent pattern of converting all errors to structured
CopilotKitErrorinstances before tracing. This ensures consistent error format in trace events and improves debuggability.Also applies to: 1254-1260
1406-1453: Comprehensive streaming error handlingExcellent implementation that covers various network error scenarios with clear, user-friendly messages. The error classification helps with proper handling downstream.
| export interface CopilotTraceEvent { | ||
| type: "error" | "request" | "response" | "agent_state" | "action" | "message" | "performance"; | ||
| timestamp: number; | ||
| context: CopilotRequestContext; | ||
| error?: any; // Present when type is 'error' | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Improve error field typing and enforce type constraints
The error field is typed as any, which bypasses TypeScript's type safety. Additionally, the comment indicates it should only be present when type is 'error', but this constraint isn't enforced by the type system.
Consider using a discriminated union to enforce the relationship between type and error:
-export interface CopilotTraceEvent {
- type: "error" | "request" | "response" | "agent_state" | "action" | "message" | "performance";
- timestamp: number;
- context: CopilotRequestContext;
- error?: any; // Present when type is 'error'
-}
+export type CopilotTraceEvent =
+ | {
+ type: "error";
+ timestamp: number;
+ context: CopilotRequestContext;
+ error: Error | CopilotKitError | unknown;
+ }
+ | {
+ type: "request" | "response" | "agent_state" | "action" | "message" | "performance";
+ timestamp: number;
+ context: CopilotRequestContext;
+ };This ensures that error is only present when type is 'error' and provides better type safety.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export interface CopilotTraceEvent { | |
| type: "error" | "request" | "response" | "agent_state" | "action" | "message" | "performance"; | |
| timestamp: number; | |
| context: CopilotRequestContext; | |
| error?: any; // Present when type is 'error' | |
| } | |
| export type CopilotTraceEvent = | |
| | { | |
| type: "error"; | |
| timestamp: number; | |
| context: CopilotRequestContext; | |
| error: Error | CopilotKitError | unknown; | |
| } | |
| | { | |
| type: "request" | "response" | "agent_state" | "action" | "message" | "performance"; | |
| timestamp: number; | |
| context: CopilotRequestContext; | |
| }; |
🤖 Prompt for AI Agents
In CopilotKit/packages/shared/src/types/trace.ts lines 1 to 6, the
CopilotTraceEvent interface uses an 'any' type for the error field and does not
enforce that error is only present when type is 'error'. Refactor this interface
into a discriminated union where each possible 'type' value corresponds to a
specific interface variant, ensuring that the error field is only included and
typed appropriately in the variant where type is 'error'. This will enforce type
safety and the conditional presence of the error field.
🦋 Changeset detectedLatest commit: 8bf5a8f The changes in this PR will be included in the next version bump. This PR includes changesets to release 7 packages
Click here if you're a maintainer who wants to add another changeset to this PR |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
CopilotKit/.changeset/tender-geese-look.md (1)
7-8: Refine changeset summary formatting.
The first bullet is very long and includes an internal hyphen that may be misinterpreted by the parser. Consider using a concise one-line summary (e.g.,feat: add onTrace handler for runtime and UI tracing) and moving detailed descriptions into sub-bullets or a separate description block.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
CopilotKit/.changeset/tender-geese-look.md(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: Pre-release
- GitHub Check: Test (18.x)
- GitHub Check: Test (20.x)
🔇 Additional comments (1)
CopilotKit/.changeset/tender-geese-look.md (1)
1-5: Frontmatter syntax is valid.
The changeset correctly declares patch bumps for@copilotkit/react-core,@copilotkit/runtime, and@copilotkit/shared.
|
Preview environments destroyed for this pull request. |
Test ResultsStatus: ✅ Passed (View Run) Commit: 9ab0272 Duration: 245.0s Total Tests: 20 Pass Rate: 100.0% Failed Tests: 0 🔍 Detailed Resultscoagents-research-canvasCoAgents Research Canvas (UI) - Local Depenencies
coagents-qa-nativeCoAgents QA Native (UI) - Local
coagents-qa-textCoAgents QA Text (UI) - Local
coagents-routingCoAgents Routing (UI) - Local
next-openaiNext OpenAI - Self Hosted
|
Summary by CodeRabbit
New Features
onTrace) for enhanced debugging and observability in both the CopilotKit UI and runtime. This enables capturing structured trace events for errors, requests, agent states, and other key events, available as a premium feature with CopilotKit Cloud.Documentation
onTraceproperty and provide usage examples for both the CopilotKit component and CopilotRuntime class, including the new method for tracing GraphQL errors.Tests
Chores