Repository navigation
Add Agent Chat UI for HITL approve/edit/reject - #8
Conversation
Align the agent graph interrupt payload with the Agent Inbox HITLRequest schema so Agent Chat UI can render interactive approvals. Vendor the UI under apps/agent-chat-ui, fix CLI resume to Command(resume=decisions), and cover the new contract with tests. Co-authored-by: jnyross <jnyross@users.noreply.github.com>
📝 WalkthroughWalkthroughChangesAgent Chat UI and HITL integration
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
Unwrap multimodal content blocks to plain text and fall back when the planner model endpoint is unreachable so approve/edit/reject demos still reach the interrupt UI. Co-authored-by: jnyross <jnyross@users.noreply.github.com>
React rejected SVG clip-path attributes in the LangGraph logo, which aborted rendering so Tailwind never applied. CamelCase the attributes, and keep planner-fallback copy clean for the interrupt card. Co-authored-by: jnyross <jnyross@users.noreply.github.com>
| # Truthy/falsey fallback for unexpected shapes. | ||
| return {"type": "approve" if bool(resume_value) else "reject"} |
There was a problem hiding this comment.
🔴 Unrecognized approval replies are treated as approval, letting actions run without a human saying yes
An approval reply that the code doesn't recognise is treated as a "yes" (the truthy fallback at src/langgraph_graph/hitl.py:108-109) instead of being refused, so a pending external action can be carried out even though nobody actually approved it.
Impact: A malformed or empty approval reply silently executes the pending side-effecting action, defeating the human approval gate.
How an empty or unknown resume payload becomes an approval
_first_decision handles bool, str, dicts containing decisions/type, and lists of decision dicts. Any other non-empty structure falls through to return {"type": "approve" if bool(resume_value) else "reject"}. Concretely, Command(resume={"decisions": []}) (empty list — e.g. a UI/proxy sending no decisions) or any other non-empty dict such as {"foo": 1} is truthy, so resolve_hitl_decision returns granted=True and act_node invokes the bound tool with the default args (src/langgraph_graph/graph.py:105-115). The repository's HITL policy (AGENTS.md "HITL compliance minimum") requires an explicit human approval before external sends; the safe default here must be reject.
| # Truthy/falsey fallback for unexpected shapes. | |
| return {"type": "approve" if bool(resume_value) else "reject"} | |
| # Unrecognized shapes must never auto-approve a side effect. | |
| return {"type": "reject", "message": "Unrecognized resume payload; treating as rejection."} |
Was this helpful? React with 👍 or 👎 to provide feedback.
| messages = list(state.messages) | ||
| if not messages and request: | ||
| messages = [{"role": "user", "content": request}] | ||
| return { | ||
| "input": request, | ||
| "plan": steps, | ||
| "messages": state.messages + [{"role": "assistant", "content": str(raw)}], | ||
| "messages": messages + [{"role": "assistant", "content": str(raw)}], | ||
| } |
There was a problem hiding this comment.
🟡 Chat history disappears after each new message in the approval UI
Each new chat turn overwrites the stored conversation instead of being appended to it (the plain list messages field at src/langgraph_graph/state.py:18-21 has no merge behaviour), so earlier messages in a thread vanish once the next message is sent.
Impact: Users lose the visible conversation history in the new chat UI, and the agent loses prior context when continuing a thread.
Why the UI's incremental message submission drops history
Agent Chat UI submits only the newly created messages, relying on the server-side state to merge them: stream.submit({ messages: [...toolMessages, newHumanMessage], context }, ...) in apps/agent-chat-ui/src/components/thread/index.tsx:217-233. LangGraph merges channel updates with the channel's reducer; AgentState.messages is a plain list[dict[str, Any]] with no Annotated[..., add_messages] reducer, so the update replaces the whole list. On turn two the persisted state becomes just the new human message (plus whatever plan_node/reply_node append at src/langgraph_graph/graph.py:69-76), so previous turns are dropped from thread state and from stream.messages in the UI. The new test tests/agent/test_hitl.py:174-209 encodes this replacement behaviour.
Prompt for agents
Agent Chat UI submits only newly created messages per turn (see apps/agent-chat-ui/src/components/thread/index.tsx handleSubmit), expecting the graph state to append them. AgentState.messages in src/langgraph_graph/state.py is a plain list with no reducer, so each submit replaces the whole conversation and prior turns are lost from thread state and from the UI. Consider annotating the messages channel with an append/merge reducer (while preserving the AGENTS.md requirement that entries stay OpenAI-style dicts), and make sure plan_node/reply_node return only the new messages rather than the full list so they don't duplicate history. Update tests/agent/test_hitl.py::test_follow_up_messages_override_persisted_input accordingly, since it currently relies on replacement semantics.
Was this helpful? React with 👍 or 👎 to provide feedback.
| # Truthy/falsey fallback for unexpected shapes. | ||
| return {"type": "approve" if bool(resume_value) else "reject"} |
There was a problem hiding this comment.
🟥 Human approval gate fails open on unrecognized resume payloads
_first_decision falls back to {"type": "approve" if bool(resume_value) else "reject"} for any resume shape it does not recognise. A non-empty but unrecognised payload (e.g. Command(resume={"decisions": []}) or {"foo": 1} sent by a UI, proxy, or API caller) is truthy and therefore resolves to an approval, causing act_node to execute the bound side-effecting tool (src/langgraph_graph/graph.py:105-115) with no explicit human consent. AGENTS.md mandates a human approval interrupt before any external send / spend / production write.
Was this helpful? React with 👍 or 👎 to provide feedback.
| if dtype == "edit": | ||
| edited = decision.get("edited_action") or {} | ||
| name = str(edited.get("name") or default_tool) | ||
| args = edited.get("args") | ||
| if not isinstance(args, dict): | ||
| args = default_args | ||
| return True, name, args, None |
There was a problem hiding this comment.
🟨 Edited approval can substitute an arbitrary tool and arguments without re-review
On an edit decision, resolve_hitl_decision accepts whatever edited_action.name and edited_action.args the resume payload supplies and act_node looks that tool up in ALL_TOOLS and invokes it (src/langgraph_graph/graph.py:112-117). The edited action is never checked against the action name that was actually presented for review in the interrupt, so a resume payload can swap send_message for another registered side-effecting tool (e.g. write_record) and different arguments while the reviewed request said something else.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
Actionable comments posted: 14
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
🟡 Minor comments (20)
apps/agent-chat-ui/README.md-6-6 (1)
6-6: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse descriptive link text for the setup guide.
Replace
herewith text that identifies the destination, such asthe setup video. This improves link clarity and resolves the reported link-text warning.Suggested wording
-> 🎥 Watch the video setup guide [here](https://youtu.be/lInrwVnZ83o). +> 🎥 Watch the video setup guide [the setup video](https://youtu.be/lInrwVnZ83o).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/README.md` at line 6, Update the setup guide link in the README to use descriptive link text that identifies the destination, such as “the setup video,” instead of the generic “here,” while preserving the existing URL.Source: Linters/SAST tools
apps/agent-chat-ui/README.md-62-64 (1)
62-64: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winRemove the blank line inside the note blockquote.
Keep the alert marker directly above the note text. This resolves the reported MD028 warning.
Suggested fix
> [!NOTE] -> > If you are connecting to a LangSmith Agent Builder deployment, set `NEXT_PUBLIC_AUTH_SCHEME=langsmith-api-key`.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/README.md` around lines 62 - 64, Remove the blank line between the [!NOTE] marker and its text in the README, keeping the alert marker directly adjacent to the LangSmith authentication instruction to resolve the MD028 warning.Source: Linters/SAST tools
apps/agent-chat-ui/README.md-243-245 (1)
243-245: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUse
Authorizationfor the bearer token.LangGraph custom-auth examples use
Authorization, andauthreceives it asauthorization; this example will send the token in an unstandard/non-matchingAuthenticationheader.Suggested fix
defaultHeaders: { - Authentication: `Bearer ${addYourTokenHere}`, // this is where you would pass your authentication token + Authorization: `Bearer ${addYourTokenHere}`, // this is where you would pass your authentication token },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/README.md` around lines 243 - 245, Update the defaultHeaders example to use the standard Authorization header for the bearer token instead of Authentication, preserving the existing Bearer token value and comment.Source: MCP tools
src/langgraph_graph/graph.py-105-117 (1)
105-117: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winRestrict the edited tool name to the reviewed action.
resolve_hitl_decisionaccepts an arbitraryedited_action.name. Line 113 then resolves that name againstALL_TOOLS. A resume payload can therefore run a different tool than the one presented in the interrupt. The human supplies the payload, so this stays inside the HITL trust boundary, but the approval record at line 110 still saysact-1and the UI showedsend_message. Consider rejecting an edited name that does not matchtool_name, or record the executed tool in state.🛡️ Proposed change
if granted: + if resolved_tool != tool_name: + return { + "approvals": approvals, + "pending_action": None, + "output": f"Edited tool {resolved_tool!r} does not match the reviewed action; nothing executed.", + } tool = next((t for t in ALL_TOOLS if t.name == resolved_tool), None)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/langgraph_graph/graph.py` around lines 105 - 117, Restrict the resolved tool in the HITL decision flow around resolve_hitl_decision and the granted branch to the originally reviewed tool_name. Reject or otherwise prevent execution when resolved_tool differs from tool_name, while preserving approval recording and execution for matching names.Source: Learnings
apps/agent-chat-ui/src/components/thread/utils.ts-3-15 (1)
3-15: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe doc comment does not match the behavior.
The comment promises a modality label and a
Multimodal messagefallback. The function returns an empty string when the content holds no text block.apps/agent-chat-ui/src/components/thread/history/index.tsxline 39 assigns that result toitemText, so an image-only first message renders a blank thread label. Implement the documented fallback, or correct the comment.♻️ Proposed change
export function getContentString(content: Message["content"]): string { if (typeof content === "string") return content; const texts = content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text); - return texts.join(" "); + if (texts.length > 0) return texts.join(" "); + if (content.length === 0) return ""; + return "Multimodal message"; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/utils.ts` around lines 3 - 15, Update getContentString so content without text blocks returns the documented label for the first non-text modality, with “Multimodal message” as the unknown fallback, instead of an empty string; preserve the joined-text behavior for text content and keep the documentation aligned with the implementation.apps/agent-chat-ui/src/components/thread/history/index.tsx-88-95 (1)
88-95: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winSurface thread-fetch failures to the user.
.catch(console.error)hides the failure. The panel then shows an empty history, which looks identical to a new account with no threads. Show a toast, as the thread view does for stream errors. The effect also omitsgetThreads,setThreads, andsetThreadsLoadingfrom the dependency array; add a comment if the mount-only fetch is intentional, becausereact-hooks/exhaustive-depsflags this.♻️ Proposed change
useEffect(() => { if (typeof window === "undefined") return; setThreadsLoading(true); getThreads() .then(setThreads) - .catch(console.error) + .catch((error) => { + console.error(error); + toast.error("Failed to load thread history."); + }) .finally(() => setThreadsLoading(false)); + // Fetch once on mount; the context setters are stable. + // eslint-disable-next-line react-hooks/exhaustive-deps }, []);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/history/index.tsx` around lines 88 - 95, Update the thread-loading useEffect to show a user-facing toast on getThreads failure, matching the existing thread-view stream-error behavior instead of only calling console.error. Preserve the loading reset in finally, and address the exhaustive-deps warning by including getThreads, setThreads, and setThreadsLoading in the dependency array or documenting the intentional mount-only fetch with an appropriate comment.apps/agent-chat-ui/src/components/thread/messages/shared.tsx-25-30 (1)
25-30: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winHandle clipboard failures and clear the timer.
navigator.clipboard.writeTextreturns a promise. The code ignores the rejection. On an insecure origin or when permission is denied, the UI still shows the copied state and the browser logs an unhandled rejection. ThesetTimeoutalso survives unmount.🛡️ Proposed change
- const handleCopy = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { + const handleCopy = async ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent>, + ) => { e.stopPropagation(); - navigator.clipboard.writeText(content); - setCopied(true); - setTimeout(() => setCopied(false), 2000); + try { + await navigator.clipboard.writeText(content); + setCopied(true); + } catch { + toast.error("Failed to copy content."); + } };Then clear the flag with an effect:
useEffect(() => { if (!copied) return; const timer = setTimeout(() => setCopied(false), 2000); return () => clearTimeout(timer); }, [copied]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/messages/shared.tsx` around lines 25 - 30, Update handleCopy to await navigator.clipboard.writeText and set copied only after success, handling rejected writes without an unhandled promise rejection. Move the reset timeout into a useEffect keyed by copied, returning clearTimeout cleanup so it cannot survive component unmount.apps/agent-chat-ui/src/components/thread/messages/human.tsx-52-74 (1)
52-74: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winEditing drops multimodal attachments.
handleSubmitEditbuildscontent: value, a plain string. If the original message contains base64 image or file blocks, the edit removes them. The rendering path at lines 93-111 shows those blocks, so the loss is visible to the user. Preserve the non-text blocks and replace only the text block.♻️ Proposed change
- const newMessage: Message = { type: "human", content: value }; + const attachments = Array.isArray(message.content) + ? message.content.filter((block) => isBase64ContentBlock(block)) + : []; + const newMessage: Message = { + type: "human", + content: [ + ...(value.trim().length > 0 ? [{ type: "text", text: value }] : []), + ...attachments, + ] as Message["content"], + };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/messages/human.tsx` around lines 52 - 74, Update handleSubmitEdit to preserve the original human message’s non-text content blocks, including image and file attachments, while replacing only its text block with value. Reuse the existing message/content structure available to the component, and ensure both the submitted newMessage and optimisticValues update contain the preserved blocks.apps/agent-chat-ui/src/components/ui/input.tsx-10-13 (1)
10-13: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRestore a keyboard focus indicator on the shared input.
outline-noneremoves the default focus outline, and thisoutline-noneuses does not provide afocus-visible:equivalent. Add the same keyboard focus style used by the nearby UI inputs, such asfocus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/ui/input.tsx` around lines 10 - 13, The shared input lacks a visible keyboard focus indicator because its class list includes outline-none without a focus-visible replacement. Update the className in the input component to add the established focus-visible:border-ring, focus-visible:ring-[3px], and focus-visible:ring-ring/50 styles alongside the existing focus-related classes.apps/agent-chat-ui/tailwind.config.js-16-19 (1)
16-19: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winRegister
.scrollbar-prettywhere this app uses Tailwind.
globals.cssimports Tailwind v4 without@config, soapps/agent-chat-ui/tailwind.config.jsis not loaded by this app andcomponents: { ".scrollbar-pretty": ... }has no effect here. Define.scrollbar-prettyinglobals.csswith@utility, or add the missing CSS/import wiring if the JS config must apply.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/tailwind.config.js` around lines 16 - 19, Register the scrollbar-pretty utility in the app’s Tailwind v4 CSS entrypoint, globals.css, using `@utility` and preserve the existing overflow and scrollbar styles; alternatively, wire that entrypoint to load tailwind.config.js if the components definition must remain there.apps/agent-chat-ui/src/app/globals.css-126-140 (1)
126-140: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winRemove the invalid chart-token overrides.
Lines 126-140 overwrite valid
oklch(...)chart colors with bare HSL channels.--color-chart-*then resolves to an invalid color value for chart utility classes.Remove these duplicate declarations, or use complete values such as
hsl(12 76% 61%).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/app/globals.css` around lines 126 - 140, Remove the duplicate --chart-1 through --chart-5 declarations from the :root and .dark blocks in globals.css, or replace them with complete valid color values; preserve the existing valid oklch chart-token definitions so --color-chart-* resolves correctly.apps/agent-chat-ui/src/components/thread/artifact.tsx-128-137 (1)
128-137: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winHonor the functional
setOpenargument.The callback branch ignores
value. For example,setOpen(() => false)opens a closed artifact instead of keeping it closed.Proposed fix
if (typeof value === "boolean") { ctxSetOpen(value ? id : null); } else { - ctxSetOpen((open) => (open === id ? null : id)); + ctxSetOpen((open) => (value(open === id) ? id : null)); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/artifact.tsx` around lines 128 - 137, Update the functional branch of setOpen to invoke value with the current open state and use its boolean result to determine whether ctxSetOpen receives id or null. Preserve the existing direct-boolean behavior and continue calling ctxSetMounted(id).apps/agent-chat-ui/package.json-12-20 (1)
12-20: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winMove
nextintodependencies.The
startscript runsnext startin production.nextis declared indevDependenciesat Line 76. An install with--productionorNODE_ENV=productionomitsnext, andnext startthen fails.reactandreact-domare already runtime dependencies, so the split is inconsistent.🔧 Proposed dependency move
"dependencies": { + "next": "^15.5.21", "`@langchain/core`": "^1.1.44","devDependencies": { - "next": "^15.5.21",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/package.json` around lines 12 - 20, Move the next package from devDependencies to dependencies in package.json, keeping its existing version constraint unchanged so the production start script can resolve it while preserving the current dependency set.apps/agent-chat-ui/package.json-72-76 (1)
72-76: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAlign the Next lint config path with the installed Next.js version.
nextis still at^15.5.21, whileeslint-config-nextis pinned to16.2.4.eslint-config-next16 is meant for Next 16/flat config flow, and Next 16 removednext lint. If this app remains on Next 15, change the config/source to includenext-eslint/Next 15 rules. If the app will upgrade to Next 16, removenext lintscripts/config and run ESLint directly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/package.json` around lines 72 - 76, Align the linting setup with the installed Next.js version in the package configuration: either keep next at ^15.5.21 and replace eslint-config-next 16.2.4 with the compatible Next 15 lint configuration, or upgrade the app consistently to Next 16 and remove next lint usage, switching scripts and configuration to invoke ESLint directly.apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-id.tsx-41-46 (1)
41-46: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winGuard the clipboard write.
navigator.clipboardis undefined in non-secure contexts, andwriteTextreturns a promise that can reject. The current code throws or produces an unhandled rejection, and it still setscopiedtotrueafter a failure.🛡️ Proposed fix
- const handleCopy = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => { + const handleCopy = async ( + e: React.MouseEvent<HTMLButtonElement, MouseEvent>, + ) => { e.stopPropagation(); - navigator.clipboard.writeText(threadId); - setCopied(true); - setTimeout(() => setCopied(false), 2000); + try { + await navigator.clipboard?.writeText(threadId); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + } catch (error) { + console.error("Failed to copy thread ID", error); + } };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-id.tsx` around lines 41 - 46, Update handleCopy to verify navigator.clipboard and handle the promise returned by writeText before updating copied state; setCopied(true) and the reset timeout only after a successful write, and safely handle unavailable or rejected clipboard operations without an unhandled rejection.apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx-154-173 (1)
154-173: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winMake the error inspection safe.
erroris typedany. If the thrown value is a string,null, or a number,"message" in errorthrows aTypeErrorinside thecatchblock. The user then receives no toast.🛡️ Proposed fix
- } catch (error: any) { + } catch (error: unknown) { console.error("Error sending human response", error); errorOccurred = true; - if ("message" in error && error.message.includes("Invalid assistant")) { + const message = error instanceof Error ? error.message : String(error); + if (message.includes("Invalid assistant")) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx` around lines 154 - 173, Make the catch logic in the human-response submission handler safely inspect unknown thrown values before checking the error message: ensure the value is non-null and object-like before using the "message" property, while preserving the existing invalid-assistant and generic toast behavior.apps/agent-chat-ui/src/components/thread/agent-inbox/components/inbox-item-input.tsx-210-224 (1)
210-224: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAssociate the field labels with the textareas.
The argument label at Line 211 and the "Reason" label at Line 286 are plain
<p>elements. Screen readers do not announce a name for the relatedTextarea. Add anidon eachTextareaand use aLabelwithhtmlFor, or addaria-labelto eachTextarea.♿ Proposed fix for the edit fields
- <div className="flex w-full flex-col items-start gap-[6px]"> - <p className="min-w-fit text-sm font-medium"> - {prettifyText(key)} - </p> - <Textarea - disabled={isLoading} + <div className="flex w-full flex-col items-start gap-[6px]"> + <label + htmlFor={`edit-arg-${key}-${idx}`} + className="min-w-fit text-sm font-medium" + > + {prettifyText(key)} + </label> + <Textarea + id={`edit-arg-${key}-${idx}`} + disabled={isLoading}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/components/inbox-item-input.tsx` around lines 210 - 224, Associate each edit-field label with its corresponding Textarea in the component: replace the plain label paragraphs with accessible Label elements using htmlFor, and assign matching unique ids to the Textareas in both the argument field block and the “Reason” field block. Preserve the existing values, handlers, and layout.apps/agent-chat-ui/src/components/thread/messages/tool-calls.tsx-74-86 (1)
74-86: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winNon-string tool content renders as
[object Object].The
tryblock only runs whenmessage.contentis a string. When a tool returns structured content blocks,message.contentis an array,parsedContentstaysundefined,isJsonContentstaysfalse, and Line 86 falls through toString(message.content). That produces"[object Object]"in the result panel.Serialize non-string content instead.
🐛 Proposed fix
try { if (typeof message.content === "string") { parsedContent = JSON.parse(message.content); isJsonContent = isComplexValue(parsedContent); + } else { + parsedContent = message.content; + isJsonContent = isComplexValue(parsedContent); } } catch { // Content is not JSON, use as is parsedContent = message.content; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/messages/tool-calls.tsx` around lines 74 - 86, Update the content parsing logic around parsedContent and isJsonContent so non-string message.content values, including structured arrays or objects, are serialized with JSON.stringify before rendering. Preserve the existing JSON parsing behavior for string content and ensure contentStr does not fall back to String(message.content) for structured values.apps/agent-chat-ui/src/lib/agent-inbox-interrupt.ts-4-52 (1)
4-52: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winThe guard validates only the first array element but narrows the whole array.
Line 7 selects
value[0]whenvalueis an array, and every later check runs against that single element. The return type still assertsInterrupt<HITLRequest>[], so callers treat all entries as validated.
ThreadViewinapps/agent-chat-ui/src/components/thread/agent-inbox/index.tsxmaps over every entry (Lines 70-93) and forwards each one toThreadActionsView. A malformed later entry yields an emptyaction_requestslist and a decision form with no actions, so the run cannot be resumed from that tab.Validate every element.
🐛 Proposed fix
export function isAgentInboxInterruptSchema( value: unknown, ): value is Interrupt<HITLRequest> | Interrupt<HITLRequest>[] { - const valueAsObject = Array.isArray(value) ? value[0] : value; + if (Array.isArray(value)) { + return value.length > 0 && value.every(isSingleAgentInboxInterrupt); + } + return isSingleAgentInboxInterrupt(value); +} + +function isSingleAgentInboxInterrupt(valueAsObject: unknown): boolean { if (!valueAsObject || typeof valueAsObject !== "object") { return false; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/lib/agent-inbox-interrupt.ts` around lines 4 - 52, Update isAgentInboxInterruptSchema to validate every element when value is an array, rather than checking only value[0]. Preserve the single-value validation path, ensure each interrupt has valid action_requests and review_configs, and only return the array type guard when all entries pass validation.apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx-30-41 (1)
30-41: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
"System"case never matches.LangChain message types are lowercase. Line 37 compares against
"System", so a system message falls through to thedefaultcase and renders an empty label. Use"system".🐛 Proposed fix
case "tool": return "Tool"; - case "System": + case "system": return "System"; default: return "";🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx` around lines 30 - 41, Update the type switch so the system-message branch in the label-mapping logic matches the lowercase `"system"` value instead of `"System"`, while preserving the existing `"System"` label and fallback behavior.
🧹 Nitpick comments (18)
apps/agent-chat-ui/src/components/thread/messages/human.tsx (1)
93-111: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
filterandmapinstead ofreduce.The
reducecall only filters and maps.filter(isBase64ContentBlock).map(...)states the intent directly and removes the accumulator.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/messages/human.tsx` around lines 93 - 111, In the message content rendering block, replace the reduce-based accumulation with a filter using isBase64ContentBlock followed by map to render MultimodalPreview for each retained block, preserving the existing idx-based keys and preview props.apps/agent-chat-ui/src/components/thread/messages/shared.tsx (1)
137-158: 🩺 Stability & Availability | 🔵 Trivial | ⚖️ Poor tradeoffPrefer a discriminated union over throwing during render.
CommandBarthrows for invalid prop combinations. A throw during render unmounts the whole thread view unless an error boundary catches it. A discriminated union prop type rejects the same combinations at compile time and removes the runtime crash path.♻️ Sketch
type CommandBarProps = { content: string; isLoading: boolean } & ( | { isHumanMessage: true; isAiMessage?: false; isEditing: boolean; setIsEditing: React.Dispatch<React.SetStateAction<boolean>>; handleSubmitEdit: () => void; handleRegenerate?: never; } | { isAiMessage: true; isHumanMessage?: false; handleRegenerate?: () => void; } );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/messages/shared.tsx` around lines 137 - 158, Update the CommandBar props type to a discriminated union keyed by isHumanMessage and isAiMessage, requiring the human-message editing callbacks only in the human branch and allowing regeneration only in the AI branch. Remove the render-time validation throws for mutually exclusive or missing flags, while preserving the existing valid prop behavior.examples/hitl_basic.py (1)
6-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace the en dash to satisfy Ruff RUF002.
- 3. Resume with an Agent Chat UI–compatible decision payload. + 3. Resume with an Agent Chat UI-compatible decision payload.The same character appears in the docstring at
src/langgraph_graph/hitl.pyline 58, which Ruff also flags.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/hitl_basic.py` at line 6, Replace the en dash in the documentation text in examples/hitl_basic.py with a plain hyphen or equivalent ASCII punctuation, and make the same replacement in the docstring associated with the hitl implementation. Preserve the existing wording and meaning while ensuring both locations satisfy Ruff RUF002.Source: Linters/SAST tools
tests/agent/test_hitl.py (1)
36-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for unparseable resume payloads.
The parametrized cases cover approve, edit, reject, and booleans. They do not cover the fallback branch in
_first_decisionatsrc/langgraph_graph/hitl.pyline 109. That branch decides whether an unknown payload grants an external side effect. Add cases such as{},{"decisions": []},{"foo": "bar"}, and"maybe". The test also drops_msg; assert the rejection message for the reject case.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/agent/test_hitl.py` around lines 36 - 74, Add parametrized cases to test_resolve_hitl_decision for unparseable resumes such as {}, {"decisions": []}, {"foo": "bar"}, and "maybe", asserting the fallback denies the action while preserving the default tool and arguments. Also retain the resolved message from the function and assert the expected rejection message for the existing reject case.scripts/run.py (1)
51-74: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShare the resume helper with the example.
examples/hitl_basic.pylines 43-65 contain the same interrupt detection, decision construction, and output printing. Both copies must change together when the decision schema changes. Consider moving_ask_humanand the resume block intosrc/langgraph_graph/hitl.pyor a small shared CLI helper.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scripts/run.py` around lines 51 - 74, Extract the duplicated _ask_human, interrupt detection, decision construction, resume invocation, and final output handling from scripts/run.py and examples/hitl_basic.py into a shared helper, preferably src/langgraph_graph/hitl.py or a small shared CLI module. Update both callers to use the shared implementation so future decision-schema changes are applied consistently.src/langgraph_graph/graph.py (1)
59-64: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winLog the swallowed planner exception.
The bare
except Exceptionhides configuration, authentication, and network errors. The run then continues silently with a fallback plan. Add a debug or warning log so operators can diagnose why the model call failed. This also documents the intent of the broad catch for Ruff BLE001.♻️ Proposed change
+import logging + +logger = logging.getLogger(__name__) + try: raw = str(_llm().invoke(prompt).content) - except Exception: + except Exception: # noqa: BLE001 - keep demos usable when the endpoint is down # Keep HITL demos usable when the local model endpoint is down. # Keep this user-facing text clean — it surfaces in Agent Chat UI. + logger.warning("Planner model call failed; using fallback plan.", exc_info=True) raw = request or "Handle the user's request"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/langgraph_graph/graph.py` around lines 59 - 64, Update the broad exception handler around the planner invocation in the graph flow to capture the exception and emit a debug or warning log with its details before assigning the fallback raw response. Keep the existing fallback behavior unchanged and retain the broad catch with explicit logging to document its intentional use for Ruff BLE001.Source: Linters/SAST tools
apps/agent-chat-ui/src/components/ui/sheet.tsx (1)
65-100: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueResolve the missing Sheet description in dev.
history/index.tsxrendersSheetTitlewithoutSheetDescription. This can trigger Radix’s “Missing Description oraria-describedby={undefined}” warning in non-production environments. Add a visually hidden description inSheetHeader, or passaria-describedby={undefined}when no description is available.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/ui/sheet.tsx` around lines 65 - 100, Update the Sheet usage in history/index.tsx where SheetTitle is rendered to provide a SheetDescription inside SheetHeader, using the existing visually-hidden pattern, or explicitly set aria-describedby to undefined when no description is available. Preserve the current SheetContent behavior and ensure the Radix warning is eliminated in development.apps/agent-chat-ui/components.json (1)
6-10: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the active global stylesheet for shadcn configuration.
components.jsonpoints shadcn atsrc/index.css, but the app only imports./globals.cssfromapps/agent-chat-ui/src/app/layout.tsx; there is nosrc/index.css. Set this tosrc/app/globals.cssso shadcn writes theme changes to the loaded stylesheet.Proposed fix
- "css": "src/index.css", + "css": "src/app/globals.css",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/components.json` around lines 6 - 10, Update the shadcn Tailwind configuration’s tailwind.css path in components.json from src/index.css to src/app/globals.css, matching the stylesheet imported by the layout.tsx component.apps/agent-chat-ui/src/hooks/use-file-upload.tsx (1)
223-243: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the shadowed
isDuplicatecopy.
handlePastedefines a localisDuplicatethat duplicates the hook-scope helper at Lines 27-45. The local copy shadows the outer one. If one copy changes, paste and upload apply different duplicate rules. Reuse the hook-scope helper and passcontentBlocks.♻️ Proposed deduplication
- const isDuplicate = (file: File) => { - if (file.type === "application/pdf") { - return contentBlocks.some( - (b) => - b.type === "file" && - b.mimeType === "application/pdf" && - b.metadata?.filename === file.name, - ); - } - if (SUPPORTED_FILE_TYPES.includes(file.type)) { - return contentBlocks.some( - (b) => - b.type === "image" && - b.metadata?.name === file.name && - b.mimeType === file.type, - ); - } - return false; - }; - const duplicateFiles = validFiles.filter(isDuplicate); - const uniqueFiles = validFiles.filter((file) => !isDuplicate(file)); + const duplicateFiles = validFiles.filter((file) => + isDuplicate(file, contentBlocks), + ); + const uniqueFiles = validFiles.filter( + (file) => !isDuplicate(file, contentBlocks), + );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/hooks/use-file-upload.tsx` around lines 223 - 243, Remove the locally defined isDuplicate function in handlePaste and reuse the hook-scope isDuplicate helper instead, passing contentBlocks as required. Keep duplicateFiles and uniqueFiles filtering behavior unchanged while ensuring paste and upload share the same duplicate rules.apps/agent-chat-ui/src/lib/ensure-tool-responses.ts (1)
10-13: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCorrect the
tool_callsguard.The comment states the guard skips AI messages without tool calls. The condition does not do that. If
tool_callsisundefined,message.tool_calls?.lengthisundefined, andundefined === 0isfalse. Execution continues past the guard.The result is still correct today, because
?? []at Line 29 pushes nothing. The code depends on that fallback. Use a length check so the guard matches its comment.♻️ Proposed fix
- if (message.type !== "ai" || message.tool_calls?.length === 0) { + if (message.type !== "ai" || !message.tool_calls?.length) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/lib/ensure-tool-responses.ts` around lines 10 - 13, Update the guard in ensureToolResponses so AI messages with no tool calls, including when tool_calls is undefined, return immediately. Use a null-safe length check that treats missing or empty tool_calls as zero, while preserving the existing behavior for AI messages containing tool calls.apps/agent-chat-ui/src/lib/multimodal-utils.ts (1)
8-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe supported MIME type list is declared twice.
multimodal-utils.tsbuilds its ownsupportedImageTypesandsupportedFileTypesarrays, anduse-file-upload.tsxexportsSUPPORTED_FILE_TYPESwith the same values. Both lists gate the same upload flow. If one list changes, the hook accepts a file that the converter then rejects with a second toast.
apps/agent-chat-ui/src/lib/multimodal-utils.ts#L8-L14: export a singleSUPPORTED_IMAGE_TYPESconstant here, derivesupportedFileTypesfrom it, and remove the inline literals.apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L6-L12: import the shared constants from@/lib/multimodal-utilsand re-exportSUPPORTED_FILE_TYPESif external consumers depend on the current name.Place the constants in
multimodal-utils.ts, because the hook already importsfileToContentBlockfrom that module. The reverse direction would create a cycle.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/lib/multimodal-utils.ts` around lines 8 - 14, Centralize the MIME type constants in apps/agent-chat-ui/src/lib/multimodal-utils.ts:8-14 by exporting SUPPORTED_IMAGE_TYPES and deriving supportedFileTypes from it, removing duplicate literals. Update apps/agent-chat-ui/src/hooks/use-file-upload.tsx:6-12 to import these shared constants from `@/lib/multimodal-utils` and re-export SUPPORTED_FILE_TYPES under its existing name for external consumers; keep the dependency direction through fileToContentBlock to avoid a cycle.apps/agent-chat-ui/src/components/thread/agent-inbox/utils.ts (1)
75-87: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winValidate the parsed date instead of relying on a thrown error.
The condition at Lines 77-80 is always true.
new Date("not a date")returns an Invalid Date object, which is truthy.formatthen throws aRangeError, and thecatchblock returnsundefined. Check the parsed value directly.♻️ Proposed fix
export function unknownToPrettyDate(input: unknown): string | undefined { - try { - if ( - Object.prototype.toString.call(input) === "[object Date]" || - new Date(input as string) - ) { - return format(new Date(input as string), "MM/dd/yyyy hh:mm a"); - } - } catch (_) { - // failed to parse date. no-op - } - return undefined; + if (typeof input !== "string" && typeof input !== "number" && !(input instanceof Date)) { + return undefined; + } + const parsed = new Date(input as string | number | Date); + if (Number.isNaN(parsed.getTime())) { + return undefined; + } + return format(parsed, "MM/dd/yyyy hh:mm a"); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/utils.ts` around lines 75 - 87, Update unknownToPrettyDate to parse the input once and validate the resulting Date before calling format. Replace the always-truthy new Date condition with an explicit validity check, preserving the undefined return for invalid or unparseable inputs and the existing formatting for valid dates.apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx (1)
5-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
RefObjectinstead of the deprecated React ref type.
React.MutableRefObject<Record<string, string>>is deprecated under@types/react19. UseReact.RefObject<Record<string, string>>inuse-interrupted-actions.tsx:41.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx` around lines 5 - 13, Update the ref type used by use-interrupted-actions to use React.RefObject<Record<string, string>> instead of the deprecated React.MutableRefObject type, while preserving the existing ref behavior and callers.apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx (1)
83-85: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConvert numbers to strings before passing them to
MarkdownText.This branch accepts
numberbut casts it withas string.MarkdownTextforwards its child toReactMarkdown, which expects a string. The cast hides the mismatch from the compiler instead of fixing it.♻️ Proposed fix
if (["string", "number"].includes(typeof props.value)) { - return <MarkdownText>{props.value as string}</MarkdownText>; + return <MarkdownText>{String(props.value)}</MarkdownText>; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx` around lines 83 - 85, Update the primitive-value branch in the state view to convert numeric props.value to a string before passing it to MarkdownText, rather than relying on the current as string cast; preserve the existing string handling and MarkdownText rendering behavior.apps/agent-chat-ui/src/components/thread/agent-inbox/index.tsx (1)
27-29: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winReset the active index on interrupt identity, not on count.
The dependency is
interrupts.length. If a new interrupt set arrives with the same number of entries,activeInterruptIndexis kept, and the UI shows an unrelated action at the same position. Depend oninterruptsinstead.♻️ Proposed fix
useEffect(() => { setActiveInterruptIndex(0); - }, [interrupts.length]); + }, [interrupts]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/agent-inbox/index.tsx` around lines 27 - 29, Update the useEffect that calls setActiveInterruptIndex in the agent inbox component to depend on the interrupts collection rather than interrupts.length, so the active index resets whenever the interrupt identities change even if the count stays the same.apps/agent-chat-ui/src/components/thread/markdown-text.tsx (1)
30-37: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winHandle clipboard write failures.
navigator.clipboard.writeTextreturns a rejected promise when the page is not in a secure context or the user denies permission. The current chain has no rejection handler, so the failure surfaces as an unhandled promise rejection and the copy button gives no feedback.♻️ Proposed fix
const copyToClipboard = (value: string) => { if (!value) return; - navigator.clipboard.writeText(value).then(() => { - setIsCopied(true); - setTimeout(() => setIsCopied(false), copiedDuration); - }); + navigator.clipboard + .writeText(value) + .then(() => { + setIsCopied(true); + setTimeout(() => setIsCopied(false), copiedDuration); + }) + .catch((error) => { + console.error("Failed to copy to clipboard", error); + }); };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/markdown-text.tsx` around lines 30 - 37, Update copyToClipboard to handle rejected promises from navigator.clipboard.writeText by adding a rejection path that prevents unhandled errors and provides appropriate copy-failure feedback, while preserving the existing success behavior that updates isCopied and resets it after copiedDuration.apps/agent-chat-ui/src/components/thread/messages/ai.tsx (1)
169-181: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCollapse the redundant tool-call branches.
The first branch (Lines 171-173) and the third branch (Lines 177-179) render the identical element
<ToolCalls toolCalls={message.tool_calls} />. ThetoolCallsHaveContentscheck therefore changes nothing. Keep one branch for SDK tool calls and one for the Anthropic streamed tool calls.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/messages/ai.tsx` around lines 169 - 181, Simplify the tool-call rendering inside the hideToolCalls guard in the message component by removing the redundant hasToolCalls && toolCallsHaveContents branch. Render one ToolCalls instance for SDK tool calls and one for hasAnthropicToolCalls using anthropicStreamedToolCalls, preserving the existing fallback behavior.apps/agent-chat-ui/src/components/thread/syntax-highlighter.tsx (1)
1-4: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueImport the Prism theme from the ESM style bundle.
typescriptandpythonusedist/esm/languages/prism/..., butcoldarkDarkusesdist/cjs/styles/prism. Use the package’s native style entry point:react-syntax-highlighter/dist/esm/styles/prism. This avoids importing both the CommonJS and ESM builds ofreact-syntax-highlighterfrom the same file.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/agent-chat-ui/src/components/thread/syntax-highlighter.tsx` around lines 1 - 4, Update the coldarkDark import in syntax-highlighter.tsx to use react-syntax-highlighter’s ESM Prism style entry point, matching the existing tsx and python language imports; leave the theme symbol and other imports unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 2c95ecfd-6d5a-40c6-a127-5d040904e537
⛔ Files ignored due to path filters (2)
apps/agent-chat-ui/pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlapps/agent-chat-ui/src/app/favicon.icois excluded by!**/*.ico
📒 Files selected for processing (84)
.gitignoreAGENTS.mdREADME.mdapps/agent-chat-ui/.codespellignoreapps/agent-chat-ui/.dockerignoreapps/agent-chat-ui/.env.exampleapps/agent-chat-ui/.github/dependabot.ymlapps/agent-chat-ui/.github/workflows/ci.ymlapps/agent-chat-ui/.gitignoreapps/agent-chat-ui/.prettierignoreapps/agent-chat-ui/LICENSEapps/agent-chat-ui/LOCAL.mdapps/agent-chat-ui/README.mdapps/agent-chat-ui/components.jsonapps/agent-chat-ui/eslint.config.jsapps/agent-chat-ui/next.config.mjsapps/agent-chat-ui/package.jsonapps/agent-chat-ui/postcss.config.mjsapps/agent-chat-ui/prettier.config.jsapps/agent-chat-ui/src/app/api/[..._path]/route.tsapps/agent-chat-ui/src/app/globals.cssapps/agent-chat-ui/src/app/layout.tsxapps/agent-chat-ui/src/app/page.tsxapps/agent-chat-ui/src/components/icons/github.tsxapps/agent-chat-ui/src/components/icons/langgraph.tsxapps/agent-chat-ui/src/components/thread/ContentBlocksPreview.tsxapps/agent-chat-ui/src/components/thread/MultimodalPreview.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/components/inbox-item-input.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-actions-view.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-id.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/components/tool-call-table.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/index.tsxapps/agent-chat-ui/src/components/thread/agent-inbox/types.tsapps/agent-chat-ui/src/components/thread/agent-inbox/utils.tsapps/agent-chat-ui/src/components/thread/artifact.tsxapps/agent-chat-ui/src/components/thread/history/index.tsxapps/agent-chat-ui/src/components/thread/index.tsxapps/agent-chat-ui/src/components/thread/markdown-styles.cssapps/agent-chat-ui/src/components/thread/markdown-text.tsxapps/agent-chat-ui/src/components/thread/messages/ai.tsxapps/agent-chat-ui/src/components/thread/messages/generic-interrupt.tsxapps/agent-chat-ui/src/components/thread/messages/human.tsxapps/agent-chat-ui/src/components/thread/messages/shared.tsxapps/agent-chat-ui/src/components/thread/messages/tool-calls.tsxapps/agent-chat-ui/src/components/thread/syntax-highlighter.tsxapps/agent-chat-ui/src/components/thread/tooltip-icon-button.tsxapps/agent-chat-ui/src/components/thread/utils.tsapps/agent-chat-ui/src/components/ui/avatar.tsxapps/agent-chat-ui/src/components/ui/button.tsxapps/agent-chat-ui/src/components/ui/card.tsxapps/agent-chat-ui/src/components/ui/input.tsxapps/agent-chat-ui/src/components/ui/label.tsxapps/agent-chat-ui/src/components/ui/password-input.tsxapps/agent-chat-ui/src/components/ui/separator.tsxapps/agent-chat-ui/src/components/ui/sheet.tsxapps/agent-chat-ui/src/components/ui/skeleton.tsxapps/agent-chat-ui/src/components/ui/sonner.tsxapps/agent-chat-ui/src/components/ui/switch.tsxapps/agent-chat-ui/src/components/ui/textarea.tsxapps/agent-chat-ui/src/components/ui/tooltip.tsxapps/agent-chat-ui/src/hooks/use-file-upload.tsxapps/agent-chat-ui/src/hooks/useMediaQuery.tsxapps/agent-chat-ui/src/lib/agent-inbox-interrupt.tsapps/agent-chat-ui/src/lib/api-key.tsxapps/agent-chat-ui/src/lib/ensure-tool-responses.tsapps/agent-chat-ui/src/lib/multimodal-utils.tsapps/agent-chat-ui/src/lib/utils.tsapps/agent-chat-ui/src/providers/Stream.tsxapps/agent-chat-ui/src/providers/Thread.tsxapps/agent-chat-ui/src/providers/client.tsapps/agent-chat-ui/tailwind.config.jsapps/agent-chat-ui/tsconfig.jsondocs/hitl.mddocs/roadmap.mdexamples/hitl_basic.pyscripts/run.pyscripts/run_agent_chat_ui.shsrc/langgraph_graph/__init__.pysrc/langgraph_graph/graph.pysrc/langgraph_graph/hitl.pytests/agent/__init__.pytests/agent/test_hitl.py
| - **Agent HITL interrupt / resume:** `act` interrupts with an Agent Chat UI | ||
| HITLRequest (`action_requests` + `review_configs`). Resume with | ||
| `graph.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=cfg)` | ||
| (or `reject` / `edit`). Legacy boolean `resume=True|False` still works. |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
rg -n -C 4 'build_graph|MemorySaver|Command\(resume|thread_id|graph\.invoke' \
AGENTS.md README.md docs examples srcRepository: jnyross/langgraph-graph
Length of output: 38996
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf 'AGENTS.md around exports and resume example:\n'
sed -n '35,50p;140,160p' AGENTS.md
printf '\nlanggraph docs availability and interrupt examples:\n'
python3 - <<'PY'
try:
import langgraph
print("langgraph imported", getattr(langgraph, "__version__", ""))
except Exception as e:
print("langgraph import unavailable:", type(e).__name__, e)
PY
printf '\nRelevant source snippets:\n'
sed -n '125,155p' src/langgraph_graph/graph.py
sed -n '1,15p;40,50p' src/langgraph_graph/__init__.pyRepository: jnyross/langgraph-graph
Length of output: 4043
🌐 Web query:
LangGraph Python Command resume requires checkpointer thread_id invoke config
💡 Result:
In LangGraph, you can resume execution from a checkpointer by invoking the graph using the same thread_id that was used during the initial execution [1][2][3]. To resume: 1. Persistence Configuration: Ensure your graph is compiled with a checkpointer (e.g., MemorySaver, SqliteSaver) [2][4]. 2. Thread ID: When invoking the graph, provide the same thread_id in the configuration dictionary. This identifier tells LangGraph which persisted state to load [1][5][6]. 3. Invocation: Pass None (or a Command object if handling interruptions) as the input during the invocation [3][6]. Do not pass the original state as input, as this will trigger a new graph execution from the entry node instead of resuming from the last checkpoint [3]. Example of resuming execution: config = {"configurable": {"thread_id": "your-thread-id"}} # Pass None to resume from the latest checkpoint result = graph.invoke(None, config=config) When dealing with interruptions (such as human-in-the-loop workflows), you can use Command(resume=...) to pass a value back into the graph at the point where it was interrupted [6]. Important Considerations: - Checkpoint IDs: You generally do not need to pass a checkpoint_id to resume from the latest state [3]. Passing a specific checkpoint_id is typically reserved for "time travel" scenarios, where you wish to re-run or branch from a specific historical point rather than simply continuing from the most recent one [7][5][8]. - State: If you provide a new, non-None input, LangGraph treats it as a new invocation and maps that input into the state, starting the graph from the beginning [3]. To continue seamlessly, let the runtime manage the existing state via the provided thread_id [3].
Citations:
- 1: https://docs.langchain.com/oss/python/langgraph/checkpointers
- 2: https://docs.langchain.com/oss/python/langgraph/persistence
- 3: https://forum.langchain.com/t/can-we-resume-from-the-checkpoint-and-continue-running-at-the-interruption-point-instead-of-starting-from-the-first-node/1240
- 4: http://docs.langchain.com/oss/python/langgraph/add-memory
- 5: https://github.com/langchain-ai/langgraph/blob/main/libs/checkpoint/README.md
- 6: https://docs.langchain.com/oss/python/langgraph/interrupts
- 7: https://docs.langchain.com/oss/python/langgraph/use-time-travel
- 8: https://github.com/langchain-ai/langgraph/blob/main/docs/docs/concepts/persistence.md
Make the direct resume example use build_graph() with thread_id.
As shown earlier, the module-level graph has no custom checkpointer while build_graph() provides MemorySaver for scripts. Resume with the same checkpointer-backed instance plus the same configurable.thread_id used for the paused run, e.g. graph = build_graph(), cfg = {"configurable": {"thread_id": ...}}, then invoke the initial run and Command(resume=...) with the same cfg.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@AGENTS.md` around lines 154 - 157, Update the Agent HITL interrupt/resume
example to construct the graph via build_graph() and configure a stable
configurable.thread_id. Show the initial invocation and subsequent
Command(resume=...) invocation using the same graph instance and cfg, preserving
the existing approve/reject/edit decision examples.
Sources: Coding guidelines, MCP tools
| node_modules | ||
| .next | ||
| .git | ||
| .env No newline at end of file |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Ignore all dotenv variants.
.env.local, .env.production, and .env.production.local can enter the Docker build context. A remote builder can receive their secrets.
Proposed fix
-.env
+.env*
+!.env.example📝 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.
| .env | |
| .env* | |
| !.env.example |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/agent-chat-ui/.dockerignore` at line 4, Update the Docker ignore rules
around the existing .env entry to exclude all dotenv file variants, including
.env.local, .env.production, and .env.production.local, so none are included in
the Docker build context.
| name: CI | ||
|
|
||
| on: | ||
| push: | ||
| branches: ["main"] | ||
| pull_request: | ||
| workflow_dispatch: # Allows triggering the workflow manually in GitHub UI |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Move the GitHub configuration files to repository-root .github.
GitHub only discovers workflow files from the repository-root .github/workflows directory. Dependabot only reads the repository-root .github/dependabot.yml file. These nested files will not run or configure updates. (docs.github.com)
apps/agent-chat-ui/.github/workflows/ci.yml#L3-L9: Move this workflow to.github/workflows/. Update each command to run fromapps/agent-chat-ui.apps/agent-chat-ui/.github/dependabot.yml#L1-L4: Merge this into.github/dependabot.yml. Set the npmdirectoryto/apps/agent-chat-ui.
📍 Affects 2 files
apps/agent-chat-ui/.github/workflows/ci.yml#L3-L9(this comment)apps/agent-chat-ui/.github/dependabot.yml#L1-L4
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/agent-chat-ui/.github/workflows/ci.yml` around lines 3 - 9, Move
apps/agent-chat-ui/.github/workflows/ci.yml to the repository-root
.github/workflows directory and update every command to execute from
apps/agent-chat-ui. Merge apps/agent-chat-ui/.github/dependabot.yml into the
repository-root .github/dependabot.yml, setting its npm directory to
/apps/agent-chat-ui.
| const date = unknownToPrettyDate(value); | ||
| if (date) { | ||
| valueStr = date; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect unknownToPrettyDate and all of its call sites.
fd -t f 'utils.ts' apps/agent-chat-ui/src --exec rg -n -C 6 'unknownToPrettyDate' {} \;
rg -n -C 3 'unknownToPrettyDate' apps/agent-chat-ui/srcRepository: jnyross/langgraph-graph
Length of output: 4102
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== utils.ts relevant section =="
nl -ba apps/agent-chat-ui/src/components/thread/agent-inbox/utils.ts | sed -n '55,92p'
echo
echo "== tool-call-table.tsx relevant section =="
nl -ba apps/agent-chat-ui/src/components/thread/agent-inbox/components/tool-call-table.tsx | sed -n '15,40p'
echo
echo "== state-view.tsx relevant section =="
nl -ba apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx | sed -n '72,82p'
echo
echo "== JS date parsing behavior for representative inputs =="
node - <<'JS'
const inputs = [5, -1, "1", "25", "2025-08-01", "not a date", new Date()];
for (const input of inputs) {
const raw = new Date(input);
const guard = Object.prototype.toString.call(input) === "[object Date]" || raw;
const iso = raw.toISOString();
const dateOnly = typeof input === "string" && /^\d{4}-\d{2}-\d{2}(T|$)/.test(input);
console.log(JSON.stringify({input: String(input), raw, valueOf: raw.valueOf(), guard, iso, dateOnly}));
}
JS
echo
echo "== package date formatter dependency =="
fd -t f 'package.json' apps/agent-chat-ui package.json | while read -r f; do
echo "-- ${f#"$PWD"/}"
rg -n '"date-fns"|date-fns' "$f" || true
doneRepository: jnyross/langgraph-graph
Length of output: 233
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== utils.ts relevant section =="
awk '{printf "%6d\t%s\n", NR, $0}' apps/agent-chat-ui/src/components/thread/agent-inbox/utils.ts | sed -n '55,92p'
echo
echo "== tool-call-table.tsx relevant section =="
awk '{printf "%6d\t%s\n", NR, $0}' apps/agent-chat-ui/src/components/thread/agent-inbox/components/tool-call-table.tsx | sed -n '15,40p'
echo
echo "== state-view.tsx relevant section =="
awk '{printf "%6d\t%s\n", NR, $0}' apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx | sed -n '72,82p'
echo
echo "== JS date parsing behavior for representative inputs =="
node - <<'JS'
const inputs = [5, -1, "1", "25", "2025-08-01", "not a date", new Date()];
for (const input of inputs) {
const raw = new Date(input);
const guard = Object.prototype.toString.call(input) === "[object Date]" || raw;
const iso = raw.toISOString();
const dateOnly = typeof input === "string" && /^\d{4}-\d{2}-\d{2}(T|$)/.test(input);
console.log(JSON.stringify({input: String(input), raw, valueOf: raw.valueOf(), guard, iso, dateOnly}));
}
JS
echo
echo "== package date formatter dependency =="
fd -t f 'package.json' apps/agent-chat-ui package.json | while read -r f; do
echo "-- ${f#"$PWD"/}"
rg -n '"date-fns"|date-fns' "$f" || true
doneRepository: jnyross/langgraph-graph
Length of output: 3893
Restrict date formatting to legitimate date values.
new Date(input as string) is truthy for any value that is not Invalid Date, so unknownToPrettyDate() formats numbers and short numeric strings as dates. This replaces integer argument values in tool-call-table.tsx and generic values in state-view.tsx with epoch-derived output unless the date branch checks for real Date instances or valid date-like strings before calling format().
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/agent-chat-ui/src/components/thread/agent-inbox/components/tool-call-table.tsx`
around lines 25 - 28, Update the date-handling branch in the tool-call table
around unknownToPrettyDate so it only formats legitimate Date instances or valid
date-like strings, not numbers or short numeric strings. Add the same guard to
the corresponding date formatting path in state-view.tsx, preserving raw values
when the input is not date-like.
| const resumeRun = (decisions: Decision[]): boolean => { | ||
| try { | ||
| thread.submit( | ||
| {}, | ||
| { | ||
| command: { | ||
| resume: { | ||
| decisions, | ||
| }, | ||
| }, | ||
| }, | ||
| ); | ||
| return true; | ||
| } catch (error) { | ||
| console.error("Error sending human response", error); | ||
| return false; | ||
| } | ||
| }; |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Resume submissions are not awaited, so failures escape and success is reported early. Both call sites wrap the LangGraph stream submit call in try/catch without awaiting it. The call returns a promise, so a rejection becomes an unhandled rejection, the success toast appears before the run resumes, and local decision state is cleared even when the resume fails.
apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx#L87-L104: makeresumeRunasync,await thread.submit(...), and awaitresumeRunat Line 142 before the success toast andsetStreamFinished(true).apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-actions-view.tsx#L202-L250: makehandleSubmitAllasync,await stream.submit(...), and clearaddressedActionsonly after the promise resolves. Apply the same change tohandleApproveAllat Lines 170-200.
📍 Affects 2 files
apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx#L87-L104(this comment)apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-actions-view.tsx#L202-L250
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx`
around lines 87 - 104, Await resume submissions before reporting success: make
resumeRun async and await thread.submit, then await resumeRun before showing the
success toast or calling setStreamFinished(true) in use-interrupted-actions.tsx.
In thread-actions-view.tsx, make handleSubmitAll and handleApproveAll async,
await stream.submit, and clear addressedActions only after submission resolves.
| if (isToolResult && hideToolCalls) { | ||
| return null; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Hiding tool calls also hides the HITL interrupt form.
When hideToolCalls is enabled and the last message is a tool result, this early return skips the whole subtree, including the Interrupt block at Lines 155-159. The user then cannot approve, edit, or reject the pending action, and the run stays blocked with no visible control.
Render the interrupt even when the tool result body is hidden.
🐛 Proposed fix
- if (isToolResult && hideToolCalls) {
- return null;
- }
+ if (isToolResult && hideToolCalls) {
+ return (
+ <Interrupt
+ interrupt={threadInterrupt}
+ isLastMessage={isLastMessage}
+ hasNoAIOrToolMessages={hasNoAIOrToolMessages}
+ />
+ );
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/agent-chat-ui/src/components/thread/messages/ai.tsx` around lines 145 -
147, Update the early return in the message-rendering component around
isToolResult and hideToolCalls so hiding the tool-result body does not suppress
the Interrupt block. Keep the tool call content hidden while still rendering
Interrupt when a pending HITL action exists, preserving the approve, edit, and
reject controls.
| const newBlocks = uniqueFiles.length | ||
| ? await Promise.all(uniqueFiles.map(fileToContentBlock)) | ||
| : []; | ||
| setContentBlocks((prev) => [...prev, ...newBlocks]); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Unhandled fileToContentBlock rejections in three upload paths. All three paths call Promise.all over fileToContentBlock with no rejection handling. fileToContentBlock awaits fileToBase64, which rejects when FileReader emits onerror. One failed file then discards the whole batch and raises an unhandled promise rejection. The user sees no error.
apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L75-L78: wrap thePromise.allinhandleFileUploadwithtry/catch, show atoast.error, and keep thee.target.value = ""reset in afinallyblock.apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L135-L137: wrap thePromise.allinhandleWindowDropwithtry/catch. This handler is anasyncwindow listener, so an uncaught rejection escapes entirely.apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L255-L256: wrap thePromise.allinhandlePastewithtry/catch.
Consider Promise.allSettled so that one unreadable file does not drop the readable files in the same batch.
Also note that fileToBase64 in apps/agent-chat-ui/src/lib/multimodal-utils.ts at Line 52 assigns reader.onerror = reject, which rejects with a ProgressEvent rather than an Error. Reject with an Error so the catch blocks can report a useful message.
🛡️ Proposed fix for the first site
- const newBlocks = uniqueFiles.length
- ? await Promise.all(uniqueFiles.map(fileToContentBlock))
- : [];
- setContentBlocks((prev) => [...prev, ...newBlocks]);
- e.target.value = "";
+ try {
+ const results = uniqueFiles.length
+ ? await Promise.allSettled(uniqueFiles.map(fileToContentBlock))
+ : [];
+ const newBlocks = results
+ .filter((r) => r.status === "fulfilled")
+ .map((r) => r.value);
+ if (results.some((r) => r.status === "rejected")) {
+ toast.error("Some files could not be read. Please try again.");
+ }
+ setContentBlocks((prev) => [...prev, ...newBlocks]);
+ } finally {
+ e.target.value = "";
+ }📍 Affects 1 file
apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L75-L78(this comment)apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L135-L137apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L255-L256
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/agent-chat-ui/src/hooks/use-file-upload.tsx` around lines 75 - 78,
Handle file conversion failures in handleFileUpload
(apps/agent-chat-ui/src/hooks/use-file-upload.tsx:75-78), handleWindowDrop
(apps/agent-chat-ui/src/hooks/use-file-upload.tsx:135-137), and handlePaste
(apps/agent-chat-ui/src/hooks/use-file-upload.tsx:255-256) with try/catch, using
Promise.allSettled where appropriate so readable files are retained; display
conversion errors via toast.error, and keep the input reset in
handleFileUpload’s finally block. Update fileToBase64 in
apps/agent-chat-ui/src/lib/multimodal-utils.ts:52 to reject with an Error
containing a useful message instead of the raw ProgressEvent.
| export function isBase64ContentBlock( | ||
| block: unknown, | ||
| ): block is ContentBlock.Multimodal.Data { | ||
| if (typeof block !== "object" || block === null || !("type" in block)) | ||
| return false; | ||
| // file type (legacy) | ||
| if ( | ||
| (block as { type: unknown }).type === "file" && | ||
| "mimeType" in block && | ||
| typeof (block as { mimeType?: unknown }).mimeType === "string" && | ||
| ((block as { mimeType: string }).mimeType.startsWith("image/") || | ||
| (block as { mimeType: string }).mimeType === "application/pdf") | ||
| ) { | ||
| return true; | ||
| } | ||
| // image type (new) | ||
| if ( | ||
| (block as { type: unknown }).type === "image" && | ||
| "mimeType" in block && | ||
| typeof (block as { mimeType?: unknown }).mimeType === "string" && | ||
| (block as { mimeType: string }).mimeType.startsWith("image/") | ||
| ) { | ||
| return true; | ||
| } | ||
| return false; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Verify data in the isBase64ContentBlock type guard.
The guard narrows to ContentBlock.Multimodal.Data but never checks the data field. A block that has a matching type and mimeType but no data passes. human.tsx then hands that block to MultimodalPreview, which builds a data URL from an undefined value and renders a broken image.
Check data before returning true.
🛡️ Proposed fix
export function isBase64ContentBlock(
block: unknown,
): block is ContentBlock.Multimodal.Data {
if (typeof block !== "object" || block === null || !("type" in block))
return false;
+ if (typeof (block as { data?: unknown }).data !== "string") return false;
// file type (legacy)📝 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 function isBase64ContentBlock( | |
| block: unknown, | |
| ): block is ContentBlock.Multimodal.Data { | |
| if (typeof block !== "object" || block === null || !("type" in block)) | |
| return false; | |
| // file type (legacy) | |
| if ( | |
| (block as { type: unknown }).type === "file" && | |
| "mimeType" in block && | |
| typeof (block as { mimeType?: unknown }).mimeType === "string" && | |
| ((block as { mimeType: string }).mimeType.startsWith("image/") || | |
| (block as { mimeType: string }).mimeType === "application/pdf") | |
| ) { | |
| return true; | |
| } | |
| // image type (new) | |
| if ( | |
| (block as { type: unknown }).type === "image" && | |
| "mimeType" in block && | |
| typeof (block as { mimeType?: unknown }).mimeType === "string" && | |
| (block as { mimeType: string }).mimeType.startsWith("image/") | |
| ) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| export function isBase64ContentBlock( | |
| block: unknown, | |
| ): block is ContentBlock.Multimodal.Data { | |
| if (typeof block !== "object" || block === null || !("type" in block)) | |
| return false; | |
| if (typeof (block as { data?: unknown }).data !== "string") return false; | |
| // file type (legacy) | |
| if ( | |
| (block as { type: unknown }).type === "file" && | |
| "mimeType" in block && | |
| typeof (block as { mimeType?: unknown }).mimeType === "string" && | |
| ((block as { mimeType: string }).mimeType.startsWith("image/") || | |
| (block as { mimeType: string }).mimeType === "application/pdf") | |
| ) { | |
| return true; | |
| } | |
| // image type (new) | |
| if ( | |
| (block as { type: unknown }).type === "image" && | |
| "mimeType" in block && | |
| typeof (block as { mimeType?: unknown }).mimeType === "string" && | |
| (block as { mimeType: string }).mimeType.startsWith("image/") | |
| ) { | |
| return true; | |
| } | |
| return false; | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/agent-chat-ui/src/lib/multimodal-utils.ts` around lines 58 - 83, Update
isBase64ContentBlock to validate that the matching file or image block includes
a valid data field before returning true. Preserve the existing type and
mimeType checks, and ensure blocks lacking data return false so the
ContentBlock.Multimodal.Data narrowing remains accurate.
| const [apiUrl, setApiUrl] = useQueryState("apiUrl", { | ||
| defaultValue: envApiUrl || "", | ||
| }); | ||
| const [assistantId, setAssistantId] = useQueryState("assistantId", { | ||
| defaultValue: envAssistantId || "", | ||
| }); | ||
| const [authScheme, setAuthScheme] = useQueryState("authScheme", { | ||
| defaultValue: envAuthScheme || "", | ||
| }); | ||
| const [isAgentBuilder, setIsAgentBuilder] = useState( | ||
| () => | ||
| (authScheme || envAuthScheme || "").toLowerCase() === | ||
| AGENT_BUILDER_AUTH_SCHEME, | ||
| ); | ||
|
|
||
| // For API key, use localStorage with env var fallback | ||
| const [apiKey, _setApiKey] = useState(() => { | ||
| const storedKey = getApiKey(); | ||
| return storedKey || ""; | ||
| }); | ||
|
|
||
| const setApiKey = (key: string) => { | ||
| window.localStorage.setItem("lg:chat:apiKey", key); | ||
| _setApiKey(key); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
Prevent query parameters from redirecting stored API keys.
An attacker can share a URL with an attacker-controlled apiUrl. The application loads lg:chat:apiKey and sends it to that origin. Require explicit confirmation for a new origin, or restrict API origins to a trusted allowlist. Scope stored keys by validated origin.
apps/agent-chat-ui/src/providers/Stream.tsx#L153-L176: Do not load or send the stored key untilapiUrlis trusted.apps/agent-chat-ui/src/providers/Thread.tsx#L42-L69: Apply the same origin validation before searching threads.
📍 Affects 2 files
apps/agent-chat-ui/src/providers/Stream.tsx#L153-L176(this comment)apps/agent-chat-ui/src/providers/Thread.tsx#L42-L69
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/agent-chat-ui/src/providers/Stream.tsx` around lines 153 - 176, Validate
apiUrl against a trusted origin or require explicit confirmation before loading
or sending the stored API key; scope stored keys to the validated origin rather
than using one global key. Apply this in
apps/agent-chat-ui/src/providers/Stream.tsx:153-176 around the apiUrl/apiKey
initialization, and apply the same origin validation before thread searches in
apps/agent-chat-ui/src/providers/Thread.tsx:42-69.
| if isinstance(resume_value, list) and resume_value: | ||
| first = resume_value[0] | ||
| if isinstance(first, dict) and "type" in first: | ||
| return first # type: ignore[return-value] | ||
|
|
||
| # Truthy/falsey fallback for unexpected shapes. | ||
| return {"type": "approve" if bool(resume_value) else "reject"} |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Fail closed on unrecognized resume payloads.
Line 109 maps any truthy value to approve. Several realistic shapes reach that line: a dict that has decisions with malformed entries, a dict without a type key, a non-empty tuple, or a number. Those payloads then grant an external side effect without an explicit human decision. act_node in src/langgraph_graph/graph.py invokes the tool at that point. An approval gate must reject anything it cannot parse.
🛡️ Proposed fix
if isinstance(resume_value, list) and resume_value:
first = resume_value[0]
if isinstance(first, dict) and "type" in first:
return first # type: ignore[return-value]
- # Truthy/falsey fallback for unexpected shapes.
- return {"type": "approve" if bool(resume_value) else "reject"}
+ # Unknown shapes are never treated as approval.
+ return {
+ "type": "reject",
+ "message": "Unrecognized resume payload; nothing executed.",
+ }Based on learnings: "Require human approval before external sends, spending or paid API calls, production writes, or HR/PII exports."
📝 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.
| if isinstance(resume_value, list) and resume_value: | |
| first = resume_value[0] | |
| if isinstance(first, dict) and "type" in first: | |
| return first # type: ignore[return-value] | |
| # Truthy/falsey fallback for unexpected shapes. | |
| return {"type": "approve" if bool(resume_value) else "reject"} | |
| if isinstance(resume_value, list) and resume_value: | |
| first = resume_value[0] | |
| if isinstance(first, dict) and "type" in first: | |
| return first # type: ignore[return-value] | |
| # Unknown shapes are never treated as approval. | |
| return { | |
| "type": "reject", | |
| "message": "Unrecognized resume payload; nothing executed.", | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/langgraph_graph/hitl.py` around lines 103 - 109, Update the resume-value
parsing logic in the shown handler to fail closed: only return an explicit
parsed approval or rejection, and map every unrecognized shape—including
malformed decision dictionaries, dictionaries without “type”, non-empty tuples,
and numbers—to {"type": "reject"} rather than using truthiness. Preserve valid
list-based decision parsing and ensure act_node receives rejection unless a
human decision is explicitly recognized.
Source: Learnings
Summary
Integrates Agent Chat UI as the primary human-in-the-loop surface for the
agentgraph.Backend
actinterrupts with an Agent Inbox–compatible HITLRequest (action_requests+review_configs)approve/edit/rejectsrc/langgraph_graph/hitl.pyUI
apps/agent-chat-uiclip-path→clipPathin LangGraph logo SVG) that aborted render and left the app looking like unstyled HTML./scripts/run_agent_chat_ui.shto boot the UIBrowser verification (after CSS fix)
Tests
pytest: 158 passed (tests/agent: 11)How to try
uv run langgraph dev --no-browser ./scripts/run_agent_chat_ui.sh --install # http://localhost:3000 — graph id `agent`Summary by CodeRabbit