Skip to content

🐛 Bug: useAgent: agent.subscribe() throws "Cannot read properties of undefined (reading 'subscribers')" on mount #5000

Closed

Description

@codeonym

♻️ Reproduction Steps

import { useAgent } from "@copilotkit/react-core/v2";
import { useEffect } from "react";

function useAgentSubscriber(agentId: string) {
  const { agent } = useAgent({ agentId });

  useEffect(() => {

    // Throws on first render:
    // TypeError: Cannot read properties of undefined (reading 'subscribers')
    const sub = agent.subscribe({
      onRunFinalized: (params) => console.log(params),
    });

    return () => sub.unsubscribe();
  }, [agent]);
}

✅ Expected Behavior

agent.subscribe() should be safe to call as soon as useAgent() returns the agent. If initialization is async, the hook should expose an isReady flag so consumers can guard accordingly:

const { agent, isReady } = useAgent({ agentId });

useEffect(() => {
  if (!isReady) return;

  const sub = agent.subscribe({
    onRunFinalized: (params) => console.log(params),
  });

  return () => sub.unsubscribe();
}, [agent, isReady]);

❌ Actual Behavior

Calling agent.subscribe() inside a useEffect immediately after useAgent() returns throws at runtime:

TypeError: Cannot read properties of undefined (reading 'subscribers')
    at AbstractAgent.subscribe

The hook always returns an AbstractAgent instance — never null — so there is no signal to know when the agent is fully initialized and safe to call subscribe() on.

Screenshots

No response

𝌚 CopilotKit Version

├── @copilotkit/[email protected]
├── @copilotkit/[email protected]
├── @copilotkit/[email protected]

📄 Logs (Optional)

Activity

  1. added
    bug
    on May 24, 2026
  2. codeonym commented on May 24, 2026

    @codeonym
    Author

    The current type declaration says agent is always an AbstractAgent:

    declare function useAgent({
      agentId,
      updates,
      throttleMs
    }?: UseAgentProps): {
      agent: AbstractAgent;
    };
  3. copilotkit-support-bot commented on May 24, 2026

    @copilotkit-support-bot

    To address the issue where agent.subscribe() throws a TypeError on mount, I have analyzed the codebase and identified the likely cause. The useAgent hook in @copilotkit/react-core returns a ProxiedCopilotRuntimeAgent when the CopilotKit runtime is still connecting.

    Details

    Analysis

    The useAgent hook in @copilotkit/react-core returns a ProxiedCopilotRuntimeAgent when the CopilotKit runtime is still connecting. While this agent instance is fully valid and designed to stand in for the real agent, the error Cannot read properties of undefined (reading 'subscribers') at AbstractAgent.subscribe suggests that the underlying base class from @ag-ui/client may not have initialized its internal subscriber registry at the time of the first call.

    Even though useAgent itself performs an internal subscription, it does so within its own useEffect, which runs after the component has mounted. In your reproduction, calling agent.subscribe() in a separate useEffect may hit a race condition if the agent instance returned from useMemo is not yet fully "prepared" by the base class logic, or if the ProxiedCopilotRuntimeAgent is in a pending state awaiting runtime sync.

    Solution

    Currently, the useAgent hook does not expose an isReady flag directly. However, you can safely guard against this by checking the runtimeConnectionStatus from useCopilotKit, which is what useAgent uses internally to decide when to transition from a provisional (proxied) agent to the real agent.

    To fix the crash and safely subscribe, you should:

    1. Verify the runtime is connected before subscribing.
    2. Use the copilotkit.runtimeConnectionStatus as a signal for readiness.
    import { useAgent, useCopilotKit } from "@copilotkit/react-core/v2";
    import { useEffect } from "react";
    import { CopilotKitCoreRuntimeConnectionStatus } from "@copilotkit/core";
    
    function useAgentSubscriber(agentId: string) {
      const { agent } = useAgent({ agentId });
      const { copilotkit } = useCopilotKit();
    
      useEffect(() => {
        // Guard: Only subscribe when the runtime is fully connected
        // This ensures the agent is fully initialized and synced.
        if (!agent || copilotkit.runtimeConnectionStatus !== CopilotKitCoreRuntimeConnectionStatus.Connected) {
          return;
        }
    
        const sub = agent.subscribe({
          onRunFinalized: (params) => console.log(params),
        });
    
        return () => sub.unsubscribe();
      }, [agent, copilotkit.runtimeConnectionStatus]); // Re-run when status changes to 'Connected'
    }

    Why this happens

    The useAgent hook returns a "Provisional" agent while copilotkit.runtimeConnectionStatus is Connecting or Disconnected. While these instances are meant to be stable, they are technically placeholders until the /info endpoint of your runtime returns the actual agent configuration. Subscribing to them too early can lead to inconsistencies if the base class expects certain fields (like subscribers) to be lazily initialized or populated during a sync that hasn't finished.

    Documentation & References

    Confidence Assessment: High. The provided workaround addresses the "pending" state of the agent which is the root of the initialization race condition. Note that a future update to @ag-ui/client or the useAgent hook to include an isReady flag would be the ideal long-term fix.


    Was this helpful?

    If this solution worked for you, please click on the appropriate option below to help us improve:

    ✅ This was helpful | ❌ Need more help

  4. self-assigned this
    on Jun 12, 2026
  5. added a commit that references this issue on Jul 15, 2026
    690b75f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions