2025-07-24 19:17:56 +08:00
|
|
|
import { FileUploadProps } from '@/components/file-upload';
|
2025-10-09 12:36:19 +08:00
|
|
|
import { useHandleFilterSubmit } from '@/components/list-filter-bar/use-handle-filter-submit';
|
2025-07-16 16:25:50 +08:00
|
|
|
import message from '@/components/ui/message';
|
2026-03-02 11:41:38 +08:00
|
|
|
import { AgentCategory, AgentGlobals } from '@/constants/agent';
|
2026-02-09 19:53:51 +08:00
|
|
|
import { useFetchTenantInfo } from '@/hooks/use-user-setting-request';
|
|
|
|
|
import {
|
|
|
|
|
IAgentLogResponse,
|
2025-07-30 09:48:51 +08:00
|
|
|
IAgentLogsRequest,
|
|
|
|
|
IAgentLogsResponse,
|
2026-07-20 16:05:03 +08:00
|
|
|
IBuiltinPipelineListResponse,
|
2025-08-11 14:03:52 +08:00
|
|
|
IFlow,
|
|
|
|
|
IFlowTemplate,
|
2025-10-09 12:36:19 +08:00
|
|
|
IPipeLineListRequest,
|
2025-07-30 09:48:51 +08:00
|
|
|
ITraceData,
|
2025-12-19 12:56:56 +08:00
|
|
|
IWebhookTrace,
|
2025-07-30 09:48:51 +08:00
|
|
|
} from '@/interfaces/database/agent';
|
2025-12-19 12:56:56 +08:00
|
|
|
import {
|
|
|
|
|
IAgentWebhookTraceRequest,
|
|
|
|
|
IDebugSingleRequestBody,
|
|
|
|
|
} from '@/interfaces/request/agent';
|
2025-06-05 12:04:31 +08:00
|
|
|
import i18n from '@/locales/config';
|
2025-08-01 12:38:29 +08:00
|
|
|
import { IInputs } from '@/pages/agent/interface';
|
2025-11-27 17:54:27 +08:00
|
|
|
import { useGetSharedChatSearchParams } from '@/pages/next-chats/hooks/use-send-shared-message';
|
2025-07-30 09:48:51 +08:00
|
|
|
import agentService, {
|
2026-02-09 19:53:51 +08:00
|
|
|
createAgentSession,
|
|
|
|
|
deleteAgentSession,
|
2025-07-30 09:48:51 +08:00
|
|
|
fetchAgentLogsByCanvasId,
|
2026-02-09 19:53:51 +08:00
|
|
|
fetchAgentLogsById,
|
2025-10-09 12:36:19 +08:00
|
|
|
fetchPipeLineList,
|
fix(agent): authenticate "Thinking" button in shared/embedded chat via 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 <yuzhichang@gmail.com>
2026-06-27 22:00:50 -07:00
|
|
|
fetchSharedTrace,
|
2025-07-30 09:48:51 +08:00
|
|
|
fetchTrace,
|
2025-12-19 12:56:56 +08:00
|
|
|
fetchWebhookTrace,
|
2026-04-24 10:02:22 +08:00
|
|
|
updateAgent,
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
updateAgentTags,
|
2026-04-24 10:02:22 +08:00
|
|
|
uploadAgentFile,
|
2025-07-30 09:48:51 +08:00
|
|
|
} from '@/services/agent-service';
|
2025-06-05 12:04:31 +08:00
|
|
|
import { buildMessageListWithUuid } from '@/utils/chat';
|
2025-05-20 19:13:19 +08:00
|
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
2025-05-20 16:03:55 +08:00
|
|
|
import { useDebounce } from 'ahooks';
|
2026-01-26 17:54:30 +08:00
|
|
|
import { get, isEmpty, set } from 'lodash';
|
2025-07-08 09:27:56 +08:00
|
|
|
import { useCallback, useState } from 'react';
|
2026-01-04 19:14:20 +08:00
|
|
|
import { useParams, useSearchParams } from 'react-router';
|
2025-05-20 16:03:55 +08:00
|
|
|
import {
|
|
|
|
|
useGetPaginationWithRouter,
|
|
|
|
|
useHandleSearchChange,
|
|
|
|
|
} from './logic-hooks';
|
2025-04-29 09:50:54 +08:00
|
|
|
|
|
|
|
|
export const enum AgentApiAction {
|
2025-10-09 12:36:19 +08:00
|
|
|
FetchAgentListByPage = 'fetchAgentListByPage',
|
2026-02-09 19:53:51 +08:00
|
|
|
FetchAllAgentList = 'fetchAllAgentList',
|
2025-04-29 09:50:54 +08:00
|
|
|
FetchAgentList = 'fetchAgentList',
|
2025-05-20 19:13:19 +08:00
|
|
|
UpdateAgentSetting = 'updateAgentSetting',
|
|
|
|
|
DeleteAgent = 'deleteAgent',
|
2025-06-05 12:04:31 +08:00
|
|
|
FetchAgentDetail = 'fetchAgentDetail',
|
|
|
|
|
ResetAgent = 'resetAgent',
|
|
|
|
|
SetAgent = 'setAgent',
|
|
|
|
|
FetchAgentTemplates = 'fetchAgentTemplates',
|
2026-04-24 10:02:22 +08:00
|
|
|
UploadAgentFile = 'uploadAgentFile',
|
|
|
|
|
UploadAgentFileWithProgress = 'uploadAgentFileWithProgress',
|
2025-07-08 09:27:56 +08:00
|
|
|
Trace = 'trace',
|
2025-07-16 16:25:50 +08:00
|
|
|
TestDbConnect = 'testDbConnect',
|
2025-07-18 17:54:32 +08:00
|
|
|
DebugSingle = 'debugSingle',
|
|
|
|
|
FetchInputForm = 'fetchInputForm',
|
2025-07-21 16:28:06 +08:00
|
|
|
FetchVersionList = 'fetchVersionList',
|
|
|
|
|
FetchVersion = 'fetchVersion',
|
2025-07-31 09:34:45 +08:00
|
|
|
FetchExternalAgentInputs = 'fetchExternalAgentInputs',
|
2025-08-08 11:00:55 +08:00
|
|
|
SetAgentSetting = 'setAgentSetting',
|
2025-09-05 15:48:57 +08:00
|
|
|
FetchPrompt = 'fetchPrompt',
|
2025-10-09 12:36:19 +08:00
|
|
|
CancelDataflow = 'cancelDataflow',
|
2025-11-11 15:21:08 +08:00
|
|
|
CancelCanvas = 'cancelCanvas',
|
2025-12-19 12:56:56 +08:00
|
|
|
FetchWebhookTrace = 'fetchWebhookTrace',
|
2026-02-09 19:53:51 +08:00
|
|
|
FetchSessionsByCanvasId = 'fetchSessionsByCanvasId',
|
|
|
|
|
FetchSessionById = 'fetchSessionById',
|
|
|
|
|
CreateAgentSession = 'createAgentSession',
|
|
|
|
|
DeleteAgentSession = 'deleteAgentSession',
|
|
|
|
|
FetchSessionByIdManually = 'fetchSessionByIdManually',
|
2026-03-17 18:51:26 +08:00
|
|
|
FetchAgentLog = 'fetchAgentLog',
|
2026-04-24 10:02:22 +08:00
|
|
|
FetchSharedAgent = 'fetchSharedAgent',
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
FetchAgentTags = 'fetchAgentTags',
|
|
|
|
|
UpdateAgentTags = 'updateAgentTags',
|
2026-07-20 16:05:03 +08:00
|
|
|
FetchPipelineNodes = 'fetchPipelineNodes',
|
|
|
|
|
FetchBuiltinPipelineList = 'fetchBuiltinPipelineList',
|
|
|
|
|
FetchBuiltinPipelineDetail = 'fetchBuiltinPipelineDetail',
|
2025-04-29 09:50:54 +08:00
|
|
|
}
|
|
|
|
|
|
2025-06-05 12:04:31 +08:00
|
|
|
export const useFetchAgentTemplates = () => {
|
|
|
|
|
const { data } = useQuery<IFlowTemplate[]>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAgentTemplates],
|
|
|
|
|
initialData: [],
|
|
|
|
|
queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.listAgentTemplate();
|
2025-06-05 12:04:31 +08:00
|
|
|
|
|
|
|
|
return data.data;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return data;
|
|
|
|
|
};
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
const buildAgentListParams = ({
|
|
|
|
|
page,
|
|
|
|
|
pageSize,
|
|
|
|
|
keywords,
|
|
|
|
|
canvasCategory,
|
|
|
|
|
ownerIds,
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
tags,
|
2026-04-24 10:02:22 +08:00
|
|
|
}: {
|
|
|
|
|
page: number;
|
|
|
|
|
pageSize: number;
|
|
|
|
|
keywords?: string;
|
|
|
|
|
canvasCategory?: string;
|
|
|
|
|
ownerIds?: string[];
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
tags?: string[];
|
2026-04-24 10:02:22 +08:00
|
|
|
}) => {
|
|
|
|
|
const params: Record<string, unknown> = {
|
|
|
|
|
page,
|
|
|
|
|
page_size: pageSize,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (keywords) {
|
|
|
|
|
params.keywords = keywords;
|
|
|
|
|
}
|
|
|
|
|
if (canvasCategory) {
|
|
|
|
|
params.canvas_category = canvasCategory;
|
|
|
|
|
}
|
|
|
|
|
if (Array.isArray(ownerIds) && ownerIds.length > 0) {
|
|
|
|
|
params.owner_ids = ownerIds.join(',');
|
|
|
|
|
}
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
if (Array.isArray(tags) && tags.length > 0) {
|
|
|
|
|
params.tags = tags.join(',');
|
|
|
|
|
}
|
2026-04-24 10:02:22 +08:00
|
|
|
|
|
|
|
|
return params;
|
|
|
|
|
};
|
|
|
|
|
|
2025-05-20 16:03:55 +08:00
|
|
|
export const useFetchAgentListByPage = () => {
|
|
|
|
|
const { searchString, handleInputChange } = useHandleSearchChange();
|
|
|
|
|
const { pagination, setPagination } = useGetPaginationWithRouter();
|
|
|
|
|
const debouncedSearchString = useDebounce(searchString, { wait: 500 });
|
2025-10-09 12:36:19 +08:00
|
|
|
const { filterValue, handleFilterSubmit } = useHandleFilterSubmit();
|
|
|
|
|
const canvasCategory = Array.isArray(filterValue.canvasCategory)
|
|
|
|
|
? filterValue.canvasCategory
|
|
|
|
|
: [];
|
|
|
|
|
const owner = filterValue.owner;
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
const tags = Array.isArray(filterValue.tags) ? filterValue.tags : undefined;
|
2025-10-09 12:36:19 +08:00
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
const requestParams = buildAgentListParams({
|
2025-10-09 12:36:19 +08:00
|
|
|
page: pagination.current,
|
2026-04-24 10:02:22 +08:00
|
|
|
pageSize: pagination.pageSize,
|
|
|
|
|
keywords: debouncedSearchString,
|
|
|
|
|
canvasCategory: canvasCategory.length === 1 ? canvasCategory[0] : undefined,
|
|
|
|
|
ownerIds: Array.isArray(owner) ? owner : undefined,
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
tags,
|
2026-04-24 10:02:22 +08:00
|
|
|
});
|
2025-05-20 16:03:55 +08:00
|
|
|
|
|
|
|
|
const { data, isFetching: loading } = useQuery<{
|
2025-08-11 14:03:52 +08:00
|
|
|
canvas: IFlow[];
|
2025-05-20 16:03:55 +08:00
|
|
|
total: number;
|
|
|
|
|
}>({
|
|
|
|
|
queryKey: [
|
2025-10-09 12:36:19 +08:00
|
|
|
AgentApiAction.FetchAgentListByPage,
|
2025-05-20 16:03:55 +08:00
|
|
|
{
|
|
|
|
|
debouncedSearchString,
|
|
|
|
|
...pagination,
|
2025-10-09 12:36:19 +08:00
|
|
|
filterValue,
|
2025-05-20 16:03:55 +08:00
|
|
|
},
|
|
|
|
|
],
|
2025-10-09 12:36:19 +08:00
|
|
|
placeholderData: (previousData) => {
|
|
|
|
|
if (previousData === undefined) {
|
|
|
|
|
return { canvas: [], total: 0 };
|
|
|
|
|
}
|
|
|
|
|
return previousData;
|
|
|
|
|
},
|
2025-04-29 09:50:54 +08:00
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.listAgents(
|
2025-07-23 15:09:24 +08:00
|
|
|
{
|
2025-10-09 12:36:19 +08:00
|
|
|
params: requestParams,
|
2025-07-23 15:09:24 +08:00
|
|
|
},
|
|
|
|
|
true,
|
|
|
|
|
);
|
2025-04-29 09:50:54 +08:00
|
|
|
|
2025-08-11 14:03:52 +08:00
|
|
|
return data?.data;
|
2025-04-29 09:50:54 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2025-05-20 16:03:55 +08:00
|
|
|
const onInputChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
|
|
|
|
|
(e) => {
|
2025-07-16 16:25:50 +08:00
|
|
|
// setPagination({ page: 1 });
|
2025-05-20 16:03:55 +08:00
|
|
|
handleInputChange(e);
|
|
|
|
|
},
|
|
|
|
|
[handleInputChange],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return {
|
2025-10-09 12:36:19 +08:00
|
|
|
data: data?.canvas ?? [],
|
2025-05-20 16:03:55 +08:00
|
|
|
loading,
|
|
|
|
|
searchString,
|
|
|
|
|
handleInputChange: onInputChange,
|
|
|
|
|
pagination: { ...pagination, total: data?.total },
|
|
|
|
|
setPagination,
|
2025-10-09 12:36:19 +08:00
|
|
|
filterValue,
|
|
|
|
|
handleFilterSubmit,
|
2025-05-20 16:03:55 +08:00
|
|
|
};
|
2025-04-29 09:50:54 +08:00
|
|
|
};
|
2025-05-20 19:13:19 +08:00
|
|
|
|
2026-02-09 19:53:51 +08:00
|
|
|
export function useFetchAllAgentList() {
|
|
|
|
|
const { data, isFetching: loading } = useQuery<IFlow[]>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAllAgentList],
|
|
|
|
|
queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.listAgents(
|
2026-02-09 19:53:51 +08:00
|
|
|
{
|
2026-04-24 10:02:22 +08:00
|
|
|
params: buildAgentListParams({
|
2026-02-09 19:53:51 +08:00
|
|
|
page: 1,
|
2026-04-24 10:02:22 +08:00
|
|
|
pageSize: 100000,
|
|
|
|
|
canvasCategory: AgentCategory.AgentCanvas,
|
|
|
|
|
}),
|
2026-02-09 19:53:51 +08:00
|
|
|
},
|
|
|
|
|
true,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return data?.data?.canvas;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading };
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-20 19:13:19 +08:00
|
|
|
export const useUpdateAgentSetting = () => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.UpdateAgentSetting],
|
|
|
|
|
mutationFn: async (params: any) => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const ret = await updateAgent(params.id, {
|
|
|
|
|
title: params.title,
|
|
|
|
|
description: params.description,
|
|
|
|
|
permission: params.permission,
|
|
|
|
|
avatar: params.avatar,
|
|
|
|
|
});
|
2025-05-20 19:13:19 +08:00
|
|
|
if (ret?.data?.code === 0) {
|
|
|
|
|
message.success('success');
|
|
|
|
|
queryClient.invalidateQueries({
|
2025-10-09 12:36:19 +08:00
|
|
|
queryKey: [AgentApiAction.FetchAgentListByPage],
|
2025-05-20 19:13:19 +08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return ret?.data?.code;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, updateAgentSetting: mutateAsync };
|
|
|
|
|
};
|
|
|
|
|
|
2026-06-28 18:17:44 -07:00
|
|
|
export const useDuplicateAgent = () => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.SetAgent, 'duplicate'],
|
|
|
|
|
mutationFn: async (agent: Pick<IFlow, 'id' | 'title'>) => {
|
|
|
|
|
try {
|
|
|
|
|
const { data: detail } = await agentService.getAgent(agent.id);
|
|
|
|
|
const source = detail?.data;
|
|
|
|
|
if (!source) {
|
|
|
|
|
message.error(i18n.t('message.requestError'));
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const sourceTitle = agent.title ?? source.title ?? '';
|
|
|
|
|
const { data } = await agentService.createAgent({
|
|
|
|
|
title: i18n.t('flow.copyOfAgentName', {
|
|
|
|
|
name: sourceTitle,
|
|
|
|
|
defaultValue: `${sourceTitle} (Copy)`,
|
|
|
|
|
}),
|
|
|
|
|
dsl: source.dsl,
|
|
|
|
|
avatar: source.avatar,
|
|
|
|
|
description: source.description,
|
|
|
|
|
canvas_category: source.canvas_category,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (data?.code === 0) {
|
|
|
|
|
message.success(i18n.t('message.created'));
|
|
|
|
|
queryClient.invalidateQueries({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAgentListByPage],
|
|
|
|
|
});
|
|
|
|
|
return data;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
message.error(data?.message ?? i18n.t('message.requestError'));
|
|
|
|
|
return null;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('useDuplicateAgent failed:', error);
|
|
|
|
|
message.error(
|
|
|
|
|
(error as { message?: string })?.message ??
|
|
|
|
|
i18n.t('message.requestError'),
|
|
|
|
|
);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, duplicateAgent: mutateAsync };
|
|
|
|
|
};
|
|
|
|
|
|
2025-05-20 19:13:19 +08:00
|
|
|
export const useDeleteAgent = () => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.DeleteAgent],
|
2026-04-24 10:02:22 +08:00
|
|
|
mutationFn: async (agentId: string) => {
|
|
|
|
|
const { data } = await agentService.deleteAgent(agentId);
|
2025-05-20 19:13:19 +08:00
|
|
|
if (data.code === 0) {
|
|
|
|
|
queryClient.invalidateQueries({
|
2025-10-09 12:36:19 +08:00
|
|
|
queryKey: [AgentApiAction.FetchAgentListByPage],
|
2025-05-20 19:13:19 +08:00
|
|
|
});
|
|
|
|
|
}
|
2026-04-24 10:02:22 +08:00
|
|
|
return data?.data ?? false;
|
2025-05-20 19:13:19 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, deleteAgent: mutateAsync };
|
|
|
|
|
};
|
2025-06-05 12:04:31 +08:00
|
|
|
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
export interface IAgentTagCount {
|
|
|
|
|
tag: string;
|
|
|
|
|
count: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useFetchAgentTags = (canvasCategory?: string) => {
|
|
|
|
|
const { data, isFetching: loading } = useQuery<IAgentTagCount[]>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAgentTags, canvasCategory],
|
|
|
|
|
initialData: [],
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
const { data } = await agentService.listAgentTags(
|
|
|
|
|
{
|
|
|
|
|
params: canvasCategory ? { canvas_category: canvasCategory } : {},
|
|
|
|
|
},
|
|
|
|
|
true,
|
|
|
|
|
);
|
|
|
|
|
return data?.data ?? [];
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return { data, loading };
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useUpdateAgentTags = () => {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const { isPending: loading, mutateAsync } = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.UpdateAgentTags],
|
|
|
|
|
mutationFn: async ({
|
|
|
|
|
agentId,
|
|
|
|
|
tags,
|
|
|
|
|
}: {
|
|
|
|
|
agentId: string;
|
|
|
|
|
tags: string[];
|
|
|
|
|
}) => {
|
|
|
|
|
const { data } = await updateAgentTags(agentId, tags);
|
|
|
|
|
if (data?.code === 0) {
|
|
|
|
|
queryClient.invalidateQueries({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAgentListByPage],
|
|
|
|
|
});
|
|
|
|
|
queryClient.invalidateQueries({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAgentTags],
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
message.error(data?.message || 'Update failed');
|
|
|
|
|
}
|
|
|
|
|
return data?.code === 0;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
return { loading, updateAgentTags: mutateAsync };
|
|
|
|
|
};
|
|
|
|
|
|
2025-06-05 12:04:31 +08:00
|
|
|
export const useFetchAgent = (): {
|
|
|
|
|
data: IFlow;
|
|
|
|
|
loading: boolean;
|
|
|
|
|
refetch: () => void;
|
|
|
|
|
} => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
const { sharedId } = useGetSharedChatSearchParams();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
|
|
|
|
} = useQuery({
|
2026-06-23 14:13:47 +08:00
|
|
|
queryKey: [AgentApiAction.FetchAgentDetail, sharedId || id],
|
2025-06-05 12:04:31 +08:00
|
|
|
initialData: {} as IFlow,
|
|
|
|
|
refetchOnReconnect: false,
|
|
|
|
|
refetchOnMount: false,
|
|
|
|
|
refetchOnWindowFocus: false,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.getAgent(sharedId || id);
|
2025-06-05 12:04:31 +08:00
|
|
|
|
|
|
|
|
const messageList = buildMessageListWithUuid(
|
|
|
|
|
get(data, 'data.dsl.messages', []),
|
|
|
|
|
);
|
|
|
|
|
set(data, 'data.dsl.messages', messageList);
|
|
|
|
|
|
2026-01-26 17:54:30 +08:00
|
|
|
const sysHistoryPath = [
|
|
|
|
|
'data',
|
|
|
|
|
'dsl',
|
|
|
|
|
'globals',
|
|
|
|
|
AgentGlobals.SysHistory,
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
if (isEmpty(get(data, sysHistoryPath))) {
|
|
|
|
|
set(data, sysHistoryPath, []);
|
|
|
|
|
}
|
|
|
|
|
|
2025-06-05 12:04:31 +08:00
|
|
|
return data?.data ?? {};
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, refetch };
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useResetAgent = () => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.ResetAgent],
|
|
|
|
|
mutationFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.resetAgent(id);
|
2025-06-05 12:04:31 +08:00
|
|
|
return data;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, resetAgent: mutateAsync };
|
|
|
|
|
};
|
|
|
|
|
|
2025-07-31 12:14:00 +08:00
|
|
|
export const useSetAgent = (showMessage: boolean = true) => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { id } = useParams();
|
2025-06-05 12:04:31 +08:00
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.SetAgent],
|
|
|
|
|
mutationFn: async (params: {
|
|
|
|
|
id?: string;
|
|
|
|
|
title?: string;
|
2025-10-09 19:03:29 +08:00
|
|
|
dsl?: Record<string, any>;
|
2025-06-05 12:04:31 +08:00
|
|
|
avatar?: string;
|
2025-10-09 12:36:19 +08:00
|
|
|
canvas_category?: string;
|
2026-03-06 20:17:21 +08:00
|
|
|
release?: string;
|
2026-04-24 10:02:22 +08:00
|
|
|
description?: string | null;
|
|
|
|
|
permission?: string;
|
2025-06-05 12:04:31 +08:00
|
|
|
}) => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const agentId = params.id ?? id;
|
|
|
|
|
const { data = {} } = agentId
|
|
|
|
|
? await updateAgent(agentId, {
|
|
|
|
|
title: params.title,
|
|
|
|
|
dsl: params.dsl,
|
|
|
|
|
avatar: params.avatar,
|
|
|
|
|
description: params.description,
|
|
|
|
|
permission: params.permission,
|
|
|
|
|
release: params.release,
|
|
|
|
|
})
|
|
|
|
|
: await agentService.createAgent(params);
|
2025-06-05 12:04:31 +08:00
|
|
|
if (data.code === 0) {
|
2025-07-31 12:14:00 +08:00
|
|
|
if (showMessage) {
|
|
|
|
|
message.success(
|
2026-04-24 10:02:22 +08:00
|
|
|
i18n.t(`message.${agentId ? 'modified' : 'created'}`),
|
2025-07-31 12:14:00 +08:00
|
|
|
);
|
|
|
|
|
}
|
2025-06-05 12:04:31 +08:00
|
|
|
queryClient.invalidateQueries({
|
2025-10-09 12:36:19 +08:00
|
|
|
queryKey: [AgentApiAction.FetchAgentListByPage],
|
2025-06-05 12:04:31 +08:00
|
|
|
});
|
2026-04-24 10:02:22 +08:00
|
|
|
if (agentId) {
|
|
|
|
|
queryClient.invalidateQueries({
|
2026-06-23 14:13:47 +08:00
|
|
|
queryKey: [AgentApiAction.FetchAgentDetail, agentId],
|
2026-04-24 10:02:22 +08:00
|
|
|
});
|
|
|
|
|
}
|
2025-06-05 12:04:31 +08:00
|
|
|
}
|
|
|
|
|
return data;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, setAgent: mutateAsync };
|
|
|
|
|
};
|
2025-07-07 12:18:18 +08:00
|
|
|
|
2025-07-24 19:17:56 +08:00
|
|
|
// Only one file can be uploaded at a time
|
2026-04-24 10:02:22 +08:00
|
|
|
export const useUploadAgentFile = () => {
|
2025-07-24 19:17:56 +08:00
|
|
|
const { id } = useParams();
|
2025-08-15 18:25:00 +08:00
|
|
|
const [searchParams] = useSearchParams();
|
|
|
|
|
const shared_id = searchParams.get('shared_id');
|
2026-04-24 10:02:22 +08:00
|
|
|
const agentId = id || shared_id;
|
2025-07-07 12:18:18 +08:00
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
2026-04-24 10:02:22 +08:00
|
|
|
mutationKey: [AgentApiAction.UploadAgentFile],
|
2025-07-07 12:18:18 +08:00
|
|
|
mutationFn: async (body: any) => {
|
|
|
|
|
let nextBody = body;
|
|
|
|
|
try {
|
|
|
|
|
if (Array.isArray(body)) {
|
|
|
|
|
nextBody = new FormData();
|
|
|
|
|
body.forEach((file: File) => {
|
|
|
|
|
nextBody.append('file', file as any);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await uploadAgentFile(agentId as string, nextBody);
|
2025-07-07 12:18:18 +08:00
|
|
|
if (data?.code === 0) {
|
|
|
|
|
message.success(i18n.t('message.uploaded'));
|
|
|
|
|
}
|
|
|
|
|
return data;
|
|
|
|
|
} catch (error) {
|
2026-03-02 11:41:38 +08:00
|
|
|
message.error(error as string);
|
2025-07-07 12:18:18 +08:00
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
return { data, loading, uploadAgentFile: mutateAsync };
|
2025-07-07 12:18:18 +08:00
|
|
|
};
|
2025-07-08 09:27:56 +08:00
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
export const useUploadAgentFileWithProgress = (identifier?: string | null) => {
|
2025-07-24 19:17:56 +08:00
|
|
|
const { id } = useParams();
|
|
|
|
|
|
|
|
|
|
type UploadParameters = Parameters<NonNullable<FileUploadProps['onUpload']>>;
|
|
|
|
|
|
|
|
|
|
type X = { files: UploadParameters[0]; options: UploadParameters[1] };
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
2026-04-24 10:02:22 +08:00
|
|
|
mutationKey: [AgentApiAction.UploadAgentFileWithProgress],
|
2025-07-24 19:17:56 +08:00
|
|
|
mutationFn: async ({
|
|
|
|
|
files,
|
|
|
|
|
options: { onError, onSuccess, onProgress },
|
|
|
|
|
}: X) => {
|
|
|
|
|
const formData = new FormData();
|
|
|
|
|
try {
|
|
|
|
|
if (Array.isArray(files)) {
|
|
|
|
|
files.forEach((file: File) => {
|
|
|
|
|
formData.append('file', file);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.uploadAgentFile(
|
2025-07-24 19:17:56 +08:00
|
|
|
{
|
2026-04-24 10:02:22 +08:00
|
|
|
agentId: identifier || id,
|
2025-07-24 19:17:56 +08:00
|
|
|
data: formData,
|
2025-08-11 15:31:38 +08:00
|
|
|
onUploadProgress: ({ progress }) => {
|
2025-07-24 19:17:56 +08:00
|
|
|
files.forEach((file) => {
|
|
|
|
|
onProgress(file, (progress || 0) * 100);
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
true,
|
|
|
|
|
);
|
|
|
|
|
if (data?.code === 0) {
|
|
|
|
|
files.forEach((file) => {
|
|
|
|
|
onSuccess(file);
|
|
|
|
|
});
|
|
|
|
|
message.success(i18n.t('message.uploaded'));
|
|
|
|
|
}
|
|
|
|
|
return data;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
files.forEach((file) => {
|
|
|
|
|
onError(file, error as Error);
|
|
|
|
|
});
|
2025-10-09 12:36:19 +08:00
|
|
|
message.error((error as Error)?.message || 'Upload failed');
|
2025-07-24 19:17:56 +08:00
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
return { data, loading, uploadAgentFile: mutateAsync };
|
2025-07-24 19:17:56 +08:00
|
|
|
};
|
|
|
|
|
|
fix(agent): authenticate "Thinking" button in shared/embedded chat via 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 <yuzhichang@gmail.com>
2026-06-27 22:00:50 -07:00
|
|
|
export const useFetchMessageTrace = (canvasId?: string, isShare?: boolean) => {
|
2025-07-08 09:27:56 +08:00
|
|
|
const { id } = useParams();
|
fix(agent): authenticate "Thinking" button in shared/embedded chat via 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 <yuzhichang@gmail.com>
2026-06-27 22:00:50 -07:00
|
|
|
// In shared mode there's no :id route param and `canvasId` actually carries
|
|
|
|
|
// the share (beta) APIToken — route through fetchSharedTrace so the request
|
|
|
|
|
// hits the beta-token-aware endpoint instead of /agents/<id>/logs which
|
|
|
|
|
// requires a session login (fixes #14985).
|
2025-07-28 16:48:46 +08:00
|
|
|
const queryId = id || canvasId;
|
2025-07-08 09:27:56 +08:00
|
|
|
const [messageId, setMessageId] = useState('');
|
2025-10-09 12:36:19 +08:00
|
|
|
const [isStopFetchTrace, setISStopFetchTrace] = useState(false);
|
2025-07-08 09:27:56 +08:00
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
|
|
|
|
} = useQuery<ITraceData[]>({
|
fix(agent): authenticate "Thinking" button in shared/embedded chat via 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 <yuzhichang@gmail.com>
2026-06-27 22:00:50 -07:00
|
|
|
queryKey: [AgentApiAction.Trace, queryId, messageId, !!isShare],
|
2025-07-08 09:27:56 +08:00
|
|
|
refetchOnReconnect: false,
|
|
|
|
|
refetchOnMount: false,
|
|
|
|
|
refetchOnWindowFocus: false,
|
|
|
|
|
gcTime: 0,
|
2025-07-28 16:48:46 +08:00
|
|
|
enabled: !!queryId && !!messageId,
|
|
|
|
|
refetchInterval: !isStopFetchTrace ? 3000 : false,
|
2025-07-08 09:27:56 +08:00
|
|
|
queryFn: async () => {
|
fix(agent): authenticate "Thinking" button in shared/embedded chat via 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 <yuzhichang@gmail.com>
2026-06-27 22:00:50 -07:00
|
|
|
const { data } = isShare
|
|
|
|
|
? await fetchSharedTrace({
|
|
|
|
|
shared_id: queryId as string,
|
|
|
|
|
message_id: messageId,
|
|
|
|
|
})
|
|
|
|
|
: await fetchTrace({
|
|
|
|
|
canvas_id: queryId as string,
|
|
|
|
|
message_id: messageId,
|
|
|
|
|
});
|
2025-07-08 09:27:56 +08:00
|
|
|
|
2025-10-09 12:36:19 +08:00
|
|
|
return Array.isArray(data?.data) ? data?.data : [];
|
2025-07-08 09:27:56 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2025-10-09 12:36:19 +08:00
|
|
|
return {
|
|
|
|
|
data,
|
|
|
|
|
loading,
|
|
|
|
|
refetch,
|
|
|
|
|
setMessageId,
|
|
|
|
|
messageId,
|
|
|
|
|
isStopFetchTrace,
|
|
|
|
|
setISStopFetchTrace,
|
|
|
|
|
};
|
2025-07-08 09:27:56 +08:00
|
|
|
};
|
2025-07-16 16:25:50 +08:00
|
|
|
|
|
|
|
|
export const useTestDbConnect = () => {
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.TestDbConnect],
|
|
|
|
|
mutationFn: async (params: any) => {
|
2025-07-23 15:09:24 +08:00
|
|
|
const ret = await agentService.testDbConnect(params);
|
2025-07-16 16:25:50 +08:00
|
|
|
if (ret?.data?.code === 0) {
|
|
|
|
|
message.success(ret?.data?.data);
|
|
|
|
|
} else {
|
|
|
|
|
message.error(ret?.data?.data);
|
|
|
|
|
}
|
|
|
|
|
return ret;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, testDbConnect: mutateAsync };
|
|
|
|
|
};
|
2025-07-18 17:54:32 +08:00
|
|
|
|
|
|
|
|
export const useDebugSingle = () => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
2026-04-24 10:02:22 +08:00
|
|
|
mutationKey: [AgentApiAction.DebugSingle],
|
2025-07-18 17:54:32 +08:00
|
|
|
mutationFn: async (params: IDebugSingleRequestBody) => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const ret = await agentService.debugSingle(
|
|
|
|
|
{
|
|
|
|
|
agentId: id as string,
|
|
|
|
|
componentId: params.component_id,
|
|
|
|
|
data: {
|
|
|
|
|
params: params.params,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
true,
|
|
|
|
|
);
|
2025-07-18 17:54:32 +08:00
|
|
|
if (ret?.data?.code !== 0) {
|
|
|
|
|
message.error(ret?.data?.message);
|
|
|
|
|
}
|
|
|
|
|
return ret?.data?.data;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, debugSingle: mutateAsync };
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useFetchInputForm = (componentId?: string) => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
|
|
|
|
|
const { data } = useQuery<Record<string, any>>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchInputForm],
|
|
|
|
|
initialData: {},
|
|
|
|
|
enabled: !!id && !!componentId,
|
|
|
|
|
queryFn: async () => {
|
2025-07-24 19:51:08 +08:00
|
|
|
const { data } = await agentService.inputForm(
|
2026-04-24 10:02:22 +08:00
|
|
|
{ agentId: id as string, componentId: componentId as string },
|
2025-07-24 19:51:08 +08:00
|
|
|
true,
|
|
|
|
|
);
|
2025-07-18 17:54:32 +08:00
|
|
|
|
|
|
|
|
return data.data;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return data;
|
|
|
|
|
};
|
2025-07-21 16:28:06 +08:00
|
|
|
|
|
|
|
|
export const useFetchVersionList = () => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
const { data, isFetching: loading } = useQuery<
|
2026-03-10 14:25:27 +08:00
|
|
|
Array<{ created_at: string; title: string; id: string; release?: boolean }>
|
2025-07-21 16:28:06 +08:00
|
|
|
>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchVersionList],
|
|
|
|
|
initialData: [],
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
2025-07-23 15:09:24 +08:00
|
|
|
const { data } = await agentService.fetchVersionList(id);
|
2025-07-21 16:28:06 +08:00
|
|
|
|
|
|
|
|
return data?.data ?? [];
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading };
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useFetchVersion = (
|
|
|
|
|
version_id?: string,
|
|
|
|
|
): {
|
|
|
|
|
data?: IFlow;
|
|
|
|
|
loading: boolean;
|
|
|
|
|
} => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { id } = useParams();
|
2025-07-21 16:28:06 +08:00
|
|
|
const { data, isFetching: loading } = useQuery({
|
2026-04-24 10:02:22 +08:00
|
|
|
queryKey: [AgentApiAction.FetchVersion, id, version_id],
|
2025-07-21 16:28:06 +08:00
|
|
|
initialData: undefined,
|
|
|
|
|
gcTime: 0,
|
2026-04-24 10:02:22 +08:00
|
|
|
enabled: !!id && !!version_id,
|
2025-07-21 16:28:06 +08:00
|
|
|
queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
if (!id || !version_id) return undefined;
|
2025-07-21 16:28:06 +08:00
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.fetchVersion({
|
|
|
|
|
agentId: id,
|
|
|
|
|
versionId: version_id,
|
|
|
|
|
});
|
2025-07-21 16:28:06 +08:00
|
|
|
|
|
|
|
|
return data?.data ?? undefined;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading };
|
|
|
|
|
};
|
2025-07-23 18:10:18 +08:00
|
|
|
|
2025-07-30 09:48:51 +08:00
|
|
|
export const useFetchAgentLog = (searchParams: IAgentLogsRequest) => {
|
|
|
|
|
const { id } = useParams();
|
2026-06-25 13:49:25 +08:00
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
|
|
|
|
} = useQuery<IAgentLogsResponse>({
|
2026-03-17 18:51:26 +08:00
|
|
|
queryKey: [AgentApiAction.FetchAgentLog, id, searchParams],
|
2025-07-30 09:48:51 +08:00
|
|
|
initialData: {} as IAgentLogsResponse,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
const { data } = await fetchAgentLogsByCanvasId(id as string, {
|
|
|
|
|
...searchParams,
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
return { total: data?.total ?? 0, sessions: data?.data ?? [] };
|
2025-07-30 09:48:51 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2026-06-25 13:49:25 +08:00
|
|
|
return { data, loading, refetch };
|
2025-07-30 09:48:51 +08:00
|
|
|
};
|
2025-07-31 09:34:45 +08:00
|
|
|
|
2026-02-09 19:53:51 +08:00
|
|
|
export const useFetchSessionsByCanvasId = () => {
|
|
|
|
|
const { id: canvasId } = useParams();
|
|
|
|
|
const { data: tenantInfo } = useFetchTenantInfo();
|
|
|
|
|
|
|
|
|
|
const { data, isFetching: loading } = useQuery<IAgentLogsResponse>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchSessionsByCanvasId, canvasId],
|
|
|
|
|
initialData: { total: 0, sessions: [] } as IAgentLogsResponse,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
enabled: !!canvasId && !isEmpty(tenantInfo),
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
if (!canvasId) {
|
|
|
|
|
return { total: 0, sessions: [] };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { data } = await fetchAgentLogsByCanvasId(canvasId, {
|
|
|
|
|
page: 1,
|
2026-06-09 16:56:47 +08:00
|
|
|
page_size: 100,
|
2026-02-09 19:53:51 +08:00
|
|
|
exp_user_id: tenantInfo.tenant_id,
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-24 10:02:22 +08:00
|
|
|
return { total: data?.total ?? 0, sessions: data?.data ?? [] };
|
2026-02-09 19:53:51 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
data: data?.sessions ?? [],
|
|
|
|
|
loading,
|
|
|
|
|
total: data?.total ?? 0,
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
2025-07-31 09:34:45 +08:00
|
|
|
export const useFetchExternalAgentInputs = () => {
|
|
|
|
|
const { sharedId } = useGetSharedChatSearchParams();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
2025-08-01 12:38:29 +08:00
|
|
|
} = useQuery<IInputs>({
|
2026-01-06 11:01:16 +08:00
|
|
|
queryKey: [AgentApiAction.FetchExternalAgentInputs, sharedId],
|
2025-08-01 12:38:29 +08:00
|
|
|
initialData: {} as IInputs,
|
2025-07-31 09:34:45 +08:00
|
|
|
refetchOnReconnect: false,
|
2026-01-06 11:01:16 +08:00
|
|
|
// refetchOnMount: false,
|
2025-07-31 09:34:45 +08:00
|
|
|
refetchOnWindowFocus: false,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
enabled: !!sharedId,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
const { data } = await agentService.fetchExternalAgentInputs(sharedId!);
|
|
|
|
|
|
|
|
|
|
return data?.data ?? {};
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, refetch };
|
|
|
|
|
};
|
2025-08-08 11:00:55 +08:00
|
|
|
|
2025-09-05 15:48:57 +08:00
|
|
|
export const useFetchPrompt = () => {
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
|
|
|
|
} = useQuery<Record<string, string>>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchPrompt],
|
|
|
|
|
refetchOnReconnect: false,
|
|
|
|
|
refetchOnMount: false,
|
|
|
|
|
refetchOnWindowFocus: false,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
const { data } = await agentService.fetchPrompt();
|
|
|
|
|
|
|
|
|
|
return data?.data ?? {};
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, refetch };
|
|
|
|
|
};
|
2025-10-09 12:36:19 +08:00
|
|
|
|
|
|
|
|
export const useFetchAgentList = ({
|
|
|
|
|
canvas_category,
|
|
|
|
|
}: IPipeLineListRequest) => {
|
|
|
|
|
const { data, isFetching: loading } = useQuery<{
|
|
|
|
|
canvas: IFlow[];
|
|
|
|
|
total: number;
|
|
|
|
|
}>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchAgentList],
|
|
|
|
|
initialData: { canvas: [], total: 0 },
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await fetchPipeLineList({
|
|
|
|
|
canvas_category,
|
|
|
|
|
});
|
2025-10-09 12:36:19 +08:00
|
|
|
|
|
|
|
|
return data?.data ?? [];
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading };
|
|
|
|
|
};
|
|
|
|
|
|
2026-07-20 16:05:03 +08:00
|
|
|
export const BuiltinPipelineKeys = {
|
|
|
|
|
list: (type: string) =>
|
|
|
|
|
[AgentApiAction.FetchBuiltinPipelineList, type] as const,
|
|
|
|
|
detail: (id: string) =>
|
|
|
|
|
[AgentApiAction.FetchBuiltinPipelineDetail, id] as const,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useFetchBuiltinPipelines = (type = 'builtin', enabled = true) => {
|
|
|
|
|
const { data, isFetching: loading } = useQuery<IBuiltinPipelineListResponse>({
|
|
|
|
|
queryKey: BuiltinPipelineKeys.list(type),
|
|
|
|
|
initialData: { canvas: [], total: 0 },
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
enabled,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
const { data } = await agentService.listBuiltinPipelines(
|
|
|
|
|
{ params: { type } },
|
|
|
|
|
true,
|
|
|
|
|
);
|
|
|
|
|
return data?.data ?? { canvas: [], total: 0 };
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const options =
|
|
|
|
|
data?.canvas?.map((item) => ({
|
|
|
|
|
label: item.title,
|
|
|
|
|
value: item.id,
|
|
|
|
|
})) ?? [];
|
|
|
|
|
|
|
|
|
|
return { data, loading, options };
|
|
|
|
|
};
|
|
|
|
|
|
2025-10-09 12:36:19 +08:00
|
|
|
export const useCancelDataflow = () => {
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.CancelDataflow],
|
|
|
|
|
mutationFn: async (taskId: string) => {
|
|
|
|
|
const ret = await agentService.cancelDataflow(taskId);
|
|
|
|
|
if (ret?.data?.code === 0) {
|
|
|
|
|
message.success('success');
|
|
|
|
|
} else {
|
|
|
|
|
message.error(ret?.data?.data);
|
|
|
|
|
}
|
|
|
|
|
return ret?.data?.code;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, cancelDataflow: mutateAsync };
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// export const useFetchKnowledgeList = () => {
|
|
|
|
|
// const { data, isFetching: loading } = useQuery<IFlow[]>({
|
|
|
|
|
// queryKey: [AgentApiAction.FetchAgentList],
|
|
|
|
|
// initialData: [],
|
|
|
|
|
// gcTime: 0, // https://tanstack.com/query/latest/docs/framework/react/guides/caching?from=reactQueryV3
|
|
|
|
|
// queryFn: async () => {
|
2026-04-24 10:02:22 +08:00
|
|
|
// const { data } = await agentService.listAgents();
|
2025-10-09 12:36:19 +08:00
|
|
|
|
|
|
|
|
// return data?.data ?? [];
|
|
|
|
|
// },
|
|
|
|
|
// });
|
|
|
|
|
|
|
|
|
|
// return { list: data, loading };
|
|
|
|
|
// };
|
2025-11-11 15:21:08 +08:00
|
|
|
|
|
|
|
|
export function useCancelConversation() {
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.CancelCanvas],
|
|
|
|
|
mutationFn: async (taskId: string) => {
|
|
|
|
|
const ret = await agentService.cancelCanvas(taskId);
|
|
|
|
|
|
|
|
|
|
return ret?.data?.code;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, cancelConversation: mutateAsync };
|
|
|
|
|
}
|
2025-12-02 17:24:29 +08:00
|
|
|
|
2026-04-27 03:27:39 +00:00
|
|
|
export const useFetchFlowSSE = (): {
|
2025-12-02 17:24:29 +08:00
|
|
|
data: IFlow;
|
|
|
|
|
loading: boolean;
|
|
|
|
|
refetch: () => void;
|
|
|
|
|
} => {
|
|
|
|
|
const { sharedId } = useGetSharedChatSearchParams();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
|
|
|
|
} = useQuery({
|
2026-04-24 10:02:22 +08:00
|
|
|
queryKey: [AgentApiAction.FetchSharedAgent, sharedId],
|
2025-12-02 17:24:29 +08:00
|
|
|
initialData: {} as IFlow,
|
2026-04-27 03:27:39 +00:00
|
|
|
enabled: !!sharedId,
|
2025-12-02 17:24:29 +08:00
|
|
|
refetchOnReconnect: false,
|
|
|
|
|
refetchOnMount: false,
|
|
|
|
|
refetchOnWindowFocus: false,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
if (!sharedId) return {};
|
2026-04-24 10:02:22 +08:00
|
|
|
const { data } = await agentService.getAgent(sharedId);
|
2025-12-02 17:24:29 +08:00
|
|
|
|
|
|
|
|
const messageList = buildMessageListWithUuid(
|
|
|
|
|
get(data, 'data.dsl.messages', []),
|
|
|
|
|
);
|
|
|
|
|
set(data, 'data.dsl.messages', messageList);
|
|
|
|
|
|
|
|
|
|
return data?.data ?? {};
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, refetch };
|
|
|
|
|
};
|
2025-12-19 12:56:56 +08:00
|
|
|
|
|
|
|
|
export const useFetchWebhookTrace = (autoStart: boolean = true) => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
const [currentWebhookId, setCurrentWebhookId] = useState<string>('');
|
|
|
|
|
const [currentNextSinceTs, setCurrentNextSinceTs] = useState<number>(0);
|
|
|
|
|
const [shouldPoll, setShouldPoll] = useState(autoStart);
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isFetching: loading,
|
|
|
|
|
refetch,
|
|
|
|
|
} = useQuery<IWebhookTrace>({
|
|
|
|
|
queryKey: [AgentApiAction.FetchWebhookTrace, id],
|
|
|
|
|
refetchOnReconnect: false,
|
|
|
|
|
refetchOnMount: false,
|
|
|
|
|
refetchOnWindowFocus: false,
|
|
|
|
|
refetchIntervalInBackground: false,
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
enabled: !!id && shouldPoll,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
if (!id) return {};
|
|
|
|
|
|
|
|
|
|
const payload: IAgentWebhookTraceRequest =
|
|
|
|
|
{} as IAgentWebhookTraceRequest;
|
|
|
|
|
|
|
|
|
|
if (currentNextSinceTs) {
|
|
|
|
|
payload['since_ts'] = currentNextSinceTs;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (currentWebhookId) {
|
|
|
|
|
payload['webhook_id'] = currentWebhookId;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { data } = await fetchWebhookTrace(id, payload);
|
|
|
|
|
|
|
|
|
|
const result = data.data ?? {};
|
|
|
|
|
|
|
|
|
|
if (result.webhook_id && result.webhook_id !== currentWebhookId) {
|
|
|
|
|
setCurrentWebhookId(result.webhook_id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
currentNextSinceTs === 0 &&
|
|
|
|
|
result.next_since_ts &&
|
|
|
|
|
result.next_since_ts !== currentNextSinceTs
|
|
|
|
|
) {
|
|
|
|
|
setCurrentNextSinceTs(result.next_since_ts);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (result.finished) {
|
|
|
|
|
setShouldPoll(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
},
|
|
|
|
|
refetchInterval: shouldPoll ? 3000 : false,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
data,
|
|
|
|
|
loading,
|
|
|
|
|
refetch,
|
|
|
|
|
isPolling: shouldPoll,
|
|
|
|
|
currentWebhookId,
|
|
|
|
|
currentNextSinceTs,
|
|
|
|
|
};
|
|
|
|
|
};
|
2026-02-09 19:53:51 +08:00
|
|
|
|
|
|
|
|
export function useCreateAgentSession() {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.CreateAgentSession],
|
|
|
|
|
mutationFn: async (payload: { id: string; name: string }) => {
|
|
|
|
|
const { data } = await createAgentSession(payload);
|
|
|
|
|
|
|
|
|
|
if (data.code === 0) {
|
|
|
|
|
queryClient.invalidateQueries({
|
|
|
|
|
queryKey: [AgentApiAction.FetchSessionsByCanvasId],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return data?.data ?? {};
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, createAgentSession: mutateAsync };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useDeleteAgentSession() {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.DeleteAgentSession],
|
|
|
|
|
mutationFn: async ({
|
|
|
|
|
canvasId,
|
|
|
|
|
sessionId,
|
|
|
|
|
}: {
|
|
|
|
|
canvasId: string;
|
|
|
|
|
sessionId: string;
|
|
|
|
|
}) => {
|
|
|
|
|
const { data } = await deleteAgentSession(canvasId, sessionId);
|
|
|
|
|
|
|
|
|
|
if (data.code === 0) {
|
|
|
|
|
queryClient.invalidateQueries({
|
|
|
|
|
queryKey: [AgentApiAction.FetchSessionsByCanvasId],
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return data?.code ?? -1;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, deleteAgentSession: mutateAsync };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useFetchSessionManually() {
|
|
|
|
|
const { id: canvasId } = useParams();
|
|
|
|
|
|
|
|
|
|
const {
|
|
|
|
|
data,
|
|
|
|
|
isPending: loading,
|
|
|
|
|
mutateAsync,
|
|
|
|
|
} = useMutation<IAgentLogResponse, unknown, string>({
|
|
|
|
|
mutationKey: [AgentApiAction.FetchSessionByIdManually, canvasId],
|
|
|
|
|
mutationFn: async (sessionId) => {
|
|
|
|
|
if (!canvasId || !sessionId) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { data } = await fetchAgentLogsById(canvasId, sessionId);
|
|
|
|
|
|
|
|
|
|
return data?.data;
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { data, loading, fetchSessionManually: mutateAsync };
|
|
|
|
|
}
|
2026-03-17 18:51:26 +08:00
|
|
|
|
|
|
|
|
export const useExportAgentLog = () => {
|
|
|
|
|
const { id } = useParams();
|
|
|
|
|
const { mutateAsync, isPending: loading } = useMutation({
|
|
|
|
|
mutationKey: [AgentApiAction.FetchAgentLog, 'export', id],
|
|
|
|
|
mutationFn: async (searchParams: IAgentLogsRequest) => {
|
|
|
|
|
const { data } = await fetchAgentLogsByCanvasId(id as string, {
|
|
|
|
|
...searchParams,
|
|
|
|
|
});
|
|
|
|
|
|
2026-06-17 16:20:26 +08:00
|
|
|
return data?.data ?? [];
|
2026-03-17 18:51:26 +08:00
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { exportLogs: mutateAsync, loading };
|
|
|
|
|
};
|
2026-07-20 16:05:03 +08:00
|
|
|
|
|
|
|
|
export const useFetchPipelineDslByPipelineId = (
|
|
|
|
|
pipelineId?: string,
|
|
|
|
|
isBuiltin = false,
|
|
|
|
|
) => {
|
|
|
|
|
const { data: dsl, isFetching: loading } = useQuery({
|
|
|
|
|
queryKey: isBuiltin
|
|
|
|
|
? BuiltinPipelineKeys.detail(pipelineId!)
|
|
|
|
|
: [AgentApiAction.FetchPipelineNodes, pipelineId],
|
|
|
|
|
initialData: {},
|
|
|
|
|
gcTime: 0,
|
|
|
|
|
enabled: !!pipelineId,
|
|
|
|
|
queryFn: async () => {
|
|
|
|
|
const { data } = isBuiltin
|
|
|
|
|
? await agentService.getBuiltinPipeline(pipelineId!)
|
|
|
|
|
: await agentService.getAgent(pipelineId!);
|
|
|
|
|
const flow = data?.data;
|
|
|
|
|
return flow?.dsl ?? {};
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return { dsl, loading };
|
|
|
|
|
};
|