Skip to content
This repository was archived by the owner on Sep 5, 2026. It is now read-only.

Add Agent Chat UI for HITL approve/edit/reject - #8

Merged
jnyross merged 5 commits into
mainfrom
cursor/hitl-ui-options-38d7
Aug 7, 2026
Merged

jnyross merged 5 commits into
mainfrom
cursor/hitl-ui-options-38d7

Conversation

@jnyross

@jnyross jnyross commented Aug 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Integrates Agent Chat UI as the primary human-in-the-loop surface for the agent graph.

Backend

  • act interrupts with an Agent Inbox–compatible HITLRequest (action_requests + review_configs)
  • Resume accepts Agent Chat UI decisions: approve / edit / reject
  • Helpers in src/langgraph_graph/hitl.py
  • Clean planner fallback when the model endpoint is down

UI

  • Vendored Agent Chat UI under apps/agent-chat-ui
  • Fixed React crash (clip-path → clipPath in LangGraph logo SVG) that aborted render and left the app looking like unstyled HTML
  • ./scripts/run_agent_chat_ui.sh to boot the UI

Browser verification (after CSS fix)

hitl-ui-styled-after-css-fix.mp4

Styled landing
Styled HITL interrupt
After approve

Tests

  • pytest: 158 passed (tests/agent: 11)
  • Approve + Reject browser flows pass with styles applied

How to try

uv run langgraph dev --no-browser
./scripts/run_agent_chat_ui.sh --install
# http://localhost:3000 — graph id `agent`
Open in Web Open in Cursor 

Summary by CodeRabbit

  • New Features
    • Added the Agent Chat UI for streaming conversations, thread history, attachments, tool calls, artifacts, and responsive layouts.
    • Added human-in-the-loop approvals, edits, and rejections with support for multiple actions.
    • Added Markdown, code highlighting, math rendering, expandable results, and message editing.
    • Added image and PDF uploads with previews.
  • Documentation
    • Added setup guides for local development, deployment, environment configuration, and HITL workflows.
  • Bug Fixes
    • Improved handling of interrupted runs, rejected actions, missing tool responses, and invalid requests.

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>
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Agent Chat UI and HITL integration

Layer / File(s) Summary
Structured HITL runtime
src/langgraph_graph/..., examples/hitl_basic.py, scripts/run.py, tests/agent/test_hitl.py
The graph now emits structured HITL requests and resolves approve, edit, reject, and legacy boolean decisions. Tests cover request construction, execution, rejection, and follow-up messages.
Agent Chat UI platform
apps/agent-chat-ui/package.json, apps/agent-chat-ui/src/app/..., apps/agent-chat-ui/src/providers/..., apps/agent-chat-ui/src/components/ui/...
Added the Next.js application shell, API passthrough, stream and thread providers, configuration handling, themes, and reusable UI components.
Chat experience
apps/agent-chat-ui/src/components/thread/..., apps/agent-chat-ui/src/hooks/..., apps/agent-chat-ui/src/lib/...
Added streamed chat rendering, Markdown and tool-call views, message editing, multimodal uploads, thread history, and artifact panels.
Agent Inbox interface
apps/agent-chat-ui/src/components/thread/agent-inbox/...
Added interrupt validation, state inspection, action approval, editing, rejection, multi-action navigation, and resume controls.
Documentation and workflow support
README.md, AGENTS.md, docs/..., scripts/run_agent_chat_ui.sh, apps/agent-chat-ui/README.md
Updated development instructions and HITL documentation. Added the local UI launcher, deployment guidance, CI configuration, and roadmap updates.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.65% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding Agent Chat UI support for HITL approve, edit, and reject workflows.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/hitl-ui-options-38d7

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

cursor[bot]

This comment was marked as resolved.

cursoragent and others added 3 commits August 7, 2026 21:33
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>
cursor[bot]

This comment was marked as resolved.

@jnyross
jnyross marked this pull request as ready for review August 7, 2026 22:24

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 4 potential issues.

View 1 additional finding in Devin Review.

Open in Devin Review

