agents
agents copied to clipboard
App crash from useAgentChat on 40x from /get-messages
When the default request to /get-messages receives a 40x response, the useAgentChat hook crashes the app. This can be common in the case where the user wants to implement authentication as shown in the readme for hono-agents:
// or with authentication
app.use(
"*",
agentsMiddleware({
options: {
// onBeforeConnect: async (req) => { // original
onBeforeRequest: async (req) => { // modified
const token = req.headers.get("authorization");
// validate token
if (!token) return new Response("Unauthorized", { status: 401 });
},
},
})
);
This is for the case where we want to gate not only the socket interactions but also the request for the messages.
Created a example reproduction repo, where it just rejects all requests to the agent. Here is the diff from the template: https://github.com/nickfujita/agent-issue-error-handling/commit/5bc6deb6ed981ea29f04ba62fa564881c1ecd0fd
Opened a PR to fix this with error handling, so it's up to the user what to do in the case of an auth failure: https://github.com/cloudflare/agents/pull/180