Commit Graph

171 Commits

Author SHA1 Message Date
Markus Ecker 762370a4e5 refactor: remove per-thread agent cloning, restore single registry agent per id
Reverts the cloning design from #3525 (useAgent per-thread clones, getThreadClone,
globalThreadCloneMap, cloneForThread) and #3630 (clone routing in activity renderers),
plus the inspector machinery that existed only to handle clones (onAgentRunStarted
subscriber + run-handler emissions from #3869, the connect-time emission from #3872,
and the agentRunThreadId map that read from it).

State-manager isClone composite-key path and SuggestionEngine consumerAgent param —
both added in #3525 to keep clones visible to bookkeeping — are gone too.

Restores agent.threadId = resolvedThreadId in CopilotChat (pre-#3525 behavior) and
swaps the inspector's agentRunThreadId map for a direct agent.threadId read.

Removes the DemoButtonAgent and /a2ui-demo page from the demo (added by #3630 as a
clone-fix repro).

Re-opens the original issue #2957 (CPK-7155): two CopilotChat instances with the same
agentId and different threadIds will share message state again. The follow-up is a
public registerProxiedAgent API so callers can opt into multiple frontend agents
proxying to the same runtime agent, without implicit per-thread cloning.
2026-05-04 13:27:04 +02:00
github-actions[bot] 56524a7282 style: auto-fix formatting 2026-05-01 01:08:19 +00:00
Martha Schumann 0721414fbb Merge remote-tracking branch 'origin/main' into feat/CPK-7193-inspector-threads-clean
# Conflicts:
#	examples/integrations/langgraph-python-threads/apps/app/package.json
#	examples/integrations/langgraph-python-threads/apps/bff/package.json
#	examples/integrations/langgraph-python-threads/package-lock.json
#	pnpm-lock.yaml
2026-04-30 18:01:51 -07:00
Martha Schumann cf51841d18 test(core): cover onAgentsChanged auto-unregister + seed previousAgentIds from constructor
Pins three integration cases for the thread-store auto-unregister branch
in CopilotKitCore's internal onAgentsChanged subscriber:

1. agent removed from agents → store IS unregistered; subscriber receives
   the previous store via prevStore.
2. FIRST onAgentsChanged({ agents: {} }) on a published-style core where
   the store was registered before any agents arrived → store SURVIVES.
   Reproduces the race that the "previously had" guard exists to
   prevent.
3. add → register → remove cycle → store IS unregistered. Complements (2)
   by exercising the same code path's positive branch.

Test (1) surfaced a real bug in the seed: agentRegistry.initialize does
NOT emit onAgentsChanged, so the constructor's internal subscriber never
saw the agents__unsafe_dev_only set, and `previousAgentIds` stayed empty.
A later removeAgent__unsafe_dev_only call would then be guarded into a
no-op because the agentId looked "new". Fixed by seeding
`previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only))` right
before wiring the subscriber.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 12:52:02 -07:00
Martha Schumann bd9fe0169a fix(core): guard thread-store auto-unregister against initial empty agents
CopilotKitCore subscribes to onAgentsChanged and unregisters thread
stores for any agentId not in the new agents map. For published cores,
core.agents is asynchronously populated, so the FIRST
onAgentsChanged({ agents: {} }) notification fires BEFORE published
agents are merged in. Without a guard, that empty notification rips out
a thread store that a consumer (e.g. useThreads) just registered.

Track previousAgentIds and only unregister an agentId that was present
in the previous snapshot AND missing from the new one. The first
empty-agents notification (where the agentId was never previously
present) becomes a no-op.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 12:44:13 -07:00
Tyler Slaton 52f8030f82 Merge branch 'main' into release/publish/monorepo/v1.56.5 2026-04-30 12:42:10 -07:00
Martha Schumann 7dcaa15063 test(core,runtime): strengthen error-log assertions and stub identity
- thread-store-registry: makeStore now attaches a __testId via
  intersection so callers can distinguish stubs at a glance during
  debugging instead of relying on identity-by-allocation alone.
- thread-store-registry subscriber-isolation test: assert the
  diagnostic content ("Subscriber onThreadStoreRegistered error") and
  Error argument, not just that some error was logged.
- handle-threads identifyUser-throws test: assert
  "Error identifying intelligence user" with an Error argument, since
  the throw originates inside resolveIntelligenceUser which logs and
  returns 500 before subscribeToThreads is reached.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 12:13:43 -07:00
Martha Schumann 9b7c0517b6 fix(core): forward prevStore on unregister and freeze getAll snapshot
R1's notify-ordering fix only made the sync subscriber path safe; async
subscribers still race against the next register(). When notifySubscribers
awaits inside Promise.all, control returns to register() which assigns the
new store to the same agentId before the async handler resumes — at which
point registry.get(agentId) returns the new store, not the unregistered one.

Carry the previous store on the onThreadStoreUnregistered payload so
subscribers tearing down state don't need to consult the registry. Same
treatment for unregister(). Doc the "do not call registry.get(agentId) in
this callback" contract on the subscriber type itself.

Also tighten getAll(): cache the snapshot, freeze it (so the Readonly<>
claim is honest at runtime), and return the same reference between
mutations. Stable identity matters for useSyncExternalStore consumers that
compare snapshots to skip re-renders. Tests updated to assert prevStore
delivery, frozen-snapshot mutation throws, and reference stability across
calls. Mock notifySubscribers now uses Promise.all to mirror production
parallel dispatch.
2026-04-30 11:49:13 -07:00
Tyler Slaton 0bdc798854 Merge branch 'main' into tyler/kind-mendeleev-636369 2026-04-30 10:48:28 -07:00
Martha Schumann ed4be71076 test(core): narrow invocationCallOrder access for tsc strict mode
vitest types invocationCallOrder as `number[]`, but TS narrows
indexed access to `number | undefined` under noUncheckedIndexedAccess.
Capture the entries first, assert each is defined, then compare —
keeps the ordering check intact while satisfying tsc.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 10:25:50 -07:00
Martha Schumann 9fdfe23b39 refactor(core): export ɵMAX_SOCKET_RETRIES for thread-store tests
Tests in @copilotkit/react-core need the WebSocket retry budget so they
can validate teardown semantics without hardcoding the threshold
separately from production. Exposing it under the ɵ-prefixed internal
namespace keeps it out of the public API surface while letting the
test bench import a single source of truth.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 10:20:25 -07:00
Tyler Slaton 7a0e2f532e fix(suggestions): show available:"always" pills on welcome screen with runtimeUrl
Two-part welcome-screen regression for `available: "always"` suggestion configs
when the chat connects to agents via `runtimeUrl` instead of registering them
locally:

1. SuggestionEngine.reloadSuggestions bailed early when the agent wasn't yet
   in the registry. With runtimeUrl, the registry is empty during the initial
   /info fetch, so the very first reload (fired by useConfigureSuggestions on
   mount) skipped every config — static pills never appeared on the welcome
   screen, dynamic pills never started generating.  Now: don't bail, default
   `messageCount` to 0, run static configs anyway. Dynamic configs still need
   a real agent and skip until one arrives.

2. useConfigureSuggestions's global-config path only iterated the current
   agents map, which compounded the problem above — the empty map meant zero
   reloads. Now: also reload for the chat's resolved consumer agent (covers
   the empty-map case), and subscribe to onAgentsChanged for dynamic configs
   only, firing exactly once when the target agent first appears (so dynamic
   pills catch up after the runtime fetch completes, without piling up
   overlapping generations as multiple useConfigureSuggestions hooks mount).