Comment on lines +108 to +109
# Truthy/falsey fallback for unexpected shapes.
return {"type": "approve" if bool(resume_value) else "reject"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Suggested change
# 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."}
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +69 to 76
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)}],
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +108 to +109
# Truthy/falsey fallback for unexpected shapes.
return {"type": "approve" if bool(resume_value) else "reject"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟥 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.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +127 to +133
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟨 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.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Use descriptive link text for the setup guide.

Replace here with text that identifies the destination, such as the 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 win

Remove 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 win

Use Authorization for the bearer token.

LangGraph custom-auth examples use Authorization, and auth receives it as authorization; this example will send the token in an unstandard/non-matching Authentication header.

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 win

Restrict the edited tool name to the reviewed action.

resolve_hitl_decision accepts an arbitrary edited_action.name. Line 113 then resolves that name against ALL_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 says act-1 and the UI showed send_message. Consider rejecting an edited name that does not match tool_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 win

The doc comment does not match the behavior.

The comment promises a modality label and a Multimodal message fallback. The function returns an empty string when the content holds no text block. apps/agent-chat-ui/src/components/thread/history/index.tsx line 39 assigns that result to itemText, 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 win

Surface 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 omits getThreads, setThreads, and setThreadsLoading from the dependency array; add a comment if the mount-only fetch is intentional, because react-hooks/exhaustive-deps flags 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 win

Handle clipboard failures and clear the timer.

navigator.clipboard.writeText returns 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. The setTimeout also 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 win

Editing drops multimodal attachments.

handleSubmitEdit builds content: 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 win

Restore a keyboard focus indicator on the shared input.

outline-none removes the default focus outline, and this outline-none uses does not provide a focus-visible: equivalent. Add the same keyboard focus style used by the nearby UI inputs, such as focus-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 win

Register .scrollbar-pretty where this app uses Tailwind.

globals.css imports Tailwind v4 without @config, so apps/agent-chat-ui/tailwind.config.js is not loaded by this app and components: { ".scrollbar-pretty": ... } has no effect here. Define .scrollbar-pretty in globals.css with @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 win

Remove 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 win

Honor the functional setOpen argument.

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 win

Move next into dependencies.

The start script runs next start in production. next is declared in devDependencies at Line 76. An install with --production or NODE_ENV=production omits next, and next start then fails. react and react-dom are 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 win

Align the Next lint config path with the installed Next.js version.

next is still at ^15.5.21, while eslint-config-next is pinned to 16.2.4. eslint-config-next 16 is meant for Next 16/flat config flow, and Next 16 removed next lint. If this app remains on Next 15, change the config/source to include next-eslint/Next 15 rules. If the app will upgrade to Next 16, remove next lint scripts/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 win

Guard the clipboard write.

navigator.clipboard is undefined in non-secure contexts, and writeText returns a promise that can reject. The current code throws or produces an unhandled rejection, and it still sets copied to true after 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 win

Make the error inspection safe.

error is typed any. If the thrown value is a string, null, or a number, "message" in error throws a TypeError inside the catch block. 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 win

Associate 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 related Textarea. Add an id on each Textarea and use a Label with htmlFor, or add aria-label to each Textarea.

♿ 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 win

Non-string tool content renders as [object Object].

The try block only runs when message.content is a string. When a tool returns structured content blocks, message.content is an array, parsedContent stays undefined, isJsonContent stays false, and Line 86 falls through to String(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 win

The guard validates only the first array element but narrows the whole array.

Line 7 selects value[0] when value is an array, and every later check runs against that single element. The return type still asserts Interrupt<HITLRequest>[], so callers treat all entries as validated.

ThreadView in apps/agent-chat-ui/src/components/thread/agent-inbox/index.tsx maps over every entry (Lines 70-93) and forwards each one to ThreadActionsView. A malformed later entry yields an empty action_requests list 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 the default case 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 value

Use filter and map instead of reduce.

The reduce call 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 tradeoff

Prefer a discriminated union over throwing during render.

CommandBar throws 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 value

Replace 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.py line 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 win

Add coverage for unparseable resume payloads.

The parametrized cases cover approve, edit, reject, and booleans. They do not cover the fallback branch in _first_decision at src/langgraph_graph/hitl.py line 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 value

Share the resume helper with the example.

examples/hitl_basic.py lines 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_human and the resume block into src/langgraph_graph/hitl.py or 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 win

Log the swallowed planner exception.

The bare except Exception hides 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 value

Resolve the missing Sheet description in dev.

history/index.tsx renders SheetTitle without SheetDescription. This can trigger Radix’s “Missing Description or aria-describedby={undefined}” warning in non-production environments. Add a visually hidden description in SheetHeader, or pass aria-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 win

Use the active global stylesheet for shadcn configuration.

components.json points shadcn at src/index.css, but the app only imports ./globals.css from apps/agent-chat-ui/src/app/layout.tsx; there is no src/index.css. Set this to src/app/globals.css so 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 win

Remove the shadowed isDuplicate copy.

handlePaste defines a local isDuplicate that 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 pass contentBlocks.

♻️ 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 win

Correct the tool_calls guard.

The comment states the guard skips AI messages without tool calls. The condition does not do that. If tool_calls is undefined, message.tool_calls?.length is undefined, and undefined === 0 is false. 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 win

The supported MIME type list is declared twice. multimodal-utils.ts builds its own supportedImageTypes and supportedFileTypes arrays, and use-file-upload.tsx exports SUPPORTED_FILE_TYPES with 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 single SUPPORTED_IMAGE_TYPES constant here, derive supportedFileTypes from 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-utils and re-export SUPPORTED_FILE_TYPES if external consumers depend on the current name.

Place the constants in multimodal-utils.ts, because the hook already imports fileToContentBlock from 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 win

Validate 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. format then throws a RangeError, and the catch block returns undefined. 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 value

Use RefObject instead of the deprecated React ref type.

React.MutableRefObject<Record<string, string>> is deprecated under @types/react 19. Use React.RefObject<Record<string, string>> in use-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 value

Convert numbers to strings before passing them to MarkdownText.

This branch accepts number but casts it with as string. MarkdownText forwards its child to ReactMarkdown, 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 win

Reset 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, activeInterruptIndex is kept, and the UI shows an unrelated action at the same position. Depend on interrupts instead.

♻️ 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 win

Handle clipboard write failures.

navigator.clipboard.writeText returns 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 value

Collapse 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} />. The toolCallsHaveContents check 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 value

Import the Prism theme from the ESM style bundle.

typescript and python use dist/esm/languages/prism/..., but coldarkDark uses dist/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 of react-syntax-highlighter from 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

📥 Commits

Reviewing files that changed from the base of the PR and between 76d804f and 262c8dd.

⛔ Files ignored due to path filters (2)
  • apps/agent-chat-ui/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • apps/agent-chat-ui/src/app/favicon.ico is excluded by !**/*.ico
📒 Files selected for processing (84)
  • .gitignore
  • AGENTS.md
  • README.md
  • apps/agent-chat-ui/.codespellignore
  • apps/agent-chat-ui/.dockerignore
  • apps/agent-chat-ui/.env.example
  • apps/agent-chat-ui/.github/dependabot.yml
  • apps/agent-chat-ui/.github/workflows/ci.yml
  • apps/agent-chat-ui/.gitignore
  • apps/agent-chat-ui/.prettierignore
  • apps/agent-chat-ui/LICENSE
  • apps/agent-chat-ui/LOCAL.md
  • apps/agent-chat-ui/README.md
  • apps/agent-chat-ui/components.json
  • apps/agent-chat-ui/eslint.config.js
  • apps/agent-chat-ui/next.config.mjs
  • apps/agent-chat-ui/package.json
  • apps/agent-chat-ui/postcss.config.mjs
  • apps/agent-chat-ui/prettier.config.js
  • apps/agent-chat-ui/src/app/api/[..._path]/route.ts
  • apps/agent-chat-ui/src/app/globals.css
  • apps/agent-chat-ui/src/app/layout.tsx
  • apps/agent-chat-ui/src/app/page.tsx
  • apps/agent-chat-ui/src/components/icons/github.tsx
  • apps/agent-chat-ui/src/components/icons/langgraph.tsx
  • apps/agent-chat-ui/src/components/thread/ContentBlocksPreview.tsx
  • apps/agent-chat-ui/src/components/thread/MultimodalPreview.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/components/inbox-item-input.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/components/state-view.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-actions-view.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-id.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/components/tool-call-table.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/hooks/use-interrupted-actions.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/index.tsx
  • apps/agent-chat-ui/src/components/thread/agent-inbox/types.ts
  • apps/agent-chat-ui/src/components/thread/agent-inbox/utils.ts
  • apps/agent-chat-ui/src/components/thread/artifact.tsx
  • apps/agent-chat-ui/src/components/thread/history/index.tsx
  • apps/agent-chat-ui/src/components/thread/index.tsx
  • apps/agent-chat-ui/src/components/thread/markdown-styles.css
  • apps/agent-chat-ui/src/components/thread/markdown-text.tsx
  • apps/agent-chat-ui/src/components/thread/messages/ai.tsx
  • apps/agent-chat-ui/src/components/thread/messages/generic-interrupt.tsx
  • apps/agent-chat-ui/src/components/thread/messages/human.tsx
  • apps/agent-chat-ui/src/components/thread/messages/shared.tsx
  • apps/agent-chat-ui/src/components/thread/messages/tool-calls.tsx
  • apps/agent-chat-ui/src/components/thread/syntax-highlighter.tsx
  • apps/agent-chat-ui/src/components/thread/tooltip-icon-button.tsx
  • apps/agent-chat-ui/src/components/thread/utils.ts
  • apps/agent-chat-ui/src/components/ui/avatar.tsx
  • apps/agent-chat-ui/src/components/ui/button.tsx
  • apps/agent-chat-ui/src/components/ui/card.tsx
  • apps/agent-chat-ui/src/components/ui/input.tsx
  • apps/agent-chat-ui/src/components/ui/label.tsx
  • apps/agent-chat-ui/src/components/ui/password-input.tsx
  • apps/agent-chat-ui/src/components/ui/separator.tsx
  • apps/agent-chat-ui/src/components/ui/sheet.tsx
  • apps/agent-chat-ui/src/components/ui/skeleton.tsx
  • apps/agent-chat-ui/src/components/ui/sonner.tsx
  • apps/agent-chat-ui/src/components/ui/switch.tsx
  • apps/agent-chat-ui/src/components/ui/textarea.tsx
  • apps/agent-chat-ui/src/components/ui/tooltip.tsx
  • apps/agent-chat-ui/src/hooks/use-file-upload.tsx
  • apps/agent-chat-ui/src/hooks/useMediaQuery.tsx
  • apps/agent-chat-ui/src/lib/agent-inbox-interrupt.ts
  • apps/agent-chat-ui/src/lib/api-key.tsx
  • apps/agent-chat-ui/src/lib/ensure-tool-responses.ts
  • apps/agent-chat-ui/src/lib/multimodal-utils.ts
  • apps/agent-chat-ui/src/lib/utils.ts
  • apps/agent-chat-ui/src/providers/Stream.tsx
  • apps/agent-chat-ui/src/providers/Thread.tsx
  • apps/agent-chat-ui/src/providers/client.ts
  • apps/agent-chat-ui/tailwind.config.js
  • apps/agent-chat-ui/tsconfig.json
  • docs/hitl.md
  • docs/roadmap.md
  • examples/hitl_basic.py
  • scripts/run.py
  • scripts/run_agent_chat_ui.sh
  • src/langgraph_graph/__init__.py
  • src/langgraph_graph/graph.py
  • src/langgraph_graph/hitl.py
  • tests/agent/__init__.py
  • tests/agent/test_hitl.py

Comment thread AGENTS.md
Comment on lines +154 to +157
- **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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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 src

Repository: 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__.py

Repository: 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:


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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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.

Suggested change
.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.

Comment on lines +3 to +9
name: CI

on:
push:
branches: ["main"]
pull_request:
workflow_dispatch: # Allows triggering the workflow manually in GitHub UI

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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 from apps/agent-chat-ui.
  • apps/agent-chat-ui/.github/dependabot.yml#L1-L4: Merge this into .github/dependabot.yml. Set the npm directory to /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.

Comment on lines +25 to +28
const date = unknownToPrettyDate(value);
if (date) {
valueStr = date;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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/src

Repository: 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
done

Repository: 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
done

Repository: 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.

Comment on lines +87 to +104
const resumeRun = (decisions: Decision[]): boolean => {
try {
thread.submit(
{},
{
command: {
resume: {
decisions,
},
},
},
);
return true;
} catch (error) {
console.error("Error sending human response", error);
return false;
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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: make resumeRun async, await thread.submit(...), and await resumeRun at Line 142 before the success toast and setStreamFinished(true).
  • apps/agent-chat-ui/src/components/thread/agent-inbox/components/thread-actions-view.tsx#L202-L250: make handleSubmitAll async, await stream.submit(...), and clear addressedActions only after the promise resolves. Apply the same change to handleApproveAll at 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.

Comment on lines +145 to +147
if (isToolResult && hideToolCalls) {
return null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +75 to +78
const newBlocks = uniqueFiles.length
? await Promise.all(uniqueFiles.map(fileToContentBlock))
: [];
setContentBlocks((prev) => [...prev, ...newBlocks]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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 the Promise.all in handleFileUpload with try/catch, show a toast.error, and keep the e.target.value = "" reset in a finally block.
  • apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L135-L137: wrap the Promise.all in handleWindowDrop with try/catch. This handler is an async window listener, so an uncaught rejection escapes entirely.
  • apps/agent-chat-ui/src/hooks/use-file-upload.tsx#L255-L256: wrap the Promise.all in handlePaste with try/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-L137
  • apps/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.

Comment on lines +58 to +83
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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

Comment on lines +153 to +176
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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 until apiUrl is 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.

Comment on lines +103 to +109
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"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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.

Suggested change
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

@jnyross
jnyross merged commit 90172e1 into main Aug 7, 2026
3 checks passed
@jnyross
jnyross deleted the cursor/hitl-ui-options-38d7 branch August 8, 2026 08:55
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants