Repository navigation
fix: synchronously execute renderAndWaitForResponse - #1861
Conversation
WalkthroughThis update introduces a multi-action travel planner chat interface in the Next.js example, adds supporting CSS, and significantly refactors CopilotKit's action execution flow to better handle multiple and human-in-the-loop (HITL) actions. It also enhances test coverage for multi-action scenarios and updates an Anthropic adapter configuration. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant TravelPlanner (React)
participant CopilotKitProvider
participant CopilotKit (Core)
participant HITL Action Handler
User->>TravelPlanner (React): Clicks multi-action button
TravelPlanner (React)->>CopilotKitProvider: Sends user message(s)
CopilotKitProvider->>CopilotKit (Core): Processes message(s)
CopilotKit (Core)->>HITL Action Handler: Triggers HITL action(s)
HITL Action Handler->>TravelPlanner (React): Renders action panel(s)
User->>TravelPlanner (React): Clicks "Continue"
TravelPlanner (React)->>HITL Action Handler: Calls respond callback
HITL Action Handler->>CopilotKit (Core): Completes action
CopilotKit (Core)->>CopilotKitProvider: Updates chat state
CopilotKitProvider->>TravelPlanner (React): Renders updated chat
Suggested reviewers
✨ Finishing Touches
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
|
There was a problem hiding this comment.
Pull Request Overview
This pull request fixes the synchronous execution of HITL actions by ensuring that multiple renderAndWaitForResponse calls are handled in a queue‐like fashion. Key changes include passing a messageId for HITL correlation in the render function, extending the action handler in useCopilotAction to capture an activating message ID, and updating useChat to execute actions in a synchronous sequence.
Reviewed Changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| CopilotKit/packages/react-ui/src/components/chat/messages/RenderActionExecutionMessage.tsx | Adds messageId for HITL correlation and improves error logging |
| CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts | Introduces and uses activatingMessageIdRef; refactors handler and render for HITL actions |
| CopilotKit/packages/react-core/src/hooks/use-chat.ts | Refactors action execution logic with flushSync and deduplicates HITL action handling |
| CopilotKit/examples/next-openai/src/app/multi/styles.css | Adds minimal styling for the multi-page example |
| CopilotKit/examples/next-openai/src/app/multi/page.tsx | Updates the client side to showcase multiple HITL and regular actions |
Comments suppressed due to low confidence (1)
CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts:186
- [nitpick] Consider defining an explicit type for _setActivatingMessageId to avoid using 'any' and improve code clarity.
(action as any)._setActivatingMessageId = (id: string | null) => {
| ); | ||
|
|
||
| if (alreadyProcessed) { | ||
| // Skip re-execution if already processed |
There was a problem hiding this comment.
Consider explicitly returning from the executeActionFromMessage function when alreadyProcessed is true to prevent further execution in this branch.
| // Skip re-execution if already processed | |
| // Skip re-execution if already processed | |
| return; |
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
1 Skipped Deployment
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (11)
CopilotKit/examples/next-openai/src/app/multi/styles.css (1)
3-5: Consider usingmin-heightinstead of a fixedheightto avoid double-scroll issues on mobile SafariSetting both
htmlandbodytoheight: 100%occasionally introduces an extra scroll-bar on iOS Safari when descendants also rely on100vh/100%. Switching tomin-height: 100%(or tailoring for100dvh) avoids that pitfall while keeping the wanted full-viewport effect.- height: 100%; + min-height: 100%;CopilotKit/packages/react-ui/src/components/chat/messages/RenderActionExecutionMessage.tsx (1)
90-92: Log full error details for easier debugging
console.errorwith template-string interpolation drops the stack trace and makes non-Error objects hard to read. Use a two-argument call to preserve the stack.-console.error(`Error executing render function for action ${message.name}: ${e}`); +console.error( + `Error executing render function for action ${message.name}:`, + e, +);CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts (2)
168-169: Remove leftover commented codeThe
currentlyActivatingHitlActionMessageIdRefcomment is obsolete and flagged with “REMOVE THIS FOR NOW”. Stray TODO-style comments easily become stale and trigger lint/prettier warnings—best delete them altogether.- // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW
208-233: Guard against undefinedresolve/ providereject
waitProps.respond/handleronly exposeresolve.
If the UI needs to cancel or signal an error,rejectshould also be available.- handler: status === "executing" && renderAndWaitRef.current && renderAndWaitRef.current.messageId === currentRenderMessageId ? renderAndWaitRef.current!.resolve : undefined, - respond: status === "executing" && renderAndWaitRef.current && renderAndWaitRef.current.messageId === currentRenderMessageId ? renderAndWaitRef.current!.resolve : undefined, + handler: + status === "executing" && + renderAndWaitRef.current && + renderAndWaitRef.current.messageId === currentRenderMessageId + ? renderAndWaitRef.current.resolve + : undefined, + respond: + status === "executing" && + renderAndWaitRef.current && + renderAndWaitRef.current.messageId === currentRenderMessageId + ? (value, isError = false) => + isError + ? renderAndWaitRef.current!.reject(value) + : renderAndWaitRef.current!.resolve(value) + : undefined,CopilotKit/examples/next-openai/src/app/multi/page.tsx (3)
70-83: Unusedargsparameter – great opportunity to improve UX
renderAndWaitForResponse({ status, args, respond })receivesargsbut never displays it.
Surfacing the incoming arguments (e.g., the city or date requested) would help users understand what they’re approving.- <p>Hotel</p> + <p>Hotel {args?.city && `for ${args.city}`}</p>
90-111: Infinite-loop safeguard
addMessageboth setsfollowUp: falseon the action definition and passes{ followUp: false }toappendMessage.
That is correct and prevents a follow-up completion, but please add a short inline comment explaining the intent to future maintainers—HITL examples can be confusing at first glance.
129-175: Reduce style duplication with a small helperThe four buttons share identical Tailwind classes. Extracting them into a reusable component (e.g.,
<DemoButton onClick={...}>) will reduce repetition and keep future edits DRY.- <button - className="bg-blue-500 text-white p-2 rounded-md" + <DemoButton onClick={...} > … - </button> + </DemoButton>CopilotKit/packages/react-core/src/hooks/use-chat.ts (4)
1-3: Avoid importingflushSyncat top-level unless absolutely necessary
flushSyncshould be used sparingly because it forces a synchronous React render.
If only HITL flows require it, consider dynamic import inside that branch to avoid pulling the heavier API into every bundle.🧰 Tools
🪛 GitHub Actions: Quality
[warning] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.
558-605: Helper re-created on every run – extract or memoise
executeActionFromMessageis re-declared for everyrunChatCompletionexecution, closing over a large number of locals.
Moving it outside or wrapping it inuseCallbackwith a minimal dependency list will:
- Reduce allocations.
- Make the function easier to unit-test.
No behaviour change, purely a perf / readability win.
640-648: Skipped HITL action still iterates – potential O(n²) growthAfter detecting
alreadyProcessed, wecontinueimplicitly by falling through.
For clarity and to avoid future accidental mutation, add an explicitcontinue;statement.- } else { + } else { // Call the single, externally defined executeActionFromMessage … } + continue; }
895-910: Parameter explosion – consider anoptionsobject
executeActionnow receives six positional params; adding more later will be brittle.
A single{ …options }parameter keeps call-sites readable and backwards-compatible.(Not blocking, but worth refactoring soon.)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
CopilotKit/examples/next-openai/src/app/multi/page.tsx(1 hunks)CopilotKit/examples/next-openai/src/app/multi/styles.css(1 hunks)CopilotKit/packages/react-core/src/hooks/use-chat.ts(7 hunks)CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts(3 hunks)CopilotKit/packages/react-ui/src/components/chat/messages/RenderActionExecutionMessage.tsx(2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Quality
CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts
[warning] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.
CopilotKit/packages/react-core/src/hooks/use-chat.ts
[warning] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.
CopilotKit/examples/next-openai/src/app/multi/page.tsx
[warning] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.
⏰ Context from checks skipped due to timeout of 90000ms (11)
- GitHub Check: Build Images (next-openai, next-openai)
- GitHub Check: Build Images (coagents-qa-native, ui)
- GitHub Check: Build Images (coagents-qa-native, agent, python, local-deps)
- GitHub Check: Build Images (coagents-qa-text, ui)
- GitHub Check: Build Images (coagents-qa-text, agent, python, local-deps)
- GitHub Check: Build Images (coagents-routing, ui)
- GitHub Check: Build Images (coagents-routing, agent, python, local-deps)
- GitHub Check: Build Images (coagents-research-canvas, ui)
- GitHub Check: Build Images (coagents-research-canvas, agent, python, local-deps)
- GitHub Check: Test (18.x)
- GitHub Check: Test (20.x)
🔇 Additional comments (3)
CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts (1)
1-1: Prettier check failing – run formatterCI reported a Prettier failure for this file. Running
pnpm prettier --write CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts(or the equivalent yarn/npm command) will keep the pipeline green.🧰 Tools
🪛 GitHub Actions: Quality
[warning] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.
CopilotKit/examples/next-openai/src/app/multi/page.tsx (1)
1-5: Prettier failure – run the formatter before mergingThe pipeline is complaining about formatting.
Please executepnpm prettier --write CopilotKit/examples/next-openai/src/app/multi/page.tsx(or the repo-equivalent command) and commit the result to unblock CI.🧰 Tools
🪛 GitHub Actions: Quality
[warning] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.
CopilotKit/packages/react-core/src/hooks/use-chat.ts (1)
927-932: CallingflushSyncinside an async context can starve the event loopReact docs recommend restricting
flushSyncto synchronous browser events.
Inside an awaited promise it can cause jank on large trees.
If the goal is “update state before awaiting”, a simpler pattern is:setMessages([...currentMessagesForRender]); await Promise.resolve(); // micro-task boundaryor wrap the handler in
ReactDOM.unstable_batchedUpdatesif batching is enough.
Consider revisiting this implementation to avoid potential performance regressions.
Signed-off-by: Tyler Slaton <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
CopilotKit/packages/react-core/src/hooks/use-chat.ts (2)
640-648: Add explicit return statement when skipping re-execution.When an action has already been processed, the code skips re-execution but doesn't explicitly return from the conditional branch. Adding an explicit return would improve code clarity and prevent potential execution of unintended code.
if (alreadyProcessed) { // Skip re-execution if already processed + return; } else { // Call the single, externally defined executeActionFromMessage const resultMessage = await executeActionFromMessage( action, message as ActionExecutionMessage, );
598-601: Verify nullability of _setActivatingMessageId parameter.The function call
_setActivatingMessageId(null)might cause a runtime error if the function is defined to accept only string types. Consider usingundefinedinstead or ensure the function signature acceptsnullvalues.
🧹 Nitpick comments (1)
CopilotKit/.changeset/healthy-flowers-act.md (1)
8-10: Consider adding a comma after 'Ultimately'.For improved readability and proper grammar:
- Previously, it was impossible to execute multiple human-in-the-loop (renderAndWaitForResponse) - calls in a row. Ultimately this was due to an issue with how CopilotKit was rendering the updates - when multiple renderAndWaitForResponse actions appeared on screen due to a reference based approach. + Previously, it was impossible to execute multiple human-in-the-loop (renderAndWaitForResponse) + calls in a row. Ultimately, this was due to an issue with how CopilotKit was rendering the updates + when multiple renderAndWaitForResponse actions appeared on screen due to a reference-based approach.🧰 Tools
🪛 LanguageTool
[typographical] ~9-~9: Consider adding a comma after ‘Ultimately’ for more clarity.
Context: ...nderAndWaitForResponse) calls in a row. Ultimately this was due to an issue with how Copil...(RB_LY_COMMA)
[uncategorized] ~10-~10: This expression is usually spelled with a hyphen.
Context: ...nse actions appeared on screen due to a reference based approach. With this change, actions wi...(BASED_HYPHEN)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
CopilotKit/.changeset/healthy-flowers-act.md(1 hunks)CopilotKit/examples/next-openai/src/app/multi/page.tsx(1 hunks)CopilotKit/packages/react-core/src/hooks/use-chat.ts(7 hunks)CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts
- CopilotKit/examples/next-openai/src/app/multi/page.tsx
🧰 Additional context used
🪛 LanguageTool
CopilotKit/.changeset/healthy-flowers-act.md
[typographical] ~9-~9: Consider adding a comma after ‘Ultimately’ for more clarity.
Context: ...nderAndWaitForResponse) calls in a row. Ultimately this was due to an issue with how Copil...
(RB_LY_COMMA)
[uncategorized] ~10-~10: This expression is usually spelled with a hyphen.
Context: ...nse actions appeared on screen due to a reference based approach. With this change, actions wi...
(BASED_HYPHEN)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Test (18.x)
- GitHub Check: Test (20.x)
🔇 Additional comments (5)
CopilotKit/packages/react-core/src/hooks/use-chat.ts (4)
2-2: Good addition of flushSync for synchronous UI updates.Adding
flushSyncfrom react-dom is essential for forcing synchronous DOM updates when handling human-in-the-loop interactions, which addresses the core issue described in the PR.
558-604: Well-structured centralized action execution implementation.This helper function effectively centralizes the action execution logic, creating a more maintainable codebase. It properly handles:
- HITL correlation through message ID tracking
- Appropriate follow-up behavior determination
- Synchronous UI updates for render-and-wait actions
- Result message insertion at the correct position
The synchronous execution model enables the queue-like behavior described in the changeset, allowing multiple renderAndWaitForResponse calls to execute consecutively.
932-937: Effective synchronous UI updates for interactive HITL actions.Using
flushSyncimmediately after the handler sets up the promise ensures that the UI updates to an interactive state before awaiting the promise resolution. This is crucial for the responsive rendering of human-in-the-loop components.
690-691: Improved clarity on follow-up logic.The comment clarifies when to run chat completion again, making the code more maintainable. The logic now properly handles action follow-up behavior based on explicit settings and execution context.
CopilotKit/.changeset/healthy-flowers-act.md (1)
12-14: Clear explanation of the fix implementation.The description effectively communicates how the synchronous execution approach addresses the core issue, creating a queue-like behavior that works with any combination of actions.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
examples/e2e/tests/multi-action.spec.ts (4)
10-11: Consider using more reliable waiting mechanisms instead of fixed timeouts.Hardcoded timeouts like
INTERACTION_DELAYcan make tests brittle and unnecessarily slow. Where possible, prefer waiting for specific UI changes or network responses.-const INTERACTION_DELAY = 6000; +// Use more granular timeouts in individual tests or wait for UI/network events
16-33: Consider cleanup of commented code and ensure query parameter consistency.Some variants are commented out without explanation, and there's an inconsistency in query parameter naming between active and commented variants.
const variants: TestVariants = [ { name: "OpenAI", queryParams: "?serviceAdapter=openai", }, { name: "Anthropic", queryParams: "?serviceAdapter=anthropic" }, { name: "Google Generative AI", queryParams: "?serviceAdapter=gemini" }, - // { - // name: "LangChain (OpenAI)", - // queryParams: "?serviceAdapter=langchain_openai", - // }, - // { - // name: "LangChain (Anthropic)", - // queryParams: "?coAgentsModel=langchain_anthropic", - // }, - // { - // name: "LangChain (Gemini)", - // queryParams: "?coAgentsModel=langchain_gemini", - // }, - // { name: "Groq", queryParams: "?coAgentsModel=groq" }, + // TODO: Add additional adapter variants once fully supported ];
96-98: Remove or update outdated comments.These comments refer to selectors that may not be relevant for this test. Either update them or remove them to keep the code clean.
- // This data-test-id seems specific to CopilotChat, ensure it's relevant for /multi page's readiness - // await expect(page.locator('[data-test-id="copilot-chat-ready"]')).toBeVisible({ timeout: PAGE_TIMEOUT }); - // Consider a more specific assertion for readiness after actions, like no loading indicators.
57-70: Extract common test patterns into helper functions.Each test follows a similar pattern of navigation, button clicks, and assertions. Extract these into helper functions to reduce duplication and improve maintainability.
async function runTest( page: Page, config: ConfigItem, variant: { queryParams: string }, buttonName: string, actions: Array<() => Promise<void>>, assertions: Array<() => Promise<void>> ) { page.setDefaultTimeout(PAGE_TIMEOUT); await page.goto(`${config.url}/multi${variant.queryParams}`); await page.getByRole('button', { name: buttonName }).click(); for (const action of actions) { await action(); } for (const assertion of assertions) { await assertion(); } } // Example usage: test('multiple of the same action', async ({ page }) => { await runTest( page, config, variant, 'Multiple of the same action', [ async () => { await page.getByTestId('temperature-continue-button').click(); await page.waitForTimeout(INTERACTION_DELAY); }, async () => { await page.getByTestId('precipitation-continue-button').click(); await page.waitForTimeout(INTERACTION_DELAY); }, async () => { await page.getByTestId('wind-continue-button').click(); } ], [ async () => { await expect(page.locator('.weather-result')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }); } ] ); });Also applies to: 73-84, 87-101, 104-120
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
CopilotKit/examples/next-openai/src/app/multi/page.tsx(1 hunks)CopilotKit/examples/next-openai/src/lib/dynamic-service-adapter.ts(1 hunks)examples/e2e/tests/multi-action.spec.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- CopilotKit/examples/next-openai/src/app/multi/page.tsx
🧰 Additional context used
🧬 Code Graph Analysis (2)
CopilotKit/examples/next-openai/src/lib/dynamic-service-adapter.ts (1)
CopilotKit/packages/runtime/src/service-adapters/anthropic/anthropic-adapter.ts (1)
AnthropicAdapter(48-225)
examples/e2e/tests/multi-action.spec.ts (1)
examples/e2e/lib/config-helper.ts (5)
TestVariants(35-35)getConfigs(40-42)filterConfigsByProject(70-80)PROJECT_NAMES(5-11)ConfigItem(15-22)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: Test (18.x)
- GitHub Check: Test (20.x)
🔇 Additional comments (2)
CopilotKit/examples/next-openai/src/lib/dynamic-service-adapter.ts (1)
41-41:Details
✅ Verification successful
Explicit model specification is a good practice.
Setting a specific model version for the Anthropic adapter ensures consistent behavior across environments and test runs. This explicit specification aligns well with the changes in the multi-action tests.
🌐 Web query:
Is "claude-3-7-sonnet-20250219" a valid Anthropic model name?💡 Result:
Yes, "claude-3-7-sonnet-20250219" is a valid model name for Anthropic's Claude 3.7 Sonnet model. This model, released on February 19, 2025, is Anthropic's most intelligent model to date, offering a balance between intelligence and speed, making it suitable for enterprise workloads. (docs.anthropic.com)
Citations:
Anthropic model version verified and approved
- File:
CopilotKit/examples/next-openai/src/lib/dynamic-service-adapter.ts(line 41)- Confirmed via Anthropic documentation that
"claude-3-7-sonnet-20250219"is a valid Claude 3.7 Sonnet model name. Locking to this version ensures consistent behavior across environments and test suites.return new AnthropicAdapter({ model: "claude-3-7-sonnet-20250219" });examples/e2e/tests/multi-action.spec.ts (1)
1-124: Good implementation of end-to-end tests for multiple human-in-the-loop actions.This test suite successfully validates the synchronous execution of multiple human-in-the-loop actions, which is the core objective of the PR. The tests cover various scenarios including multiple same actions, different actions, and a mix of HITL and non-HITL actions, providing comprehensive test coverage.
| await page.getByRole('button', { name: 'Continue' }).first().click(); | ||
| await page.waitForTimeout(INTERACTION_DELAY); // Consider replacing with waitForResponse or specific UI change | ||
| await page.getByRole('button', { name: 'Continue' }).first().click(); | ||
| await page.waitForTimeout(INTERACTION_DELAY); | ||
| await page.getByRole('button', { name: 'Continue' }).first().click(); | ||
| // Asserting on body might be too broad; prefer specific message containers |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Use more specific selectors instead of relying on position.
Using .first() to select buttons makes tests fragile if the UI order changes. Consider using more specific selectors or data attributes.
- await page.getByRole('button', { name: 'Continue' }).first().click();
+ await page.getByTestId('temperature-continue-button').click();
await page.waitForTimeout(INTERACTION_DELAY);
- await page.getByRole('button', { name: 'Continue' }).first().click();
+ await page.getByTestId('precipitation-continue-button').click();
await page.waitForTimeout(INTERACTION_DELAY);
- await page.getByRole('button', { name: 'Continue' }).first().click();
+ await page.getByTestId('wind-continue-button').click();You'll need to add corresponding data-testid attributes to your UI components:
<button data-testid="temperature-continue-button">Continue</button>🤖 Prompt for AI Agents
In examples/e2e/tests/multi-action.spec.ts around lines 63 to 68, the test uses
.first() to select the 'Continue' button, which is fragile if the UI order
changes. To fix this, update the UI components to include unique data-testid
attributes like data-testid="temperature-continue-button" on each button, then
modify the test to select buttons using these data-testid selectors instead of
relying on position or .first().
There was a problem hiding this comment.
Let's ignore the suggestion to not target valid HTML features and instead look for synthetic attributes.
Targeting by role is a "free accessibility test". If we have the chance to do it, let's do it.
There was a problem hiding this comment.
@ranst91 You're absolutely right. Using role-based selectors like getByRole('button') serves as an excellent "free accessibility test" and leverages proper HTML semantics rather than adding synthetic attributes.
If the team wants to make the selectors more specific while maintaining the accessibility benefits, you could consider distinguishing the buttons by their full text content or surrounding context rather than position:
// Instead of .first()
await page.getByRole('button', { name: 'Continue' }).filter({ hasText: 'Continue with weather data' }).click();
// Or locate by nearest label/heading
await page.locator('div:has-text("Temperature") button:has-text("Continue")').click();This preserves the accessibility testing while making selectors less dependent on UI order.
✏️ Learnings added
Learnt from: ranst91
PR: CopilotKit/CopilotKit#1861
File: examples/e2e/tests/multi-action.spec.ts:63-68
Timestamp: 2025-05-23T08:59:53.025Z
Learning: When writing Playwright tests for CopilotKit, prefer using role-based selectors (like getByRole) over synthetic attributes like data-testid, as role-based selectors provide implicit accessibility testing while targeting valid HTML features.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
| await page.waitForTimeout(INTERACTION_DELAY); | ||
| await page.getByRole('button', { name: 'Continue' }).first().click(); | ||
| // Asserting on body might be too broad; prefer specific message containers | ||
| await expect(page.locator('body')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Use more specific selectors for assertions.
Asserting on the entire body element is too broad and might catch unrelated text. Use more specific selectors for more reliable tests.
- await expect(page.locator('body')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT });
+ await expect(page.locator('.weather-result')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT });📝 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.
| await expect(page.locator('body')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }); | |
| await expect(page.locator('.weather-result')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }); |
🤖 Prompt for AI Agents
In examples/e2e/tests/multi-action.spec.ts at line 69, the assertion uses the
broad 'body' selector which may capture unrelated text. Replace the 'body'
selector with a more specific selector that targets the exact element containing
the '70 degrees' text, such as a unique class, id, or data attribute, to make
the test more reliable and precise.
| expect(page.locator('body')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }), | ||
| expect(page.locator('body')).toContainText('Marriott', { timeout: PAGE_TIMEOUT }), | ||
| ]); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Use more specific selectors for assertions.
Similar to the previous comment, use more specific selectors for assertions to make tests more reliable and maintainable.
await Promise.all([
- expect(page.locator('body')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }),
- expect(page.locator('body')).toContainText('Marriott', { timeout: PAGE_TIMEOUT }),
+ expect(page.locator('.weather-result')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }),
+ expect(page.locator('.hotel-result')).toContainText('Marriott', { timeout: PAGE_TIMEOUT }),
]);📝 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.
| expect(page.locator('body')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }), | |
| expect(page.locator('body')).toContainText('Marriott', { timeout: PAGE_TIMEOUT }), | |
| ]); | |
| await Promise.all([ | |
| expect(page.locator('.weather-result')).toContainText('70 degrees', { timeout: PAGE_TIMEOUT }), | |
| expect(page.locator('.hotel-result')).toContainText('Marriott', { timeout: PAGE_TIMEOUT }), | |
| ]); |
🤖 Prompt for AI Agents
In examples/e2e/tests/multi-action.spec.ts around lines 81 to 83, the assertions
use a generic 'body' selector which can lead to unreliable tests. Update the
selectors to target more specific elements or containers that uniquely identify
the text '70 degrees' and 'Marriott'. This will improve test reliability and
maintainability by reducing false positives and making the intent clearer.
Massive help, thanks a lot. Now the component doesn't unmount and remount when the chat's isLoading goes from true to false as well, not sure if the fix was intended for this behavior too but it fixed it as well which is nice. Edit @suhasdeshpande @tylerslaton : I retract what i said previously. The PR does solve the tools being umounted and remounted, but not completely, there is 1 last update when the chat goes from isLoading (true) to isLoading(false) and sometimes even randomly before that, the component gets umounted and remounted. I solved it by setting a key hashed from the arguments, hacky solution that works for now: const getOrCreateStableKey = (
componentName: string,
args: any,
status?: string
) => {
if (status === "inProgress") {
return undefined;
}
try {
// Create a unique identifier for this component instance
const argsString = JSON.stringify(args, Object.keys(args).sort());
const hash = stringToHash(argsString);
const componentId = `${componentName}-${hash}`;
// If we already have a key for this component, reuse it
if (componentKeysRef.has(componentId)) {
return componentKeysRef.get(componentId);
}
// Generate new stable key and store it
const newKey = `${componentName}-${Date.now()}-${Math.random()
.toString(36)
.substring(2, 8)}`;
componentKeysRef.set(componentId, newKey);
// Clean up old keys periodically to prevent memory leaks
if (componentKeysRef.size > 200) {
const keysToDelete = Array.from(componentKeysRef.keys()).slice(0, 50);
keysToDelete.forEach((key) => componentKeysRef.delete(key));
}
return newKey;
} catch (error) {
console.error("Error generating stable key:", error);
// Fallback to a simple key if there's any error
return `${componentName}-fallback-${Date.now()}-${Math.random()
.toString(36)
.substring(2, 8)}`;
}
};
useCopilotAction({
name: "full_ebook_writer",
available: "disabled",
description:
"Writes a complete structured ebook",
parameters: [
// truncated for brevity
],
renderAndWaitForResponse: (props) => {
return (
<FullEbooksWriter
key={getOrCreateStableKey(
"full_ebook_writer",
props.args,
props.status
)}
args={props.args}
state={state}
status={props.status}
result={props.result}
isLoading={isLoading}
saveModelFeedbackResolve={props.respond}
/>
);
},
}); |
| // clone the action to avoid mutating the original object | ||
| action = { ...action }; | ||
|
|
||
| // const { currentlyActivatingHitlActionMessageIdRef } = useCopilotContext() as any; // <-- REMOVE THIS FOR NOW |
There was a problem hiding this comment.
can we remove it completely and not have commented code?
| // check if renderAndWaitForResponse is set | ||
| (action.renderAndWait || action.renderAndWaitForResponse) | ||
| ) { | ||
| (action as any)._isRenderAndWait = true; // Internal flag to identify this action type later |
There was a problem hiding this comment.
as any seems bit dangerous. Do we need any checks before we assign the internal flag so we don't have weird side-effects later?
Previously, it was impossible to execute multiple human-in-the-loop (renderAndWaitForResponse) calls in a row. Ultimately this was due to an issue with how CopilotKit was rendering the updates when multiple renderAndWaitForResponse actions appeared on screen due to a reference based approach. With this change, actions will be executed in a synchronous way appearing almost queue like. This works with any combination of action given much more freedom when asking for user input. Signed-off-by: Tyler Slaton <[email protected]>
Signed-off-by: Tyler Slaton <[email protected]>
Signed-off-by: Tyler Slaton <[email protected]>
Signed-off-by: Tyler Slaton <[email protected]>
…t for multi tests Signed-off-by: Tyler Slaton <[email protected]>
Signed-off-by: Tyler Slaton <[email protected]>
Signed-off-by: Tyler Slaton <[email protected]>
🦋 Changeset detectedLatest commit: 1fe66be 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/healthy-flowers-act.md (1)
8-14: Hyphenation & punctuation tweaks improve readabilityMinor language fixes make the note flow better and avoid style inconsistencies (e.g. “reference-based”, “queue-like”).
- calls in a row. Ultimately this was due to an issue with how CopilotKit was rendering the updates - when multiple renderAndWaitForResponse actions appeared on screen due to a reference based approach. + calls in a row. Ultimately, this was due to an issue with how CopilotKit was rendering the updates + when multiple renderAndWaitForResponse actions appeared on screen due to a reference-based approach. - With this change, actions will be executed in a synchronous way appearing almost queue like. This - works with any combination of action given much more freedom when asking for user input. + With this change, actions will be executed in a synchronous manner, appearing almost queue-like. This + works with any combination of actions, giving much more freedom when asking for user input.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
CopilotKit/.changeset/healthy-flowers-act.md(1 hunks)CopilotKit/examples/next-openai/src/app/multi/page.tsx(1 hunks)CopilotKit/examples/next-openai/src/app/multi/styles.css(1 hunks)CopilotKit/examples/next-openai/src/lib/dynamic-service-adapter.ts(1 hunks)CopilotKit/packages/react-core/src/hooks/use-chat.ts(7 hunks)CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts(3 hunks)CopilotKit/packages/react-ui/src/components/chat/messages/RenderActionExecutionMessage.tsx(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
- CopilotKit/examples/next-openai/src/app/multi/styles.css
- CopilotKit/examples/next-openai/src/lib/dynamic-service-adapter.ts
- CopilotKit/packages/react-ui/src/components/chat/messages/RenderActionExecutionMessage.tsx
- CopilotKit/packages/react-core/src/hooks/use-copilot-action.ts
- CopilotKit/examples/next-openai/src/app/multi/page.tsx
- CopilotKit/packages/react-core/src/hooks/use-chat.ts
🧰 Additional context used
🪛 LanguageTool
CopilotKit/.changeset/healthy-flowers-act.md
[typographical] ~9-~9: Consider adding a comma after ‘Ultimately’ for more clarity.
Context: ...nderAndWaitForResponse) calls in a row. Ultimately this was due to an issue with how Copil...
(RB_LY_COMMA)
[uncategorized] ~10-~10: This expression is usually spelled with a hyphen.
Context: ...nse actions appeared on screen due to a reference based approach. With this change, actions wi...
(BASED_HYPHEN)
[uncategorized] ~12-~12: Possible missing comma found.
Context: ...tions will be executed in a synchronous way appearing almost queue like. This works...
(AI_HYDRA_LEO_MISSING_COMMA)
[uncategorized] ~13-~13: Possible missing comma found.
Context: ...ike. This works with any combination of action given much more freedom when asking for...
(AI_HYDRA_LEO_MISSING_COMMA)
⏰ Context from checks skipped due to timeout of 90000ms (11)
- GitHub Check: Build Images (coagents-qa-native, ui)
- GitHub Check: Build Images (coagents-qa-native, agent, python, local-deps)
- GitHub Check: Build Images (coagents-routing, agent, python, local-deps)
- GitHub Check: Build Images (coagents-routing, ui)
- GitHub Check: Build Images (coagents-qa-text, ui)
- GitHub Check: Build Images (next-openai, next-openai)
- GitHub Check: Build Images (coagents-qa-text, agent, python, local-deps)
- GitHub Check: Build Images (coagents-research-canvas, ui)
- GitHub Check: Build Images (coagents-research-canvas, agent, python, local-deps)
- GitHub Check: Test (20.x)
- GitHub Check: Test (18.x)
|
Preview environments destroyed for this pull request. |
Test ResultsStatus: ✅ Passed (View Run) Commit: 10b6470 Duration: 240.5s Total Tests: 33 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
|
Previously, it was impossible to execute multiple human-in-the-loop (renderAndWaitForResponse) calls in a row. Ultimately this was due to an issue with how CopilotKit was rendering the updates when multiple renderAndWaitForResponse actions appeared on screen due to a reference based approach.
With this change, actions will be executed in a synchronous way appearing almost queue like. This works with any combination of action given much more freedom when asking for user input.
Checklist
Summary by CodeRabbit
New Features
Bug Fixes
Style
Tests