`hasSuggestions` keeps the `!isConnecting && !isRunning` UI gate. `available:
"always"` controls eligibility windows (welcome screen vs. after first
message), not whether to render through connect/replay or through a run —
those still hide and the end-of-run reload regenerates against the new
context.

Tests:
- Engine: added unit coverage for reloadSuggestions when no agent is present.
- React: 4 integration tests covering welcome screen (specific + global
  consumerAgentId) and the run lifecycle (hide during run, reappear after) in
  default and pin-to-send modes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 10:14:45 -07:00
Martha Schumann f5787e0b5d fix(core): tighten ThreadStoreRegistry notify ordering and snapshot isolation
- register() now snapshots and clears the previous slot before queuing the
  unregister notification, then assigns the new store before queuing the
  register notification. The unregister microtask is queued first so
  subscribers tear down stale subscriptions before receiving the
  replacement.
- All notifySubscribers calls now attach .catch handlers so notification
  failures surface via console.error instead of being silently swallowed
  by `void`.
- getAll() returns a shallow copy so callers cannot mutate the registry's
  internal state through the returned reference.
- Test mock now mirrors the real notifySubscribers signature (handler +
  errorMessage) and wraps each subscriber call in try/catch, exercising
  the same error-isolation behaviour as production.
- Replaced the `as unknown as ɵThreadStore` cast with a satisfies-typed
  minimal stub matching the real interface.
