Repository navigation
fix(agent): authenticate "Thinking" button in shared/embedded chat via beta token (#14985) - #15238
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThis PR adds a shared-mode agent logs endpoint and updates the frontend trace flow to use it when embedding. The backend resolves SDK tokens to agent IDs, reads per-message logs from Redis, and the hook, service, API helper, and timeline now branch on ChangesShared Agent Log Fetching
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
api/apps/restful_apis/bot_api.py (1)
381-390: ⚡ Quick winAdd auth-failure logs in the new shared trace flow.
This new route returns auth errors but does not log denied attempts, unlike nearby endpoints. Add warning logs for missing/invalid beta token and missing token-to-agent binding to keep audit/debug parity.
As per coding guidelines, "**/*.py: Add logging for new flows".
🤖 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 `@api/apps/restful_apis/bot_api.py` around lines 381 - 390, Add warning logs for authorization failures in the new shared trace flow: when _get_sdk_authorization_token() returns no token, log a warning (e.g., logger.warning) that an SDK authorization token was missing for the request; when thread_pool_exec(APIToken.query, beta=token) returns no objs, log a warning that the provided beta token is invalid along with the token or request context; and when objs[0].dialog_id (agent_id) is falsy, log a warning that the API token is not bound to an agent specifying the token/obj id. Insert these logger.warning calls immediately before each get_error_data_result return to mirror nearby endpoints (use the existing logger variable in this module).
🤖 Prompt for all review comments with 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.
Nitpick comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 381-390: Add warning logs for authorization failures in the new
shared trace flow: when _get_sdk_authorization_token() returns no token, log a
warning (e.g., logger.warning) that an SDK authorization token was missing for
the request; when thread_pool_exec(APIToken.query, beta=token) returns no objs,
log a warning that the provided beta token is invalid along with the token or
request context; and when objs[0].dialog_id (agent_id) is falsy, log a warning
that the API token is not bound to an agent specifying the token/obj id. Insert
these logger.warning calls immediately before each get_error_data_result return
to mirror nearby endpoints (use the existing logger variable in this module).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 63667dd9-ce14-4da5-94c3-b92e78d31b55
📒 Files selected for processing (5)
api/apps/restful_apis/bot_api.pyweb/src/hooks/use-agent-request.tsweb/src/pages/agent/log-sheet/workflow-timeline.tsxweb/src/services/agent-service.tsweb/src/utils/api.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with 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.
Inline comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 390-393: The warnings currently log token[:10], which exposes
secret material; replace any direct token slicing (token[:10]) in the
logger.warning calls related to agent_bot_logs/shared_id with a non-reversible
fingerprint instead (e.g., compute a SHA-256 digest of token and log the hex
prefix or use an HMAC with a service-wide key) or omit token-derived content
entirely; update all occurrences (the logger.warning calls referencing token and
shared_id) to compute the fingerprint once and log that fingerprint and
shared_id rather than any substring of the token.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a19d83eb-c0f7-48ae-aa22-705cc24de137
📒 Files selected for processing (1)
api/apps/restful_apis/bot_api.py
|
Hi, |
yeah, I think so. |
…a beta token (#14985) (#15238) ## Summary Fixes #14985 — clicking the **Thinking** button in a shared/embedded chat returns 401 and bounces the user to the login page, even though the same share page can chat with the agent just fine. ## Root cause In shared chat, `useGetSharedChatSearchParams` binds `conversationId` to the URL's `shared_id` query param — which is the **beta APIToken**, not the real agent id. That `conversationId` propagates through the component tree: ```tsx <WorkFlowTimeline canvasId={conversationId}> → useFetchMessageTrace(canvasId) → GET /api/v1/agents/<sharedId>/logs/<messageId> ``` But `/agents/<agent_id>/logs/<message_id>` is decorated with `@login_required` (`api/apps/restful_apis/agent_api.py:842-846`). The share page only holds the beta token — there is no session JWT — so the request 401s and quart-auth redirects to the login page. The reporter's server log matches exactly: ``` load_user from jwt got exception No b'.' found in value load_user: No APIToken found for token=ULG10SWG3E... Unauthorized request (quart_auth) GET /api/v1/agents/394013f8d42211f0bad6123fa55e8ed9/logs/96fd72e2-... 1.1 401 ``` The `394013f8...` segment in the URL is the `shared_id` (beta token), not an actual agent id. `_load_user` already accepts the regular `APIToken.token` field, but not `APIToken.beta`, by design — beta is a much weaker share-link credential than a personal API key. The sibling endpoints `/agentbots/<id>/completions` and `/agentbots/<id>/inputs` already use the right auth pattern for this scope (beta-token via `_get_sdk_authorization_token` → `APIToken.query(beta=token)`). Trace just didn't have a parallel. ## Fix ### Backend (`api/apps/restful_apis/bot_api.py`) Added a beta-token sibling endpoint: ``` GET /api/v1/agentbots/<shared_id>/logs/<message_id> ``` - Same auth shape as the existing `agentbots` endpoints. - The `<shared_id>` path segment is a client-supplied label only. The real `agent_id` used to build the Redis key (`<agent_id>-<message_id>-logs`) is taken from `APIToken.dialog_id` on the looked-up token, so the endpoint never trusts client-supplied identifiers for the data lookup. - Returns the same `{data: ...}` shape as the existing `/agents/<id>/logs/<message_id>` endpoint, so the frontend doesn't need to reshape the response. ### Frontend - `web/src/utils/api.ts`: added `sharedTrace(sharedId, messageId)` URL builder. - `web/src/services/agent-service.ts`: added `fetchSharedTrace({ shared_id, message_id })`. - `web/src/hooks/use-agent-request.ts`: `useFetchMessageTrace` takes an optional `isShare` argument. When set, it calls `fetchSharedTrace`; `isShare` is also folded into the `queryKey` so the two modes never share cached results. - `web/src/pages/agent/log-sheet/workflow-timeline.tsx`: forwards the already-existing `isShare` prop into the hook. All other existing call sites of `useFetchMessageTrace` (webhook timeline, pipeline log, dataflow result) pass no `isShare` argument → undefined → falsy → unchanged behavior. ## Test plan - [ ] In the regular Agent UI (logged-in user): open the trace / log sheet for any message and click into "Thinking" — the timeline should still load via `/agents/<id>/logs/<msg>`, same as before. - [ ] From the Agent page, click **Chat in new tab** to open `/chat/share?shared_id=<token>&from=agent`. Send a message, wait for a response, then click **Thinking** on the assistant turn. The trace panel should load instead of redirecting to the login page. - [ ] Same flow but with the agent embedded in an iframe ("Embed into webpage") — confirm there is no login redirect. - [ ] In DevTools → Network, confirm the share-chat trace request goes to `/api/v1/agentbots/<sharedId>/logs/<msgId>` and returns 200 with the same JSON shape as the logged-in path. - [ ] Confirm the chat completions, inputs, and upload flows in the share page still work — they were not touched. - [ ] Send a bogus / expired beta token to the new endpoint and confirm it returns the standard "Authentication error: API key is invalid!" response (no traceback, no 500). - [ ] Run `uv run pytest` to make sure no existing tests regress. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [ ] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): --------- Co-authored-by: Zhichang Yu <[email protected]>
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md Execution snapshot (all merged upstream) to the Go agent side. Group 2 - SSRF + cross-cutting - infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates the target URL and (optionally) the proxy URL BEFORE any HTTP request. utility.PinnedHTTPClient dials the validated public IP for the direct path (defeats DNS rebinding). No-redirects policy closes the 30x-bypass window. ALLOW_ANY_HOST env var added to utility.AssertURLSafe for test bypass (production: never set; tests: t.Setenv). 4 new tests cover loopback, metadata IP, loopback proxy, no-follow-redirect. Group 4 - API auth + interactive events - infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/ <message_id> sibling. BetaAuthMiddleware now also looks up the APIToken directly and stashes DialogID in the gin context as agent_id, so the handler can build the Redis key without trusting the URL segment. New UserService.GetAPITokenByBeta + userTokenResolver interface method + stub update. 2 new tests cover agent_id-in-context and message_id-required paths. - infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an Event field (json:event,omitempty); WriteChatbotFrame includes it in the inner data envelope so the front-end can distinguish user_inputs / workflow_finished events from plain messages and render the UserFillUp form vs the assistant text. 3 new tests cover the user_inputs, workflow_finished, and message event types. - infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now rejects empty/nil security config (was fail-open); validateAuth rejects auth_type=none without allow_anonymous=true. New isTruthyAllowAnonymous helper mirrors python _is_truthy. Existing tests updated to use the explicit-opt-in default via makeWebhookCanvas. 3 new tests cover empty/nil config, auth_type=none without opt-in, and the various truthy forms of allow_anonymous. Total: 12 new tests across 3 modified test files. All touched package tests pass (1709 + 4 skipped). The 1 failing test (TestAgent_ReActExhaustsSteps) is the pre-existing flaky test that also fails on the baseline without my changes. Refs: .claude/plans/review-and-port-py-agent-changes.md Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md Execution snapshot (all merged upstream) to the Go agent side. Group 2 - SSRF + cross-cutting - infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates the target URL and (optionally) the proxy URL BEFORE any HTTP request. utility.PinnedHTTPClient dials the validated public IP for the direct path (defeats DNS rebinding). No-redirects policy closes the 30x-bypass window. ALLOW_ANY_HOST env var added to utility.AssertURLSafe for test bypass (production: never set; tests: t.Setenv). 4 new tests cover loopback, metadata IP, loopback proxy, no-follow-redirect. Group 4 - API auth + interactive events - infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/ <message_id> sibling. BetaAuthMiddleware now also looks up the APIToken directly and stashes DialogID in the gin context as agent_id, so the handler can build the Redis key without trusting the URL segment. New UserService.GetAPITokenByBeta + userTokenResolver interface method + stub update. 2 new tests cover agent_id-in-context and message_id-required paths. - infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an Event field (json:event,omitempty); WriteChatbotFrame includes it in the inner data envelope so the front-end can distinguish user_inputs / workflow_finished events from plain messages and render the UserFillUp form vs the assistant text. 3 new tests cover the user_inputs, workflow_finished, and message event types. - infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now rejects empty/nil security config (was fail-open); validateAuth rejects auth_type=none without allow_anonymous=true. New isTruthyAllowAnonymous helper mirrors python _is_truthy. Existing tests updated to use the explicit-opt-in default via makeWebhookCanvas. 3 new tests cover empty/nil config, auth_type=none without opt-in, and the various truthy forms of allow_anonymous. Total: 12 new tests across 3 modified test files. All touched package tests pass (1709 + 4 skipped). The 1 failing test (TestAgent_ReActExhaustsSteps) is the pre-existing flaky test that also fails on the baseline without my changes. Refs: .claude/plans/review-and-port-py-agent-changes.md Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md Execution snapshot (all merged upstream) to the Go agent side. Group 2 - SSRF + cross-cutting - infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates the target URL and (optionally) the proxy URL BEFORE any HTTP request. utility.PinnedHTTPClient dials the validated public IP for the direct path (defeats DNS rebinding). No-redirects policy closes the 30x-bypass window. ALLOW_ANY_HOST env var added to utility.AssertURLSafe for test bypass (production: never set; tests: t.Setenv). 4 new tests cover loopback, metadata IP, loopback proxy, no-follow-redirect. Group 4 - API auth + interactive events - infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/ <message_id> sibling. BetaAuthMiddleware now also looks up the APIToken directly and stashes DialogID in the gin context as agent_id, so the handler can build the Redis key without trusting the URL segment. New UserService.GetAPITokenByBeta + userTokenResolver interface method + stub update. 2 new tests cover agent_id-in-context and message_id-required paths. - infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an Event field (json:event,omitempty); WriteChatbotFrame includes it in the inner data envelope so the front-end can distinguish user_inputs / workflow_finished events from plain messages and render the UserFillUp form vs the assistant text. 3 new tests cover the user_inputs, workflow_finished, and message event types. - infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now rejects empty/nil security config (was fail-open); validateAuth rejects auth_type=none without allow_anonymous=true. New isTruthyAllowAnonymous helper mirrors python _is_truthy. Existing tests updated to use the explicit-opt-in default via makeWebhookCanvas. 3 new tests cover empty/nil config, auth_type=none without opt-in, and the various truthy forms of allow_anonymous. Total: 12 new tests across 3 modified test files. All touched package tests pass (1709 + 4 skipped). The 1 failing test (TestAgent_ReActExhaustsSteps) is the pre-existing flaky test that also fails on the baseline without my changes. Refs: .claude/plans/review-and-port-py-agent-changes.md Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
Ports 4 L/M-effort PRs from .claude/plans/review-and-port-py-agent-changes.md Execution snapshot (all merged upstream) to the Go agent side. Group 2 - SSRF + cross-cutting - infiniflow#15426 Invoke SSRF consolidation: utility.AssertURLSafe gates the target URL and (optionally) the proxy URL BEFORE any HTTP request. utility.PinnedHTTPClient dials the validated public IP for the direct path (defeats DNS rebinding). No-redirects policy closes the 30x-bypass window. ALLOW_ANY_HOST env var added to utility.AssertURLSafe for test bypass (production: never set; tests: t.Setenv). 4 new tests cover loopback, metadata IP, loopback proxy, no-follow-redirect. Group 4 - API auth + interactive events - infiniflow#15238 Thinking logs: new GET /api/v1/agentbots/<shared_id>/logs/ <message_id> sibling. BetaAuthMiddleware now also looks up the APIToken directly and stashes DialogID in the gin context as agent_id, so the handler can build the Redis key without trusting the URL segment. New UserService.GetAPITokenByBeta + userTokenResolver interface method + stub update. 2 new tests cover agent_id-in-context and message_id-required paths. - infiniflow#14589 UserFillUp explore events: ChatbotSSEFrame gains an Event field (json:event,omitempty); WriteChatbotFrame includes it in the inner data envelope so the front-end can distinguish user_inputs / workflow_finished events from plain messages and render the UserFillUp form vs the assistant text. 3 new tests cover the user_inputs, workflow_finished, and message event types. - infiniflow#14890 Anonymous webhook opt-in: validateWebhookSecurity now rejects empty/nil security config (was fail-open); validateAuth rejects auth_type=none without allow_anonymous=true. New isTruthyAllowAnonymous helper mirrors python _is_truthy. Existing tests updated to use the explicit-opt-in default via makeWebhookCanvas. 3 new tests cover empty/nil config, auth_type=none without opt-in, and the various truthy forms of allow_anonymous. Total: 12 new tests across 3 modified test files. All touched package tests pass (1709 + 4 skipped). The 1 failing test (TestAgent_ReActExhaustsSteps) is the pre-existing flaky test that also fails on the baseline without my changes. Refs: .claude/plans/review-and-port-py-agent-changes.md Refs: infiniflow#15426 infiniflow#15238 infiniflow#14589 infiniflow#14890
) Mirrors 14 merged upstream PRs into the Go agent port. PRs ported: - #15609 ExeSQL SSRF guard + DNS pin - #15436 HTTP timeout on external API tools - #16363 be_output restore + DeepL error path - #15644 switch no longer matches empty condition - #15374 session_id bind to path agent_id (DAO idor guard) - #16169 sandbox artifact ownership gate - #15457 tenant ownership on agentbots - #15145 rerun agent document access check - #15446 thinking switch (component portion; provider policy lives in internal/llm) - #15426 Invoke URL/proxy SSRF + DNS pin + no-redirects - #15238 agentbot thinking-logs beta endpoint - #14589 UserFillUp SSE event propagation - #14890 anonymous webhook opt-in - #15068 PipelineChunker new component (text/file_ref/parser_id dispatch; file-format extraction is a follow-up) 40 files, +2355 / -58 lines. 33 new tests, all targeted package suites pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
…iniflow#16455) Mirrors 14 merged upstream PRs into the Go agent port. PRs ported: - infiniflow#15609 ExeSQL SSRF guard + DNS pin - infiniflow#15436 HTTP timeout on external API tools - infiniflow#16363 be_output restore + DeepL error path - infiniflow#15644 switch no longer matches empty condition - infiniflow#15374 session_id bind to path agent_id (DAO idor guard) - infiniflow#16169 sandbox artifact ownership gate - infiniflow#15457 tenant ownership on agentbots - infiniflow#15145 rerun agent document access check - infiniflow#15446 thinking switch (component portion; provider policy lives in internal/llm) - infiniflow#15426 Invoke URL/proxy SSRF + DNS pin + no-redirects - infiniflow#15238 agentbot thinking-logs beta endpoint - infiniflow#14589 UserFillUp SSE event propagation - infiniflow#14890 anonymous webhook opt-in - infiniflow#15068 PipelineChunker new component (text/file_ref/parser_id dispatch; file-format extraction is a follow-up) 40 files, +2355 / -58 lines. 33 new tests, all targeted package suites pass (1721 + 4 skipped); 1 pre-existing flaky test unrelated.
Summary
Fixes #14985 — clicking the Thinking button in a shared/embedded
chat returns 401 and bounces the user to the login page, even though
the same share page can chat with the agent just fine.
Root cause
In shared chat,
useGetSharedChatSearchParamsbindsconversationIdto the URL's
shared_idquery param — which is the beta APIToken,not the real agent id. That
conversationIdpropagates through thecomponent tree:
But
/agents/<agent_id>/logs/<message_id>is decorated with@login_required(api/apps/restful_apis/agent_api.py:842-846).The share page only holds the beta token — there is no session JWT
— so the request 401s and quart-auth redirects to the login page.
The reporter's server log matches exactly:
The
394013f8...segment in the URL is theshared_id(betatoken), not an actual agent id.
_load_useralready accepts theregular
APIToken.tokenfield, but notAPIToken.beta, by design— beta is a much weaker share-link credential than a personal API
key.
The sibling endpoints
/agentbots/<id>/completionsand/agentbots/<id>/inputsalready use the right auth pattern forthis scope (beta-token via
_get_sdk_authorization_token→APIToken.query(beta=token)). Trace just didn't have a parallel.Fix
Backend (
api/apps/restful_apis/bot_api.py)Added a beta-token sibling endpoint:
agentbotsendpoints.<shared_id>path segment is a client-supplied label only.The real
agent_idused to build the Redis key(
<agent_id>-<message_id>-logs) is taken fromAPIToken.dialog_idon the looked-up token, so the endpointnever trusts client-supplied identifiers for the data lookup.
{data: ...}shape as the existing/agents/<id>/logs/<message_id>endpoint, so the frontenddoesn't need to reshape the response.
Frontend
web/src/utils/api.ts: addedsharedTrace(sharedId, messageId)URL builder.
web/src/services/agent-service.ts: addedfetchSharedTrace({ shared_id, message_id }).web/src/hooks/use-agent-request.ts:useFetchMessageTracetakes an optional
isShareargument. When set, it callsfetchSharedTrace;isShareis also folded into thequeryKeyso the two modes never share cached results.web/src/pages/agent/log-sheet/workflow-timeline.tsx:forwards the already-existing
isShareprop into the hook.All other existing call sites of
useFetchMessageTrace(webhooktimeline, pipeline log, dataflow result) pass no
isShareargument → undefined → falsy → unchanged behavior.
Test plan
log sheet for any message and click into "Thinking" — the
timeline should still load via
/agents/<id>/logs/<msg>,same as before.
/chat/share?shared_id=<token>&from=agent. Send a message,wait for a response, then click Thinking on the
assistant turn. The trace panel should load instead of
redirecting to the login page.
into webpage") — confirm there is no login redirect.
goes to
/api/v1/agentbots/<sharedId>/logs/<msgId>andreturns 200 with the same JSON shape as the logged-in path.
the share page still work — they were not touched.
confirm it returns the standard "Authentication error: API
key is invalid!" response (no traceback, no 500).
uv run pytestto make sure no existing tests regress.Type of change