- Added tests for ordering (unregister before second register), throwing
  subscriber isolation, and getAll() snapshot isolation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-30 10:06:16 -07:00
Tyler Slaton bd68aeda32 fix(deps): bump ag-ui packages to 0.0.53
Picks up ag-ui-protocol/ag-ui#1578 — `import * as jsonpatch from
"fast-json-patch"` produced an empty namespace under Node native ESM
because fast-json-patch@3.x populates exports via Object.assign, which
the CJS→ESM named-export detector cannot see. Result: every STATE_DELTA
and ACTIVITY_DELTA event threw "applyPatch is not a function", and
LangGraph generative UI streams floods the console with the failure on
each patch.

0.0.53 switches to a default import so the emitted bundle works under
both ESM and CJS consumers. Bumped @ag-ui/core and @ag-ui/encoder in
lockstep since they share the release.
2026-04-29 22:41:28 -07:00
Martha Schumann d55d5495c7 Merge remote-tracking branch 'origin/main' into feat/CPK-7193-inspector-threads-clean
# Conflicts:
#	pnpm-lock.yaml
2026-04-29 13:31:32 -07:00
ranst91 5686889567 chore: release monorepo v1.56.5 2026-04-29 11:57:11 +00:00
BenTaylorDev f19afade44 chore: release monorepo v1.56.4 2026-04-27 15:05:59 -05:00
Mike Ryan f28ef5f916 fix(core): reset replay cursor on thread restore 2026-04-24 11:22:49 -07:00
Mike Ryan 5743fd051d fix(core): align intelligence reconnect catch-up 2026-04-24 11:22:49 -07:00
Mike Ryan 4b430b58a9 fix(core): align intelligence agent realtime connect 2026-04-24 11:22:49 -07:00
Max Korp 47a6c0e7f4 test(core): bootstrap STATE_SNAPSHOT hydrates state on thread resume
Covers the shared-state thread-resume path that was missing coverage:
on resume, the /connect bootstrap plan replays STATE_SNAPSHOT events
captured during the original run, and agent.state (both on the direct
IntelligenceAgent and through the ProxiedCopilotRuntimeAgent bridge)
must reflect the final snapshot so UI reading from agent.state renders
the persisted state.

Both tests pass against the current implementation, ruling out these
layers as the source of the shared-state demo regression.
2026-04-22 15:56:07 -07:00
Tyler Slaton 2596e8d932 chore: release monorepo v1.56.3 (#4138)
## Release monorepo v1.56.3

**Scope:** `monorepo` | **Bump:** `patch`

---

### How this release process works

1. **This PR was created automatically** by the "release / create-pr"
workflow.
   It bumped the `monorepo` packages to `1.56.3`
   and generated AI-enhanced release notes.

2. **CI runs on this PR** — the full test suite (unit tests, lint, type
checks, build)
   must pass before merging. This is the review gate.

3. **Review the release notes** in `release-notes.md` in this PR.
If a Notion draft was created, you can edit the release notes there
before merging.

4. **When this PR is merged**, the `release / publish` workflow
automatically:
   - Builds all packages
   - Publishes the `monorepo` packages to npm at version `1.56.3`
   - Creates git tag `monorepo/v1.56.3`
   - Creates a GitHub Release with the final release notes

### Before merging

- [ ] CI is green (tests, lint, types, build)
- [ ] Version bumps look correct
- [ ] Release notes are accurate (edit in Notion if a draft was created)

---

> **Do not merge until CI is fully green.** The full test suite runs
automatically on this PR.
2026-04-22 13:59:09 -07:00
Martha Schumann 2a9b2d3e60 chore: merge origin/main into feat/CPK-7193-inspector-threads-clean
- hooks.ts: keep both threads/clear and cpk-debug-events in RouteInfo
- use-threads.tsx: keep registerThreadStore effect + adopt main's
  runtimeStatus gating for context dispatch
- use-threads.test.tsx: keep both our register/unregister test and
  main's new runtimeConnectionStatus=Connected gating test
- scripts/hooks/check-binaries.sh: add shell-docs and shell-dojo
  demo-content.json exclusions (main introduced these >1MB files without
  updating the exclusion list)
- lefthook.yml, pnpm-lock.yaml: accept main's version

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 13:04:13 -07:00
Martha Schumann 990c097268 fix(inspector): address post-review bugs and test gaps
- ThreadStoreRegistry.register: delete old store before notifyUnregistered
  so callbacks that call getThreadStore(agentId) see undefined, not the
  new store
- ThreadDetailsComponent: reset _expandedMessages on threadId change
  alongside _expandedToolCalls (prevents stale expanded state across
  thread switches)
- handle-threads.test: assert identifyUser called in getThreadMessages
  intelligence path; add identifyUser-throws 500 test
- use-threads.test: add fetchMoreThreads end-to-end test (calls the
  function, asserts cursor param on second fetch, asserts 3 threads)
- in-memory-runner.test: call clearThreads() in first describe's
  beforeEach for GLOBAL_STORE consistency

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 12:53:07 -07:00
Benjamin Taylor d598a197dd chore(threads): code-review fixups
- Rename sortThreadsByUpdatedAt → sortThreadsByRecency to match the
  lastRunAt-preferring sort introduced in the previous commit.
- useThreads: correct the context-dispatch comment to describe what the
  code actually does (null only when runtimeUrl is absent; transient
  status states leave the previous context in place).
- CopilotChatInput: rewrite the `bottomAnchored` prop doc so the
  layout/positioning distinction is self-evident.
- Add changeset calling out the behavior change to suggestions (now
  hidden while `isRunning`) and summarizing the ENT-314 fixes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 09:42:34 -05:00
Benjamin Taylor bbe23e604e fix(threads): skip /connect for absent threads, stabilize switch UX (ENT-314)
- Skip copilotkit.connectAgent when CopilotChat lacks a caller-supplied
  threadId — a locally-minted UUID has no backend record, so /connect
  would always 404 on the intelligence platform.
- Suppress the welcome screen while a connect is in flight and
  unconditionally when the caller has supplied a threadId
  (hasExplicitThreadId). Prevents the "How can I help you today?"
  flash on thread switch.
- Gate suggestions on !isConnecting && !isRunning to avoid painting
  them against a mid-replay message tree.
- Defer the isConnecting release by one animation frame so trailing
  bootstrap renders commit before the flag flips.
- Reserve room for the "Powered by CopilotKit" license badge via a
  new --copilotkit-license-banner-offset CSS var published by the
  banner on mount; chat input consumes it only when bottom-anchored.
- Sort and display threads by lastRunAt (fallback to updatedAt →
  createdAt) so metadata-only actions like archive/rename don't
  reshuffle the list.
- useThreads waits for runtimeConnectionStatus === Connected before
  dispatching the store context, eliminating the speculative /threads
  fetch that fired before /info returned wsUrl.

Threads example polish: restore button + tooltips on
archive/restore/delete, segmented Active/All filter, graceful error
state, skeleton rows on initial load, stable scrollbar gutter,
pre-paint dark-mode class, logo position stable across app/chat
modes, drop dynamic-import drawer wrapper that caused null first
paint, archived-row dimming via child colors instead of opacity.

Tests:
- CopilotChat.absentThreadConnect: connect is skipped without a
  threadId, fires when supplied via prop or config.
- CopilotChatView.connectingGate: isConnecting suppresses welcome;
  hasExplicitThreadId suppresses welcome on empty chat.
- threads (core): lastRunAt sort fallback ordering.
- use-threads: Connecting-state gate defers /threads until Connected.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 09:42:34 -05:00
MikeRyanDev 9cc9ec48b4 chore: release monorepo v1.56.3 2026-04-21 23:48:16 +00:00
github-actions[bot] 58dc1fee62 style: auto-fix formatting 2026-04-21 16:25:11 -07:00
Mike Ryan 219f08ccb9 chore(runtime): clean up connect API and test typing 2026-04-21 16:25:11 -07:00
Mike Ryan 25f6f15418 refactor(runtime): Support durable compaction of threads 2026-04-21 16:25:11 -07:00
Martha Schumann 48331a8cfe fix(inspector): address code review findings
- ThreadStoreRegistry.register() now fires onThreadStoreUnregistered
  before overwriting an existing store so subscribers (web inspector)
  don't stay subscribed to stale stores on replacement; test extended
  to verify both events fire in order
- Wire handleClearThreads to POST /threads/clear route; add RouteInfo
  variant, router pattern, and fetch-handler case so the inspector can
  actually call it
- Add handleGetThreadMessages tool-call mapping test using properly
  typed Message objects (role as const, type as const) — exercises the
  real mapping code path without mocking getThreadMessages

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 15:19:58 -07:00
Martha Schumann 0c287c65f3 chore: merge origin/main
Excludes showcase/shell-docs and showcase/shell-dojo demo-content.json from
the size check in lefthook.yml — these data files were added by main but
weren't in the exemption list, causing the pre-commit hook to reject them.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 15:17:06 -07:00
Maxim 073c0edefd fix: resolve merge conflict with main (pnpm-lock.yaml) 2026-04-17 16:36:21 +02:00
Maxim bd2ccbd0fa refactor(core): extract logAndEmitError helper to deduplicate error handling
Consolidate the repeated console.error + emitError + .catch pattern
into a single private logAndEmitError method on CopilotKitCore. All 4
call sites (setDefaultThrottleMs, subscribeToAgentWithOptions validation,
safeCall reportError, unsupported-keys warning) now go through the helper.
2026-04-17 16:33:09 +02:00
AlemTuzlak 9d00b01ccd chore: release monorepo v1.56.2 2026-04-16 16:04:38 +00:00
AlemTuzlak a6e8a48189 chore: release monorepo v1.56.1 2026-04-16 15:38:24 +00:00
Alem Tuzlak 0bc0405043 fix: exclude tools with available:"disabled" from buildFrontendTools (#3020) (#3793)
## Summary
- `buildFrontendTools` only checked `tool.available !== false` but the
`available` field can also be the string `"disabled"`, which is truthy
- Added `tool.available !== "disabled"` to the filter so disabled tools
are properly excluded
- Added test verifying tools with `available: "disabled"` are filtered
out

## Test plan
- [x] New test: tool with `available: "disabled"` is excluded from
`buildFrontendTools`
- [x] All existing available-filtering tests still pass
- [x] Full core test suite passes (338 tests)
2026-04-16 12:19:44 +02:00
Alem Tuzlak cb4189acdf fix: forward credentials on all agent registration paths (#3839)
Closes #3141

`applyCredentialsToAgents`/`applyCredentialsToAgent` were defined but
never called from `initialize()`, `setAgents__unsafe_dev_only()`, or
`addAgent__unsafe_dev_only()`. Only remote agents received credentials
via constructor. Local agents now receive credentials alongside headers.

Split from #3838.
2026-04-16 11:45:32 +02:00
Maxim b8d6e14138 fix(tests): improve test hygiene — remove type casts, reduce duplication
Core test (core-subscribe-to-agent.test.ts):
- Replace `as any` on RunErrorEvent with proper EventType.RUN_ERROR type
- Consolidate 4 identical lifecycle tests into one `it.each` block
- Extract silenceConsoleError() helper used across 10 error-path tests
- Document the remaining intentional `as any` in guardAll JS-consumer test

Angular test (agent.spec.ts):
- Make MockAgent extend AbstractAgent, removing all 4 `as unknown as AbstractAgent` double casts
- Replace all `any` types with proper AG-UI types (Message, State, AgentSubscriber, etc.)
- Emit helpers now pass correct AgentSubscriberParams instead of empty objects
- Use userMsg() factory for properly typed test data
- Simplify ProxiedCopilotRuntimeAgent assertion with single narrowing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 01:02:36 +02:00
Maxim bb6f02c62a fix(core,react-core): handle onRunErrorEvent in useAgent and document in subscribeToAgentWithOptions
React's useAgent was missing onRunErrorEvent under OnRunStatusChanged,
causing isRunning to stay true after protocol-level RUN_ERROR events
(infinite spinner). Angular already handled this via PR #3749.

Also updates SubscribeToAgentSubscriber JSDoc to accurately document
onRunErrorEvent as the sixth allowed callback with rationale for its
inclusion despite having stopPropagation in its return type, and adds
a core-level test for onRunErrorEvent firing immediately during
throttle windows.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 00:08:25 +02:00
Maxim 96f230c7cc fix: resolve rebase conflicts — active flag, onRunErrorEvent, async tests
- Restore `let active` guard in useAgent subscription effect (removed
  during refactor, causing ReferenceError in batchedForceUpdate)
- Add onRunErrorEvent to SubscribeToAgentSubscriber allowed keys
  (added on main for Angular AgentStore)
- Fix throttle tests to use async act() for onStateChanged assertions
  (batchedForceUpdate uses queueMicrotask, needs await to flush)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 23:15:45 +02:00
Maxim b8f4a8faa0 refactor: replace custom throttle with @tanstack/pacer Throttler
Replace the hand-rolled leading+trailing throttle (scheduleOrFlush,
setTimeout, throttleActive state machine) with TanStack Pacer's
Throttler class. Clean up comments to describe the method generically
rather than only in terms of throttling.

No public API changes — throttleMs / defaultThrottleMs stay as-is.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:14:50 +02:00
Maxim 47b46e456e fix: make guardAll type-safe, remove any casts
Address review feedback: replace Object.entries loop in guardAll
with explicit per-key wrapping so TypeScript can verify all
callback signatures without any casts. Also replace Promise
duck-typing in safeCall with instanceof Promise, and use
Record<string, unknown> instead of any in the unsupported keys check.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:17 +02:00
Maxim 18a9ad6e58 fix: rename subscribeToAgent to subscribeToAgentWithOptions on CopilotKitCore
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:16 +02:00
Maxim 0ae5e4606c fix: warn about unsupported callback keys in both throttled and unthrottled paths
Move the unsupported-key scan from guardAll into a pre-scan that runs
before the throttled/unthrottled branch, so JS consumers passing
unsupported callbacks (e.g. onEvent via `as any`) get a console.warn
regardless of whether throttling is active. Previously, guardAll only
ran on lifecycleOnly in the throttled path, silently dropping
unsupported keys without any diagnostic.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:15 +02:00
Maxim d8b60f5a1c fix: address PR review — error monitoring, Angular Error state, type safety
- Add Error state handling in Angular CopilotkitAgentFactory (parity with React)
- Add emitError to guardAll for dropped callbacks (structured monitoring)
- Add emitError to setDefaultThrottleMs for monitoring parity
- Replace empty .catch(() => {}) with logging pattern on emitError
- Add generic typing to safeCall for call-site parameter safety
- Clarify flushPending comment re: sync-only unsubscribe guard

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:15 +02:00
Maxim 1f74c59eca fix: address review findings — type safety, JSDoc accuracy, and test coverage
- Add `satisfies readonly (keyof AgentSubscriber)[]` to SUBSCRIBE_TO_AGENT_KEYS
  so upstream AG-UI renames are caught at compile time
- Fix SubscribeToAgentSubscriber JSDoc: separate AG-UI event handlers (mutation
  semantics) from per-item callbacks (void return, excluded for surface area),
  note that included lifecycle callbacks also return AgentStateMutation
- Emit invalid throttleMs through emitError so monitoring systems see
  misconfiguration, not just console.error
- Add flushPending comment explaining the re-checked `active` flag between
  onMessagesChanged and onStateChanged dispatch
- Derive SubscribeToAgentFn from CopilotKitCore['subscribeToAgent'] instead
  of manually duplicating the signature (eliminates desync risk)
- Derive StubCore from Pick<CopilotKitCore, ...> in Angular tests
- Add test: async rejection during throttled trailing-edge flush
- Add test: clearing defaultThrottleMs(undefined) makes new subs unthrottled

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:14 +02:00
Maxim 7b94afd862 fix: address code review findings for subscribeToAgent
- Add .catch() to emitError() in reportError to prevent unhandled
  promise rejections if the error reporting infrastructure itself fails
- Add console.warn in guardAll when unsupported callback keys are
  dropped, so JS consumers discover they need agent.subscribe() directly
- Hoist ALLOWED_KEYS Set to module scope to avoid per-call allocation
- Fix SubscribeToAgentSubscriber JSDoc: explicitly list the 5 supported
  callbacks and mention onNewMessage/onNewToolCall as excluded
- DRY subscribeToAgent() method JSDoc by referencing the type instead
  of duplicating the AG-UI exclusion rationale
- Fix safeCall comment: async error path returns Promise<undefined>,
  not undefined
- Add JSDoc to setDefaultThrottleMs setter; simplify getter JSDoc
- Fix use-agent.tsx: consistent camelCase callback names, fix @default
  tag format, replace unresolvable {@link} with plain text reference
- Add test: emitError/onError integration for SUBSCRIBER_CALLBACK_FAILED
- Add test: unsubscribe + throw combination in onMessagesChanged
- Add test: unsupported callback keys dropped with console.warn

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:14 +02:00
Maxim b9f5679937 fix: add emitError integration, safeCall docs, and single-source ALLOWED_KEYS
- Add SUBSCRIBER_CALLBACK_FAILED error code and call emitError() in
  safeCall so subscriber failures are visible to monitoring systems
  and onError handlers, not just console.error
- Document that safeCall intentionally discards return values on the
  error path (including lifecycle AgentStateMutation)
- Extract SUBSCRIBE_TO_AGENT_KEYS tuple as single source of truth for
  both the SubscribeToAgentSubscriber type and the runtime ALLOWED_KEYS
  set, eliminating the one-directional sync risk from the satisfies pattern

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:13 +02:00
Maxim 7fb4ddcd01 fix: improve type safety, error context, and JSDoc accuracy in subscribeToAgent
- Type `handlers` in use-agent.tsx as `SubscribeToAgentSubscriber` instead
  of full `AgentSubscriber` to prevent silent runtime stripping of unsupported
  callbacks
- Reframe AG-UI exclusion JSDoc: designed for observation, not event mutation
  (stopPropagation semantics can't be safely mediated)
- Add `satisfies` constraint to ALLOWED_KEYS so it stays synchronized with
  the SubscribeToAgentSubscriber Pick type at compile time
- Use `.then` instead of `.catch` for standard thenable detection in safeCall
- Include agent ID in all safeCall error messages for multi-agent debugging
- Only wrap lifecycle callbacks in guardAll for throttled path (messages/state
  wrappers were immediately overwritten — wasted work)
- Fix "pending flags" → "pending params" in inline comment

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 22:09:12 +02:00