Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix(web): stabilize Logs loading and conversation dialogs (#44338)
yyhee5fe8bf3a1b
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 9cc0bf14357..7e3c911e057 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -288,19 +288,6 @@"count": 1}},- "web/app/components/app/log/index.tsx": {- "eslint-react/set-state-in-effect": {- "count": 1- }- },- "web/app/components/app/log/list.tsx": {- "eslint-react/set-state-in-effect": {- "count": 2- },- "typescript/no-explicit-any": {- "count": 3- }- },"web/app/components/app/log/var-panel.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 2diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsxindex aebcac0c2eb..327a199c835 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/logs/page.tsx@@ -1,21 +1,7 @@-import { Suspense } from 'react'import Main from '@/app/components/app/log-annotation'import { PageType } from '@/app/components/base/features/new-feature-panel/annotation-reply/type'-import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'export default async function Page({ params }: { params: Promise<{ appId: string }> }) {const { appId } = await params- return (- <Suspense- fallback={- <SkeletonContainer className="gap-4 p-6" aria-busy="true">- <SkeletonRectangle className="h-6 w-48" />- <SkeletonRectangle className="h-10 w-full" />- <SkeletonRectangle className="h-96 w-full" />- </SkeletonContainer>- }- >- <Main appId={appId} pageType={PageType.log} />- </Suspense>- )+ return <Main appId={appId} pageType={PageType.log} />}diff --git a/web/app/components/app/log/__tests__/filter.spec.tsx b/web/app/components/app/log/__tests__/filter.spec.tsxindex a05538dc978..8d7fee6b9c8 100644--- a/web/app/components/app/log/__tests__/filter.spec.tsx+++ b/web/app/components/app/log/__tests__/filter.spec.tsx@@ -170,11 +170,12 @@ it('omits chat sorting for completion logs', () => {})it.each(['loading', 'unavailable'] as const)(- 'does not expose filters while annotations are %s',+ 'keeps filters visible while annotations are %s',(state) => {mockAnnotationsCountLoading = state === 'loading'mockAnnotationsCountData = nullrender(<ControlledFilter />)- expect(screen.queryByRole('searchbox')).not.toBeInTheDocument()+ expect(screen.getByRole('searchbox')).toBeEnabled()+ expect(screen.getByRole('combobox', { name: 'appLog.filter.annotation.all' })).toBeDisabled()},)diff --git a/web/app/components/app/log/__tests__/index.spec.tsx b/web/app/components/app/log/__tests__/index.spec.tsxindex 95241788329..3af8ecc29fd 100644--- a/web/app/components/app/log/__tests__/index.spec.tsx+++ b/web/app/components/app/log/__tests__/index.spec.tsx@@ -5,8 +5,20 @@ import dayjs from 'dayjs'import { APP_PAGE_LIMIT } from '@/config'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'+import { createReactI18nextMock } from '@/test/i18n-mock'import Logs from '../index'+vi.mock('react-i18next', () => {+ const mock = createReactI18nextMock()+ return {+ ...mock,+ useTranslation: (...args: Parameters<typeof mock.useTranslation>) => ({+ ...mock.useTranslation(...args),+ ready: true,+ }),+ }+})+vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.com${path}`,}))@@ -83,7 +95,7 @@ describe('Logs', () => {screen.getByRole('link', { name: /(?:^|\.)operation\.learnMore(?=$|:)/ }),).toHaveAttribute('href', 'https://docs.example.com/use-dify/monitor/logs')expect(screen.getByText('retention-upgrade-notice')).toBeInTheDocument()- expect(screen.getByText('loading-logs')).toBeInTheDocument()+ expect(screen.getByText('list-total-')).toBeInTheDocument()})it('should render the empty state for completion apps without logs', async () => {@@ -102,7 +114,7 @@ describe('Logs', () => {params: { app_id: 'app-2' },}),)- expect(await screen.findByText('empty-logs')).toBeInTheDocument()+ expect(await screen.findByText('list-total-0')).toBeInTheDocument()})it('should update the page query parameter when pagination changes', async () => {diff --git a/web/app/components/app/log/__tests__/list-utils.spec.ts b/web/app/components/app/log/__tests__/list-utils.spec.tsindex 1a34227641e..5d31b7fa61e 100644--- a/web/app/components/app/log/__tests__/list-utils.spec.ts+++ b/web/app/components/app/log/__tests__/list-utils.spec.ts@@ -12,7 +12,6 @@ import {getFormattedChatList,getThreadChatItems,isNearTopLoadMore,- mergePaginatedChatItems,mergeUniqueChatItems,} from '../list-utils'@@ -138,7 +137,7 @@ describe('log list utils', () => {)})- it('should merge unique chat items and handle pagination retries', () => {+ it('should prepend new chat items without duplicating existing messages', () => {const prevItems = createChatItems()const merged = mergeUniqueChatItems(prevItems, [{ id: 'answer-2', content: 'reply', isAnswer: true } as IChatItem,@@ -152,30 +151,6 @@ describe('log list utils', () => {'question-2','answer-2',])-- expect(- mergePaginatedChatItems({- maxRetryCount: 3,- newItems: [],- prevItems,- retryCount: 1,- }),- ).toEqual({- items: prevItems,- retryCount: 2,- })-- expect(- mergePaginatedChatItems({- maxRetryCount: 3,- newItems: [],- prevItems,- retryCount: 3,- }),- ).toEqual({- items: prevItems,- retryCount: 0,- })})it('should build thread state and support switching siblings', () => {diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsxindex b84149ee671..f0c5b567ed8 100644--- a/web/app/components/app/log/__tests__/list.spec.tsx+++ b/web/app/components/app/log/__tests__/list.spec.tsx@@ -9,7 +9,7 @@ import {zConversationDetail,zConversationMessageDetail,} from '@dify/contracts/api/console/apps/zod.gen'-import { fireEvent, screen, waitFor, within } from '@testing-library/react'+import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { toast } from '@/app/notifications'@@ -20,6 +20,7 @@ import {seedModelProviderQueries,} from '@/test/console/model-provider'import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'+import { createDeferred } from '@/test/deferred'import { createAppDetailFixture } from '@/test/fixtures/app'import { createNuqsTestWrapper } from '@/test/nuqs-testing'import ConversationList from '../list'@@ -51,6 +52,7 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'apps.byAppId.chatMessages.get': (input) => api.messages(input),'apps.byAppId.chatConversations.byConversationId.get': (input) => api.chatDetail(input),'apps.byAppId.completionConversations.byConversationId.get': (input) =>api.completionDetail(input),@@ -615,3 +617,80 @@ it('shows each chatflow status and its conversation feedback counts', () => {expect(row.getByText('3')).toBeVisible()}})++it('keeps the table and close action available while conversation requests resolve independently', async () => {+ const user = userEvent.setup()+ const detail = createDeferred<ConversationDetail>()+ const messages =+ createDeferred<Awaited<ReturnType<typeof consoleClient.apps.byAppId.chatMessages.get>>>()+ api.chatDetail.mockReturnValue(detail.promise)+ api.messages.mockReturnValue(messages.promise)+ renderConversationList()+ await user.click(screen.getByText('hello world'))+ const dialog = await screen.findByRole('dialog', { name: 'appLog.detail.conversationId' })+ expect(within(dialog).getByRole('button', { name: 'common.operation.close' })).toBeVisible()+ expect(screen.getByText('hello world')).toBeVisible()+ expect(api.messages).toHaveBeenCalled()+ await act(async () => {+ detail.resolve(createChatDetail())+ })+ expect(screen.getByText('hello world')).toBeVisible()+ expect(within(dialog).queryByText('Assistant reply message-1')).not.toBeInTheDocument()+ await act(async () => {+ messages.resolve({ data: [createChatMessage('message-1')], has_more: false, limit: 10 })+ })+ expect(await within(dialog).findByText('Assistant reply message-1')).toBeVisible()+ expect(screen.getByText('hello world')).toBeVisible()+})++it('opens a deep-linked conversation while the list is still pending', async () => {+ const { wrapper: UrlState } = createNuqsTestWrapper({+ searchParams: '?conversation_id=conversation-1',+ })+ renderWithConsoleQuery(+ <UrlState>+ <ConversationList+ appDetail={createAppDetailFixture({ id: 'app-1', mode: 'chat' })}+ onRefresh={onRefresh}+ />+ </UrlState>,+ { queryClient: createClient() },+ )+ expect(screen.getByText('appLog.table.header.summary')).toBeVisible()+ expect(await screen.findByText('Assistant reply message-1')).toBeVisible()+})++it('keeps desktop details open while interacting outside and switching to another row', async () => {+ const user = userEvent.setup()+ const { wrapper: UrlState } = createNuqsTestWrapper({ searchParams: '' })+ const logs = createLogs()+ logs.data.push({ ...logs.data[0]!, id: 'conversation-2', name: 'another conversation' })+ logs.total = 2+ api.messages.mockImplementation(async ({ query }) => ({+ data: [+ createChatMessage(query.conversation_id === 'conversation-2' ? 'message-2' : 'message-1'),+ ],+ has_more: false,+ limit: 10,+ }))+ renderWithConsoleQuery(+ <UrlState>+ <button type="button">Background action</button>+ <ConversationList+ appDetail={createAppDetailFixture({ id: 'app-1', mode: 'chat' })}+ logs={logs}+ onRefresh={onRefresh}+ />+ </UrlState>,+ { queryClient: createClient() },+ )+ await user.click(screen.getByText('hello world'))+ expect(await screen.findByText('Assistant reply message-1')).toBeVisible()+ await user.click(screen.getByRole('button', { name: 'Background action' }))+ expect(screen.getByRole('dialog')).toBeVisible()+ expect(screen.getByRole('button', { name: 'Background action' })).toHaveFocus()+ await user.click(screen.getByText('another conversation'))+ expect(await screen.findByText('Assistant reply message-2')).toBeVisible()+ expect(screen.queryByText('Assistant reply message-1')).not.toBeInTheDocument()+ expect(onRefresh).not.toHaveBeenCalled()+})diff --git a/web/app/components/app/log/conversation-detail.tsx b/web/app/components/app/log/conversation-detail.tsxnew file mode 100644index 00000000000..7faaef76228--- /dev/null+++ b/web/app/components/app/log/conversation-detail.tsx@@ -0,0 +1,555 @@+'use client'++import type {+ AppDetailWithSite,+ ConversationDetail as ChatConversationDetail,+ ConversationMessageDetail,+ GetAppsByAppIdChatMessagesData,+} from '@dify/contracts/api/console/apps/types.gen'+import type { FeedbackFunc, IChatItem } from '@/app/components/base/chat/chat/type'+import type { ChatConfig } from '@/app/components/base/chat/types'+import { Button } from '@langgenius/dify-ui/button'+import { DialogClose, DialogTitle } from '@langgenius/dify-ui/dialog'+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import {+ QueryErrorResetBoundary,+ skipToken,+ useQuery,+ useSuspenseQueries,+ useSuspenseQuery,+} from '@tanstack/react-query'+import { noop } from 'es-toolkit/function'+import { Suspense, useCallback, useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import TextGeneration from '@/app/components/app/text-generate/item'+import AgentLogModal from '@/app/components/base/agent-log-modal'+import Chat from '@/app/components/base/chat/chat'+import CopyIcon from '@/app/components/base/copy-icon'+import ErrorBoundary from '@/app/components/base/error-boundary'+import MessageLogModal from '@/app/components/base/message-log-modal'+import PromptLogModal from '@/app/components/base/prompt-log-modal'+import { WorkflowContextProvider } from '@/app/components/workflow/context'+import { toast } from '@/app/notifications'+import { userProfileQueryOptions } from '@/features/account-profile/client'+import useTimestamp from '@/hooks/use-timestamp'+import { consoleClient, consoleQuery } from '@/service/console'+import { AppSourceType } from '@/service/share'+import {+ applyAnnotationAdded,+ applyAnnotationEdited,+ applyAnnotationRemoved,+ buildChatThreadState,+ getAdminFeedback,+ getCompletionMessageFiles,+ getDetailVarList,+ getFormattedChatList,+ getLogModelInfo,+ getStringInputs,+ getThreadChatItems,+ isNearTopLoadMore,+ mergeUniqueChatItems,+} from './list-utils'+import { ConversationSkeleton } from './loading'+import ModelInfo from './model-info'+import VarPanel from './var-panel'++type Messages = Awaited<ReturnType<typeof consoleClient.apps.byAppId.chatMessages.get>>++type IDetailPanel = {+ appDetail: AppDetailWithSite+ detail: ChatConversationDetail | ConversationMessageDetail+ onFeedback: FeedbackFunc+ initialMessages?: Messages+}++function DetailPanel({ appDetail, detail, onFeedback, initialMessages }: IDetailPanel) {+ const MIN_ITEMS_FOR_SCROLL_LOADING = 8+ const SCROLL_DEBOUNCE_MS = 200+ const { data: timezone } = useQuery({+ ...userProfileQueryOptions(),+ select: (data) => data.profile.timezone ?? undefined,+ })+ const [selectedLogItem, setSelectedLogItem] = useState<IChatItem>()+ const { t } = useTranslation(['appLog', 'common'])+ const [hasMore, setHasMore] = useState(initialMessages?.has_more ?? false)+ const [varValues, setVarValues] = useState(() =>+ getStringInputs(initialMessages?.data.at(-1)?.inputs ?? {}),+ )+ const lastLoadTimeRef = useRef(0)+ const [allChatItems, setAllChatItems] = useState(() =>+ getFormattedChatList(+ initialMessages?.data ?? [],+ detail.id,+ timezone!,+ t(($) => $.dateTimeFormat, { ns: 'appLog' }),+ ),+ )+ const [selectedMessageId, setSelectedMessageId] = useState<string>()+ const {+ chatItemTree,+ oldestAnswerId,+ threadChatItems: defaultThread,+ } = buildChatThreadState({+ allChatItems,+ hasMore,+ introduction: 'introduction' in detail ? (detail.introduction ?? undefined) : undefined,+ })+ const threadChatItems = selectedMessageId+ ? getThreadChatItems(chatItemTree, selectedMessageId)+ : defaultThread+ const switchSibling = setSelectedMessageId++ const handleAnnotationEdited = useCallback(+ (query: string, answer: string, index: number) => {+ setAllChatItems(applyAnnotationEdited(allChatItems, query, answer, index))+ },+ [allChatItems],+ )+ const handleAnnotationAdded = useCallback(+ (annotationId: string, authorName: string, query: string, answer: string, index: number) => {+ setAllChatItems(+ applyAnnotationAdded(allChatItems, annotationId, authorName, query, answer, index),+ )+ },+ [allChatItems],+ )+ const handleAnnotationRemoved = useCallback(+ async (index: number): Promise<boolean> => {+ const annotation = allChatItems[index]?.annotation++ try {+ if (annotation?.id) {+ await consoleClient.apps.byAppId.annotations.byAnnotationId.delete({+ params: { app_id: appDetail.id, annotation_id: annotation.id },+ })+ }++ setAllChatItems(applyAnnotationRemoved(allChatItems, index))++ toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))+ return true+ } catch {+ toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))+ return false+ }+ },+ [allChatItems, appDetail.id, t],+ )++ const [isLoading, setIsLoading] = useState(false)++ const loadMoreMessages = useCallback(async () => {+ if (isLoading || !hasMore || !appDetail.id || !detail.id) return++ // Throttle using ref to persist across re-renders+ const now = Date.now()+ if (now - lastLoadTimeRef.current < SCROLL_DEBOUNCE_MS) return+ lastLoadTimeRef.current = now++ setIsLoading(true)++ try {+ const params: GetAppsByAppIdChatMessagesData['query'] = {+ conversation_id: detail.id,+ limit: 10,+ }++ // Use ref for pagination anchor to avoid stale closure issues+ if (oldestAnswerId) {+ params.first_id = oldestAnswerId+ }++ const messageRes = await consoleClient.apps.byAppId.chatMessages.get({+ params: { app_id: appDetail.id },+ query: params,+ })++ if (!messageRes.data || messageRes.data.length === 0) {+ setHasMore(false)+ return+ }++ if (messageRes.data.length > 0) {+ const varValues = getStringInputs(messageRes.data.at(-1)!.inputs)+ setVarValues(varValues)+ }++ setHasMore(messageRes.has_more)++ const newItems = getFormattedChatList(+ messageRes.data,+ detail.id,+ timezone!,+ t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,+ )++ setAllChatItems((items) => mergeUniqueChatItems(items, newItems))+ } catch (error) {+ console.error(error)+ setHasMore(false)+ } finally {+ setIsLoading(false)+ }+ }, [detail.id, hasMore, isLoading, timezone, t, appDetail, oldestAnswerId])++ const handleScroll = useCallback(() => {+ const scrollableDiv = document.getElementById('scrollableDiv')+ if (!scrollableDiv) return+ const clientHeight = scrollableDiv.clientHeight+ const scrollHeight = scrollableDiv.scrollHeight+ const currentScrollTop = scrollableDiv.scrollTop+ // currentScrollTop is negative due to column-reverse flex direction+ const isNearTop = isNearTopLoadMore({+ clientHeight,+ scrollHeight,+ scrollTop: currentScrollTop,+ })++ if (isNearTop && hasMore && !isLoading) {+ loadMoreMessages()+ }+ }, [hasMore, isLoading, loadMoreMessages])++ const isChatMode = appDetail.mode !== 'completion'+ const isAdvanced = appDetail.mode === 'advanced-chat'+ const logKind = selectedLogItem?.workflow_run_id+ ? 'workflow'+ : selectedLogItem?.agent_thoughts?.length+ ? 'agent'+ : selectedLogItem?.log+ ? 'prompt'+ : undefined++ const varList = getDetailVarList(detail, varValues)+ const message_files = getCompletionMessageFiles(detail, isChatMode)+ const completionMessage = 'message' in detail ? detail.message : undefined++ const [width, setWidth] = useState(0)+ const ref = useRef<HTMLDivElement>(null)++ const adjustModalWidth = () => {+ if (ref.current) setWidth(document.body.clientWidth - (ref.current?.clientWidth + 16) - 8)+ }++ useEffect(() => {+ const raf = requestAnimationFrame(adjustModalWidth)+ return () => cancelAnimationFrame(raf)+ }, [])++ return (+ <div ref={ref} className="flex min-h-0 flex-1 flex-col">+ {/* Panel Body */}+ <div className="shrink-0 px-1 pt-1">+ <div className="rounded-t-xl bg-background-section-burn p-3 pb-2">+ {(varList.length > 0 || (!isChatMode && message_files.length > 0)) && (+ <VarPanel varList={varList} message_files={message_files} />+ )}+ </div>+ </div>+ <div className="mx-1 mb-1 grow overflow-auto rounded-b-xl bg-background-section-burn">+ {!isChatMode ? (+ completionMessage && (+ <div className="px-6 py-4">+ <div className="flex h-4.5 items-center space-x-3">+ <div className="system-xs-semibold-uppercase text-text-tertiary">+ {t(($) => $['table.header.output'], { ns: 'appLog' })}+ </div>+ <div+ className="h-px grow"+ style={{+ background:+ 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, rgb(243, 244, 246) 100%)',+ }}+ ></div>+ </div>+ <TextGeneration+ appSourceType={AppSourceType.webApp}+ className="mt-2"+ content={completionMessage.answer}+ messageId={completionMessage.id}+ isError={false}+ onRetry={noop}+ supportFeedback+ feedback={getAdminFeedback(completionMessage.feedbacks)}+ onFeedback={(feedback) => {+ onFeedback(completionMessage.id, feedback).catch(noop)+ }}+ isShowTextToSpeech+ siteInfo={null}+ />+ </div>+ )+ ) : threadChatItems.length < MIN_ITEMS_FOR_SCROLL_LOADING ? (+ <div className="mb-4 pt-4">+ <Chat+ config={+ {+ appId: appDetail.id,+ text_to_speech: {+ enabled: true,+ },+ questionEditEnable: false,+ supportAnnotation: true,+ annotation_reply: {+ enabled: true,+ },+ supportFeedback: true,+ } as ChatConfig+ }+ chatList={threadChatItems}+ onAnnotationAdded={handleAnnotationAdded}+ onAnnotationEdited={handleAnnotationEdited}+ onAnnotationRemoved={handleAnnotationRemoved}+ onFeedback={onFeedback}+ noChatInput+ onOpenLog={isAdvanced ? setSelectedLogItem : undefined}+ hideProcessDetail+ chatContainerInnerClassName="px-3"+ switchSibling={switchSibling}+ />+ </div>+ ) : (+ <div+ className="py-4"+ id="scrollableDiv"+ role="log"+ aria-live="off"+ style={{+ display: 'flex',+ flexDirection: 'column-reverse',+ height: '100%',+ overflow: 'auto',+ }}+ onScroll={handleScroll}+ >+ {/* Put the scroll bar always on the bottom */}+ <div className="flex w-full flex-col-reverse" style={{ position: 'relative' }}>+ <Chat+ config={+ {+ appId: appDetail.id,+ text_to_speech: {+ enabled: true,+ },+ questionEditEnable: false,+ supportAnnotation: true,+ annotation_reply: {+ enabled: true,+ },+ supportFeedback: true,+ } as ChatConfig+ }+ chatList={threadChatItems}+ onAnnotationAdded={handleAnnotationAdded}+ onAnnotationEdited={handleAnnotationEdited}+ onAnnotationRemoved={handleAnnotationRemoved}+ onFeedback={onFeedback}+ noChatInput+ onOpenLog={isAdvanced ? setSelectedLogItem : undefined}+ hideProcessDetail+ chatContainerInnerClassName="px-3"+ switchSibling={switchSibling}+ />+ </div>+ {isLoading && (+ <div className="py-3 text-center">+ <div className="system-xs-regular text-text-tertiary">+ {t(($) => $['detail.loading'], { ns: 'appLog' })}+ ...+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ {logKind === 'workflow' && (+ <WorkflowContextProvider>+ <MessageLogModal+ appId={appDetail.id}+ width={width}+ currentLogItem={selectedLogItem}+ onCancel={() => setSelectedLogItem(undefined)}+ />+ </WorkflowContextProvider>+ )}+ {logKind === 'agent' && (+ <AgentLogModal+ appId={appDetail.id}+ floating+ width={width}+ currentLogItem={selectedLogItem}+ onCancel={() => setSelectedLogItem(undefined)}+ />+ )}+ {logKind === 'prompt' && (+ <PromptLogModal+ width={width}+ currentLogItem={selectedLogItem}+ onCancel={() => setSelectedLogItem(undefined)}+ />+ )}+ </div>+ )+}++type ConversationDetailProps = {+ appDetail: AppDetailWithSite+ conversationId: string+}++export function ConversationDetail({ appDetail, conversationId }: ConversationDetailProps) {+ const { t } = useTranslation(['appLog', 'common'])+ const { formatTime } = useTimestamp()+ const isChatMode = appDetail.mode !== 'completion'+ const input = { params: { app_id: appDetail.id, conversation_id: conversationId } }+ const chat = useQuery(+ consoleQuery.apps.byAppId.chatConversations.byConversationId.get.queryOptions({+ input: isChatMode ? input : skipToken,+ }),+ )+ const completion = useQuery(+ consoleQuery.apps.byAppId.completionConversations.byConversationId.get.queryOptions({+ input: !isChatMode ? input : skipToken,+ }),+ )+ const detailQuery = isChatMode ? chat : completion+ const detail = detailQuery.data+ const modelInfo = getLogModelInfo(detail?.model_config?.model)+ const handleFeedback: FeedbackFunc = async (messageId, { rating, content }) => {+ await consoleClient.apps.byAppId.feedbacks.post({+ params: { app_id: appDetail.id },+ body: { message_id: messageId, rating, content: content ?? undefined },+ })+ if (!isChatMode) await completion.refetch()+ }++ return (+ <div className="flex min-h-0 flex-1 flex-col rounded-xl border-[0.5px] border-components-panel-border">+ <div className="flex shrink-0 items-center gap-2 rounded-t-xl bg-components-panel-bg pt-3 pr-3 pb-2 pl-4">+ <div className="min-w-0">+ <DialogTitle className="sr-only">+ {isChatMode+ ? t(($) => $['detail.conversationId'], { ns: 'appLog' })+ : t(($) => $['detail.time'], { ns: 'appLog' })}+ </DialogTitle>+ <div aria-hidden="true" className="mb-0.5 system-xs-semibold-uppercase text-text-primary">+ {isChatMode+ ? t(($) => $['detail.conversationId'], { ns: 'appLog' })+ : t(($) => $['detail.time'], { ns: 'appLog' })}+ </div>+ {isChatMode ? (+ <div className="flex items-center system-2xs-regular-uppercase text-text-secondary">+ <Tooltip>+ <TooltipTrigger render={<span className="truncate">{conversationId}</span>} />+ <TooltipContent>{conversationId}</TooltipContent>+ </Tooltip>+ <CopyIcon content={conversationId} />+ </div>+ ) : (+ <div className="min-h-4 system-2xs-regular-uppercase text-text-secondary">+ {detail?.created_at+ ? formatTime(+ detail.created_at,+ t(($) => $.dateTimeFormat, { ns: 'appLog' }),+ )+ : null}+ </div>+ )}+ </div>+ <div className="flex grow flex-wrap items-center justify-end gap-y-1">+ <Suspense fallback={null}>+ {appDetail.mode !== 'advanced-chat' && modelInfo && <ModelInfo model={modelInfo} />}+ </Suspense>+ </div>+ <DialogClose+ render={+ <IconButton size="lg" aria-label={t(($) => $['operation.close'], { ns: 'common' })}>+ <span aria-hidden className="i-ri-close-line size-4 text-text-tertiary" />+ </IconButton>+ }+ />+ </div>+ <QueryErrorResetBoundary>+ {({ reset }) => (+ <ErrorBoundary+ onReset={reset}+ fallback={(_, retry) => (+ <div+ role="alert"+ className="flex flex-1 flex-col items-center justify-center gap-3 p-6"+ >+ <p>{t(($) => $['errorBoundary.title'], { ns: 'common' })}</p>+ <Button onClick={retry}>{t(($) => $['operation.retry'], { ns: 'common' })}</Button>+ </div>+ )}+ >+ <Suspense fallback={<ConversationSkeleton />}>+ {isChatMode ? (+ <ChatConversationContent+ appDetail={appDetail}+ conversationId={conversationId}+ onFeedback={handleFeedback}+ />+ ) : (+ <CompletionConversationContent+ appDetail={appDetail}+ conversationId={conversationId}+ onFeedback={handleFeedback}+ />+ )}+ </Suspense>+ </ErrorBoundary>+ )}+ </QueryErrorResetBoundary>+ </div>+ )+}++type ConversationContentProps = ConversationDetailProps & {+ onFeedback: FeedbackFunc+}++function ChatConversationContent({+ appDetail,+ conversationId,+ onFeedback,+}: ConversationContentProps) {+ const [detail, messages] = useSuspenseQueries({+ queries: [+ consoleQuery.apps.byAppId.chatConversations.byConversationId.get.queryOptions({+ input: { params: { app_id: appDetail.id, conversation_id: conversationId } },+ }),+ consoleQuery.apps.byAppId.chatMessages.get.queryOptions({+ input: {+ params: { app_id: appDetail.id },+ query: { conversation_id: conversationId, limit: 10 },+ },+ // Preserve edits during this session; reopening fetches a fresh snapshot.+ staleTime: Infinity,+ gcTime: 0,+ }),+ ],+ })+ return (+ <DetailPanel+ appDetail={appDetail}+ detail={detail.data}+ initialMessages={messages.data}+ onFeedback={onFeedback}+ />+ )+}++function CompletionConversationContent({+ appDetail,+ conversationId,+ onFeedback,+}: ConversationContentProps) {+ const { data } = useSuspenseQuery(+ consoleQuery.apps.byAppId.completionConversations.byConversationId.get.queryOptions({+ input: { params: { app_id: appDetail.id, conversation_id: conversationId } },+ }),+ )+ return <DetailPanel appDetail={appDetail} detail={data} onFeedback={onFeedback} />+}diff --git a/web/app/components/app/log/filter.tsx b/web/app/components/app/log/filter.tsxindex 49b6d6c9ef6..7e207b07df6 100644--- a/web/app/components/app/log/filter.tsx+++ b/web/app/components/app/log/filter.tsx@@ -51,7 +51,7 @@ const Filter: FC<IFilterProps> = ({queryParams,setQueryParams,}: IFilterProps) => {- const { data, isLoading } = useQuery(+ const { data } = useQuery(consoleQuery.apps.byAppId.annotations.count.get.queryOptions({input: appId ? { params: { app_id: appId } } : skipToken,}),@@ -63,7 +63,6 @@ const Filter: FC<IFilterProps> = ({.filter(([key]) => !isTimePeriodRestricted || CLOUD_SANDBOX_TIME_PERIOD_KEYS.has(key)).map(([key, option]) => [key, resolveLogTimePeriodOption(key, option, planState)] as const)- if (isLoading || !data) return nullreturn (<div className="mb-2 flex flex-row flex-wrap items-center gap-2"><Chip@@ -88,6 +87,7 @@ const Filter: FC<IFilterProps> = ({<ChipclassName="min-w-37.5"panelClassName="w-[270px]"+ disabled={!data}showLeftIcon={false}value={queryParams.annotation_status || 'all'}onSelect={(item) => {@@ -101,7 +101,10 @@ const Filter: FC<IFilterProps> = ({{ value: 'all', name: t(($) => $['filter.annotation.all'], { ns: 'appLog' }) },{value: 'annotated',- name: t(($) => $['filter.annotation.annotated'], { ns: 'appLog', count: data?.count }),+ name: t(($) => $['filter.annotation.annotated'], {+ ns: 'appLog',+ count: data?.count ?? 0,+ }),},{value: 'not_annotated',diff --git a/web/app/components/app/log/index.tsx b/web/app/components/app/log/index.tsxindex 4a8c59cf38c..5b60c8b30df 100644--- a/web/app/components/app/log/index.tsx+++ b/web/app/components/app/log/index.tsx@@ -13,7 +13,6 @@ import { omit } from 'es-toolkit/object'import * as React from 'react'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { APP_PAGE_LIMIT } from '@/config'import { useDocLink } from '@/context/i18n'import { usePathname, useRouter, useSearchParams } from '@/next/navigation'@@ -24,7 +23,6 @@ import {resolveLogTimePeriodOption,useCloudSandboxPlanStatus,} from './cloud-sandbox-retention'-import EmptyElement from './empty-element'import Filter, { TIME_PERIOD_MAPPING } from './filter'import List from './list'import { RetentionUpgradeNotice } from './retention-upgrade-notice'@@ -48,35 +46,25 @@ const defaultQueryParams: QueryParam = {sort_by: '-created_at',}-const logsStateCache = new Map<- string,- {- queryParams: QueryParam- currPage: number- limit: number- }->()+const logsStateCache = new Map<string, { queryParams: QueryParam; limit: number }>()const Logs: FC<ILogsProps> = ({ appDetail }) => {- const { t } = useTranslation(['appLog', 'common'])+ const { t, ready } = useTranslation(['appLog', 'common'], { useSuspense: false })const docLink = useDocLink()const router = useRouter()const pathname = usePathname()const searchParams = useSearchParams()- const getPageFromParams = useCallback(() => {- const pageParam = Number.parseInt(searchParams.get('page') || '1', 10)- if (Number.isNaN(pageParam) || pageParam < 1) return 0- return pageParam - 1- }, [searchParams])- const cachedState = logsStateCache.get(appDetail.id)+ const pageParam = Number.parseInt(searchParams.get('page') || '1', 10)+ const currPage = Number.isNaN(pageParam) || pageParam < 1 ? 0 : pageParam - 1const cloudSandboxPlanState = useCloudSandboxPlanStatus()+ const cachedState = logsStateCache.get(appDetail.id)const [queryParams, setQueryParams] = useState<QueryParam>(cachedState?.queryParams ?? defaultQueryParams,)- const [currPage, setCurrPage] = React.useState<number>(- () => cachedState?.currPage ?? getPageFromParams(),- )- const [limit, setLimit] = React.useState<number>(cachedState?.limit ?? APP_PAGE_LIMIT)+ const [limit, setLimit] = useState(cachedState?.limit ?? APP_PAGE_LIMIT)+ useEffect(() => {+ logsStateCache.set(appDetail.id, { queryParams, limit })+ }, [appDetail.id, queryParams, limit])const effectivePeriod = resolveLogTimePeriod(queryParams.period, cloudSandboxPlanState)const effectiveQueryParams = { ...queryParams, period: effectivePeriod }const debouncedQueryParams = useDebounce(queryParams, { wait: 500 })@@ -87,19 +75,6 @@ const Logs: FC<ILogsProps> = ({ appDetail }) => {cloudSandboxPlanState,)- useEffect(() => {- const pageFromParams = getPageFromParams()- setCurrPage((prev) => (prev === pageFromParams ? prev : pageFromParams))- }, [getPageFromParams])-- useEffect(() => {- logsStateCache.set(appDetail.id, {- queryParams,- currPage,- limit,- })- }, [appDetail.id, currPage, limit, queryParams])-// Get the app type firstconst isChatMode = appDetail.mode !== 'completion'@@ -135,14 +110,8 @@ const Logs: FC<ILogsProps> = ({ appDetail }) => {const total = isChatMode ? chatConversations?.total : completionConversations?.totalconst totalPages = total ? Math.max(Math.ceil(total / limit), 1) : 1- const handleQueryParamsChange = useCallback((next: QueryParam) => {- setCurrPage(0)- setQueryParams(next)- }, [])-const handlePageChange = useCallback((page: number) => {- setCurrPage(page)const params = new URLSearchParams(searchParams.toString())const nextPageValue = page + 1if (nextPageValue === 1) params.delete('page')@@ -153,6 +122,16 @@ const Logs: FC<ILogsProps> = ({ appDetail }) => {[pathname, router, searchParams],)+ const handleQueryParamsChange = useCallback(+ (next: QueryParam) => {+ handlePageChange(0)+ setQueryParams(next)+ },+ [handlePageChange],+ )++ if (!ready) return null+return (<div className="flex h-full grow flex-col"><PageTitle@@ -169,19 +148,13 @@ const Logs: FC<ILogsProps> = ({ appDetail }) => {setQueryParams={handleQueryParamsChange}/><RetentionUpgradeNotice />- {total === undefined ? (- <LoadingPlaceholder className="h-full" />- ) : total > 0 ? (- <List- logs={isChatMode ? chatConversations : completionConversations}- appDetail={appDetail}- onRefresh={isChatMode ? mutateChatList : mutateCompletionList}- />- ) : (- <EmptyElement appDetail={appDetail} />- )}+ <List+ logs={isChatMode ? chatConversations : completionConversations}+ appDetail={appDetail}+ onRefresh={isChatMode ? mutateChatList : mutateCompletionList}+ />{/* Show Pagination only if the total is more than the limit */}- {total && total > APP_PAGE_LIMIT ? (+ {total !== undefined && total > APP_PAGE_LIMIT ? (<Paginationpage={currPage + 1}totalPages={totalPages}diff --git a/web/app/components/app/log/list-utils.ts b/web/app/components/app/log/list-utils.tsindex bbcdcbe8051..8aa8066caf7 100644--- a/web/app/components/app/log/list-utils.ts+++ b/web/app/components/app/log/list-utils.ts@@ -24,9 +24,9 @@ dayjs.extend(timezone)type LogDetailMessage = {answer?: string | number | null- inputs?: Record<string, unknown>- message_files?: Array<{ url?: string | null }>- query?: string+ inputs?: Record<string, unknown> | null+ message_files?: Array<{ url?: string | null }> | null+ query?: string | null}type ConversationLogDetail = {@@ -38,7 +38,7 @@ type ConversationLogDetail = {// Untyped JSON in the console API response.user_input_form?: unknown} | null- name?: string+ name?: string | null}const getUserInputVariable = (item: unknown) => {@@ -219,40 +219,6 @@ export const mergeUniqueChatItems = (prevItems: IChatItem[], newItems: IChatItemreturn [...uniqueNewItems, ...prevItems]}-export const mergePaginatedChatItems = ({- maxRetryCount,- newItems,- prevItems,- retryCount,-}: {- maxRetryCount: number- newItems: IChatItem[]- prevItems: IChatItem[]- retryCount: number-}) => {- const existingIds = new Set(prevItems.map((item) => item.id))- const uniqueNewItems = newItems.filter((item) => !existingIds.has(item.id))-- if (!uniqueNewItems.length) {- if (retryCount < maxRetryCount && prevItems.length > 1) {- return {- items: prevItems,- retryCount: retryCount + 1,- }- }-- return {- items: prevItems,- retryCount: 0,- }- }-- return {- items: [...uniqueNewItems, ...prevItems],- retryCount: 0,- }-}-export const buildChatThreadState = ({allChatItems,hasMore,@@ -378,7 +344,7 @@ export const getConversationRowValues = ({noOutputLabel,}: {isChatMode: boolean- log: ConversationLogDetail+ log: Omit<ConversationLogDetail, 'model_config'>noChatLabel: stringnoOutputLabel: string}) => {diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex 4798ab6cb7a..f84ac661b61 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -3,83 +3,39 @@import type {AppDetailWithSite,Conversation,- ConversationDetail,- ConversationMessageDetail,+ ConversationAnnotation,ConversationPagination,ConversationWithSummary,ConversationWithSummaryPagination,- GetAppsByAppIdChatMessagesData,} from '@dify/contracts/api/console/apps/types.gen'import type { FC } from 'react'-import type { ChatItemInTree } from '../../base/chat/types'-import type {- FeedbackFunc,- FeedbackType,- IChatItem,- SubmitAnnotationFunc,-} from '@/app/components/base/chat/chat/type'-import type { LogAnnotation } from '@/models/log'import { HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'import { cn } from '@langgenius/dify-ui/cn'import {- Drawer,- DrawerBackdrop,- DrawerContent,- DrawerPopup,- DrawerPortal,- DrawerTitle,- DrawerTrigger,- DrawerViewport,-} from '@langgenius/dify-ui/drawer'-import { IconButton } from '@langgenius/dify-ui/icon-button'+ Dialog,+ DialogBackdrop,+ DialogPopup,+ DialogPortal,+ DialogTrigger,+ DialogViewport,+} from '@langgenius/dify-ui/dialog'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { RiCloseLine, RiEditFill } from '@remixicon/react'-import { skipToken, useQuery } from '@tanstack/react-query'+import { RiEditFill } from '@remixicon/react'import dayjs from 'dayjs'import timezone from 'dayjs/plugin/timezone'import utc from 'dayjs/plugin/utc'-import { noop } from 'es-toolkit/function'import { parseAsString, useQueryState } from 'nuqs'-import * as React from 'react'-import { useCallback, useEffect, useRef, useState } from 'react'+import { Suspense, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import ModelInfo from '@/app/components/app/log/model-info'-import TextGeneration from '@/app/components/app/text-generate/item'-import AgentLogModal from '@/app/components/base/agent-log-modal'-import Chat from '@/app/components/base/chat/chat'-import CopyIcon from '@/app/components/base/copy-icon'-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import MessageLogModal from '@/app/components/base/message-log-modal'-import { WorkflowContextProvider } from '@/app/components/workflow/context'-import { toast } from '@/app/notifications'-import { userProfileQueryOptions } from '@/features/account-profile/client'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useTimestamp from '@/hooks/use-timestamp'-import { consoleClient, consoleQuery } from '@/service/console'-import { AppSourceType } from '@/service/share'-import PromptLogModal from '../../base/prompt-log-modal'-import {- applyAnnotationAdded,- applyAnnotationEdited,- applyAnnotationRemoved,- buildChatThreadState,- getAdminFeedback,- getCompletionMessageFiles,- getConversationRowValues,- getDetailVarList,- getFormattedChatList,- getLogModelInfo,- getStringInputs,- getThreadChatItems,- isNearTopLoadMore,- mergePaginatedChatItems,- mergeUniqueChatItems,-} from './list-utils'-import VarPanel from './var-panel'+import { ConversationDetail } from './conversation-detail'+import EmptyElement from './empty-element'+import { getConversationRowValues } from './list-utils'+import { LogListSkeleton } from './loading'type ConversationListItem = ConversationWithSummary | Conversation-type ConversationSelection = ConversationListItem | { id: string; isPlaceholder?: true }dayjs.extend(utc)dayjs.extend(timezone)@@ -118,7 +74,7 @@ const HandThumbIconWithCount: FC<{ count: number; iconType: 'up' | 'down' }> = ()}-const statusTdRender = (statusCount: StatusCount) => {+const statusTdRender = (statusCount: StatusCount | null | undefined) => {if (!statusCount) return nullif (statusCount.paused > 0) {@@ -154,597 +110,6 @@ const statusTdRender = (statusCount: StatusCount) => {}}-type IDetailPanel = {- appDetail: AppDetailWithSite- detail: ConversationDetail | ConversationMessageDetail- onClose: () => void- onFeedback: FeedbackFunc- onSubmitAnnotation: SubmitAnnotationFunc-}--function DetailPanel({ appDetail, detail, onClose, onFeedback }: IDetailPanel) {- const MIN_ITEMS_FOR_SCROLL_LOADING = 8- const SCROLL_DEBOUNCE_MS = 200- const { data: timezone } = useQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile.timezone ?? undefined,- })- const { formatTime } = useTimestamp()- const [selectedLogItem, setSelectedLogItem] = useState<IChatItem>()- const { t } = useTranslation(['appLog', 'common'])- const [hasMore, setHasMore] = useState(true)- const [varValues, setVarValues] = useState<Record<string, string>>({})- const isLoadingRef = useRef(false)- const abortControllerRef = useRef<AbortController | null>(null)- const requestIdRef = useRef(0)- const lastLoadTimeRef = useRef(0)- const retryCountRef = useRef(0)- const oldestAnswerIdRef = useRef<string | undefined>(undefined)- const MAX_RETRY_COUNT = 3-- const [allChatItems, setAllChatItems] = useState<IChatItem[]>([])- const [chatItemTree, setChatItemTree] = useState<ChatItemInTree[]>([])- const [threadChatItems, setThreadChatItems] = useState<IChatItem[]>([])-- const fetchData = useCallback(async () => {- if (isLoadingRef.current || !hasMore) return-- // Cancel any in-flight request- if (abortControllerRef.current) {- abortControllerRef.current.abort()- }-- const controller = new AbortController()- abortControllerRef.current = controller- const currentRequestId = ++requestIdRef.current-- try {- isLoadingRef.current = true-- const params: GetAppsByAppIdChatMessagesData['query'] = {- conversation_id: detail.id,- limit: 10,- }- // Use ref for pagination anchor to avoid stale closure issues- if (oldestAnswerIdRef.current) params.first_id = oldestAnswerIdRef.current-- const messageRes = await consoleClient.apps.byAppId.chatMessages.get({- params: { app_id: appDetail.id },- query: params,- })-- // Ignore stale responses- if (currentRequestId !== requestIdRef.current || controller.signal.aborted) return- if (messageRes.data.length > 0) {- const varValues = getStringInputs(messageRes.data.at(-1)!.inputs)- setVarValues(varValues)- }- setHasMore(messageRes.has_more)-- const newItems = getFormattedChatList(- messageRes.data,- detail.id,- timezone!,- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,- )-- // Use functional update to avoid stale state issues- setAllChatItems((prevItems: IChatItem[]) => mergeUniqueChatItems(prevItems, newItems))- } catch (err: unknown) {- if (err instanceof Error && err.name === 'AbortError') return- console.error('fetchData execution failed:', err)- } finally {- isLoadingRef.current = false- if (abortControllerRef.current === controller) abortControllerRef.current = null- }- }, [detail.id, hasMore, timezone, t, appDetail])-- // Derive chatItemTree, threadChatItems, and oldestAnswerIdRef from allChatItems- useEffect(() => {- if (allChatItems.length === 0) return-- const nextThreadState = buildChatThreadState({- allChatItems,- hasMore,- introduction: 'introduction' in detail ? (detail.introduction ?? undefined) : undefined,- })- setChatItemTree(nextThreadState.chatItemTree)- setThreadChatItems(nextThreadState.threadChatItems)- if (nextThreadState.oldestAnswerId) oldestAnswerIdRef.current = nextThreadState.oldestAnswerId- }, [allChatItems, hasMore, detail])-- const switchSibling = useCallback(- (siblingMessageId: string) => {- setThreadChatItems(getThreadChatItems(chatItemTree, siblingMessageId))- },- [chatItemTree],- )-- const handleAnnotationEdited = useCallback(- (query: string, answer: string, index: number) => {- setAllChatItems(applyAnnotationEdited(allChatItems, query, answer, index))- },- [allChatItems],- )- const handleAnnotationAdded = useCallback(- (annotationId: string, authorName: string, query: string, answer: string, index: number) => {- setAllChatItems(- applyAnnotationAdded(allChatItems, annotationId, authorName, query, answer, index),- )- },- [allChatItems],- )- const handleAnnotationRemoved = useCallback(- async (index: number): Promise<boolean> => {- const annotation = allChatItems[index]?.annotation-- try {- if (annotation?.id) {- await consoleClient.apps.byAppId.annotations.byAnnotationId.delete({- params: { app_id: appDetail.id, annotation_id: annotation.id },- })- }-- setAllChatItems(applyAnnotationRemoved(allChatItems, index))-- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))- return true- } catch {- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))- return false- }- },- [allChatItems, appDetail.id, t],- )-- const fetchInitiated = useRef(false)-- // Only load initial messages, don't auto-load more- useEffect(() => {- if (appDetail.id && detail.id && appDetail.mode !== 'completion' && !fetchInitiated.current) {- // Mark as initialized, but don't auto-load more messages- fetchInitiated.current = true- // Still call fetchData to get initial messages- fetchData()- }- }, [appDetail.id, detail.id, appDetail.mode, fetchData])-- const [isLoading, setIsLoading] = useState(false)-- const loadMoreMessages = useCallback(async () => {- if (isLoading || !hasMore || !appDetail.id || !detail.id) return-- // Throttle using ref to persist across re-renders- const now = Date.now()- if (now - lastLoadTimeRef.current < SCROLL_DEBOUNCE_MS) return- lastLoadTimeRef.current = now-- setIsLoading(true)-- try {- const params: GetAppsByAppIdChatMessagesData['query'] = {- conversation_id: detail.id,- limit: 10,- }-- // Use ref for pagination anchor to avoid stale closure issues- if (oldestAnswerIdRef.current) {- params.first_id = oldestAnswerIdRef.current- }-- const messageRes = await consoleClient.apps.byAppId.chatMessages.get({- params: { app_id: appDetail.id },- query: params,- })-- if (!messageRes.data || messageRes.data.length === 0) {- setHasMore(false)- retryCountRef.current = 0- return- }-- if (messageRes.data.length > 0) {- const varValues = getStringInputs(messageRes.data.at(-1)!.inputs)- setVarValues(varValues)- }-- setHasMore(messageRes.has_more)-- const newItems = getFormattedChatList(- messageRes.data,- detail.id,- timezone!,- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,- )-- // Use functional update to get latest state and avoid stale closures- setAllChatItems((prevItems: IChatItem[]) => {- const nextItems = mergePaginatedChatItems({- maxRetryCount: MAX_RETRY_COUNT,- newItems,- prevItems,- retryCount: retryCountRef.current,- })- retryCountRef.current = nextItems.retryCount- return nextItems.items- })- } catch (error) {- console.error(error)- setHasMore(false)- retryCountRef.current = 0- } finally {- setIsLoading(false)- }- }, [detail.id, hasMore, isLoading, timezone, t, appDetail])-- const handleScroll = useCallback(() => {- const scrollableDiv = document.getElementById('scrollableDiv')- if (!scrollableDiv) return- const clientHeight = scrollableDiv.clientHeight- const scrollHeight = scrollableDiv.scrollHeight- const currentScrollTop = scrollableDiv.scrollTop- // currentScrollTop is negative due to column-reverse flex direction- const isNearTop = isNearTopLoadMore({- clientHeight,- scrollHeight,- scrollTop: currentScrollTop,- })-- if (isNearTop && hasMore && !isLoading) {- loadMoreMessages()- }- }, [hasMore, isLoading, loadMoreMessages])-- const isChatMode = appDetail.mode !== 'completion'- const isAdvanced = appDetail.mode === 'advanced-chat'- const logKind = selectedLogItem?.workflow_run_id- ? 'workflow'- : selectedLogItem?.agent_thoughts?.length- ? 'agent'- : selectedLogItem?.log- ? 'prompt'- : undefined-- const varList = getDetailVarList(detail, varValues)- const message_files = getCompletionMessageFiles(detail, isChatMode)- const completionMessage = 'message' in detail ? detail.message : undefined- const modelInfo = getLogModelInfo(detail.model_config?.model)-- const [width, setWidth] = useState(0)- const ref = useRef<HTMLDivElement>(null)-- const adjustModalWidth = () => {- if (ref.current) setWidth(document.body.clientWidth - (ref.current?.clientWidth + 16) - 8)- }-- useEffect(() => {- const raf = requestAnimationFrame(adjustModalWidth)- return () => cancelAnimationFrame(raf)- }, [])-- return (- <div- ref={ref}- className="flex h-full flex-col rounded-xl border-[0.5px] border-components-panel-border"- >- {/* Panel Header */}- <div className="flex shrink-0 items-center gap-2 rounded-t-xl bg-components-panel-bg pt-3 pr-3 pb-2 pl-4">- <div className="shrink-0">- <DrawerTitle className="mb-0.5 system-xs-semibold-uppercase text-text-primary">- {isChatMode- ? t(($) => $['detail.conversationId'], { ns: 'appLog' })- : t(($) => $['detail.time'], { ns: 'appLog' })}- </DrawerTitle>- {isChatMode && (- <div className="flex items-center system-2xs-regular-uppercase text-text-secondary">- <Tooltip>- <TooltipTrigger render={<div className="truncate">{detail.id}</div>} />- <TooltipContent>{detail.id}</TooltipContent>- </Tooltip>- <CopyIcon content={detail.id} />- </div>- )}- {!isChatMode && (- <div className="system-2xs-regular-uppercase text-text-secondary">- {detail.created_at- ? formatTime(- detail.created_at,- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,- )- : defaultValue}- </div>- )}- </div>- <div className="flex grow flex-wrap items-center justify-end gap-y-1">- {!isAdvanced && modelInfo && <ModelInfo model={modelInfo} />}- </div>- <IconButton- size="lg"- aria-label={t(($) => $['operation.close'], { ns: 'common' })}- onClick={onClose}- >- <RiCloseLine aria-hidden className="size-4 text-text-tertiary" />- </IconButton>- </div>- {/* Panel Body */}- <div className="shrink-0 px-1 pt-1">- <div className="rounded-t-xl bg-background-section-burn p-3 pb-2">- {(varList.length > 0 || (!isChatMode && message_files.length > 0)) && (- <VarPanel varList={varList} message_files={message_files} />- )}- </div>- </div>- <div className="mx-1 mb-1 grow overflow-auto rounded-b-xl bg-background-section-burn">- {!isChatMode ? (- completionMessage && (- <div className="px-6 py-4">- <div className="flex h-4.5 items-center space-x-3">- <div className="system-xs-semibold-uppercase text-text-tertiary">- {t(($) => $['table.header.output'], { ns: 'appLog' })}- </div>- <div- className="h-px grow"- style={{- background:- 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, rgb(243, 244, 246) 100%)',- }}- ></div>- </div>- <TextGeneration- appSourceType={AppSourceType.webApp}- className="mt-2"- content={completionMessage.answer}- messageId={completionMessage.id}- isError={false}- onRetry={noop}- supportFeedback- feedback={getAdminFeedback(completionMessage.feedbacks)}- onFeedback={(feedback) => {- onFeedback(completionMessage.id, feedback).catch(noop)- }}- isShowTextToSpeech- siteInfo={null}- />- </div>- )- ) : threadChatItems.length < MIN_ITEMS_FOR_SCROLL_LOADING ? (- <div className="mb-4 pt-4">- <Chat- config={- {- appId: appDetail.id,- text_to_speech: {- enabled: true,- },- questionEditEnable: false,- supportAnnotation: true,- annotation_reply: {- enabled: true,- },- supportFeedback: true,- } as any- }- chatList={threadChatItems}- onAnnotationAdded={handleAnnotationAdded}- onAnnotationEdited={handleAnnotationEdited}- onAnnotationRemoved={handleAnnotationRemoved}- onFeedback={onFeedback}- noChatInput- onOpenLog={isAdvanced ? setSelectedLogItem : undefined}- hideProcessDetail- chatContainerInnerClassName="px-3"- switchSibling={switchSibling}- />- </div>- ) : (- <div- className="py-4"- id="scrollableDiv"- role="log"- aria-live="off"- style={{- display: 'flex',- flexDirection: 'column-reverse',- height: '100%',- overflow: 'auto',- }}- onScroll={handleScroll}- >- {/* Put the scroll bar always on the bottom */}- <div className="flex w-full flex-col-reverse" style={{ position: 'relative' }}>- <Chat- config={- {- appId: appDetail.id,- text_to_speech: {- enabled: true,- },- questionEditEnable: false,- supportAnnotation: true,- annotation_reply: {- enabled: true,- },- supportFeedback: true,- } as any- }- chatList={threadChatItems}- onAnnotationAdded={handleAnnotationAdded}- onAnnotationEdited={handleAnnotationEdited}- onAnnotationRemoved={handleAnnotationRemoved}- onFeedback={onFeedback}- noChatInput- onOpenLog={isAdvanced ? setSelectedLogItem : undefined}- hideProcessDetail- chatContainerInnerClassName="px-3"- switchSibling={switchSibling}- />- </div>- {hasMore && (- <div className="py-3 text-center">- <div className="system-xs-regular text-text-tertiary">- {t(($) => $['detail.loading'], { ns: 'appLog' })}- ...- </div>- </div>- )}- </div>- )}- </div>- {logKind === 'workflow' && (- <WorkflowContextProvider>- <MessageLogModal- appId={appDetail.id}- width={width}- currentLogItem={selectedLogItem}- onCancel={() => setSelectedLogItem(undefined)}- />- </WorkflowContextProvider>- )}- {logKind === 'agent' && (- <AgentLogModal- appId={appDetail.id}- floating- width={width}- currentLogItem={selectedLogItem}- onCancel={() => setSelectedLogItem(undefined)}- />- )}- {logKind === 'prompt' && (- <PromptLogModal- width={width}- currentLogItem={selectedLogItem}- onCancel={() => setSelectedLogItem(undefined)}- />- )}- </div>- )-}--type ConversationDetailProps = {- appDetail: AppDetailWithSite- conversationId?: string- onClose: () => void-}--/**- * Text App Conversation Detail Component- */-const CompletionConversationDetailComp: FC<ConversationDetailProps> = ({- appDetail,- conversationId,- onClose,-}) => {- // Text Generator App Session Details Including Message List- const { data: conversationDetail, refetch: conversationDetailMutate } = useQuery(- consoleQuery.apps.byAppId.completionConversations.byConversationId.get.queryOptions({- input: conversationId- ? { params: { app_id: appDetail.id, conversation_id: conversationId } }- : skipToken,- }),- )- const { t } = useTranslation(['appLog', 'common'])-- const handleFeedback = async (mid: string, { rating, content }: FeedbackType) => {- await consoleClient.apps.byAppId.feedbacks.post({- params: { app_id: appDetail.id },- body: { message_id: mid, rating, content: content ?? undefined },- })- conversationDetailMutate()- }-- const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {- try {- await consoleClient.apps.byAppId.annotations.post({- params: { app_id: appDetail.id },- body: { message_id: mid, content: value },- })- conversationDetailMutate()- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))- return true- } catch {- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))- return false- }- }-- if (!conversationDetail) {- return (- <DrawerTitle className="sr-only">- {t(($) => $['runDetail.title'], { ns: 'appLog' })}- </DrawerTitle>- )- }-- return (- <DetailPanel- key={`${appDetail.id}:${conversationId}`}- appDetail={appDetail}- detail={conversationDetail}- onClose={onClose}- onFeedback={handleFeedback}- onSubmitAnnotation={handleAnnotation}- />- )-}--/**- * Chat App Conversation Detail Component- */-const ChatConversationDetailComp: FC<ConversationDetailProps> = ({- appDetail,- conversationId,- onClose,-}) => {- const { data: conversationDetail } = useQuery(- consoleQuery.apps.byAppId.chatConversations.byConversationId.get.queryOptions({- input: conversationId- ? { params: { app_id: appDetail.id, conversation_id: conversationId } }- : skipToken,- }),- )- const { t } = useTranslation(['appLog', 'common'])-- const handleFeedback = async (mid: string, { rating, content }: FeedbackType) => {- await consoleClient.apps.byAppId.feedbacks.post({- params: { app_id: appDetail.id },- body: { message_id: mid, rating, content: content ?? undefined },- })- }-- const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {- try {- await consoleClient.apps.byAppId.annotations.post({- params: { app_id: appDetail.id },- body: { message_id: mid, content: value },- })- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))- return true- } catch {- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))- return false- }- }-- if (!conversationDetail) {- return (- <DrawerTitle className="sr-only">- {t(($) => $['runDetail.title'], { ns: 'appLog' })}- </DrawerTitle>- )- }-- return (- <DetailPanel- key={`${appDetail.id}:${conversationId}`}- appDetail={appDetail}- detail={conversationDetail}- onClose={onClose}- onFeedback={handleFeedback}- onSubmitAnnotation={handleAnnotation}- />- )-}-/*** Conversation list component including basic information*/@@ -756,100 +121,30 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })parseAsString,)+ const popupRef = useRef<HTMLDivElement>(null)const media = useBreakpoints()const isMobile = media === MediaType.mobile- const [showDrawer, setShowDrawer] = useState<boolean>(false) // Whether to display the chat details drawer- const [currentConversation, setCurrentConversation] = useState<- ConversationSelection | undefined- >() // Currently selected conversation- const closingConversationIdRef = useRef<string | null>(null)- const pendingConversationIdRef = useRef<string | null>(null)- const pendingConversationCacheRef = useRef<ConversationSelection | undefined>(undefined)- const isChatMode = appDetail.mode !== 'completion' // Whether the app is a chat app- const isChatflow = appDetail.mode === 'advanced-chat' // Whether the app is a chatflow app- const activeConversationId =- conversationIdInUrl ?? pendingConversationIdRef.current ?? currentConversation?.id-- const handleRowClick = useCallback(- (log: ConversationListItem) => {- if (conversationIdInUrl === log.id) {- if (!showDrawer) setShowDrawer(true)-- if (!currentConversation || currentConversation.id !== log.id) setCurrentConversation(log)- return- }-- pendingConversationIdRef.current = log.id- pendingConversationCacheRef.current = log- if (!showDrawer) setShowDrawer(true)-- if (currentConversation?.id !== log.id) setCurrentConversation(undefined)-- void setConversationIdInUrl(log.id, { history: 'push' })- },- [conversationIdInUrl, currentConversation, setConversationIdInUrl, showDrawer],- )-- const currentConversationId = currentConversation?.id-- useEffect(() => {- if (!conversationIdInUrl) {- if (pendingConversationIdRef.current) return-- if (showDrawer || currentConversationId) {- setShowDrawer(false)- setCurrentConversation(undefined)- }- closingConversationIdRef.current = null- pendingConversationCacheRef.current = undefined- return- }-- if (closingConversationIdRef.current === conversationIdInUrl) return-- if (pendingConversationIdRef.current === conversationIdInUrl)- pendingConversationIdRef.current = null-- const matchedConversation = logs?.data?.find(- (item: ConversationListItem) => item.id === conversationIdInUrl,- )- const nextConversation: ConversationSelection = matchedConversation ??- pendingConversationCacheRef.current ?? { id: conversationIdInUrl, isPlaceholder: true }-- if (!showDrawer) setShowDrawer(true)-- if (- !currentConversation ||- currentConversation.id !== conversationIdInUrl ||- (!('created_at' in currentConversation) && matchedConversation)- )- setCurrentConversation(nextConversation)-- if (pendingConversationCacheRef.current?.id === conversationIdInUrl || matchedConversation)- pendingConversationCacheRef.current = undefined- }, [conversationIdInUrl, currentConversation, currentConversationId, logs?.data, showDrawer])-- const onCloseDrawer = useCallback(() => {+ const isChatMode = appDetail.mode !== 'completion'+ const isChatflow = appDetail.mode === 'advanced-chat'+ const activeConversationId = conversationIdInUrl+ const handleRowClick = (log: ConversationListItem) => {+ void setConversationIdInUrl(log.id, { history: 'push' })+ }+ const onCloseDialog = () => {onRefresh()- setShowDrawer(false)- setCurrentConversation(undefined)- pendingConversationIdRef.current = null- pendingConversationCacheRef.current = undefined- closingConversationIdRef.current = conversationIdInUrl ?? null-- if (conversationIdInUrl) void setConversationIdInUrl(null, { history: 'replace' })- }, [conversationIdInUrl, onRefresh, setConversationIdInUrl])+ void setConversationIdInUrl(null, { history: 'replace' })+ }// Annotated data needs to be highlightedconst renderTdValue = (value: string | number | null,isEmptyStyle: boolean,isHighlight = false,- annotation?: LogAnnotation,+ annotation?: ConversationAnnotation | null,) => {return (- <Tooltip disabled={!isHighlight || isChatMode}>+ <Tooltip disabled={isEmptyStyle}><TooltipTriggerrender={<div@@ -864,28 +159,43 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })}/><TooltipContent className="flex items-center gap-1">- <RiEditFill aria-hidden className="size-3 shrink-0" />- <span>- {`${t(($) => $['detail.annotationTip'], { ns: 'appLog', user: annotation?.account?.name ?? '-' })} ${formatTime(annotation?.created_at || dayjs().unix(), 'MM-DD hh:mm A')}`}- </span>+ {isHighlight && !isChatMode ? (+ <>+ <RiEditFill aria-hidden className="size-3 shrink-0" />+ <span>+ {`${t(($) => $['detail.annotationTip'], { ns: 'appLog', user: annotation?.account?.name ?? '-' })} ${formatTime(annotation?.created_at || dayjs().unix(), 'MM-DD hh:mm A')}`}+ </span>+ </>+ ) : (+ value+ )}</TooltipContent></Tooltip>)}- if (!logs) return <LoadingPlaceholder />-return (<div className="relative mt-2 grow overflow-x-auto">- <Drawer- open={showDrawer}- modal- swipeDirection="right"+ <Dialog+ open={!!conversationIdInUrl}+ modal={isMobile}+ disablePointerDismissal={!isMobile}onOpenChange={(open) => {- if (!open) onCloseDrawer()+ if (!open) onCloseDialog()}}>- <table className={cn('w-full min-w-110 border-collapse border-0')}>+ <table className="w-full min-w-300 table-fixed border-collapse border-0">+ <colgroup>+ <col className="w-5" />+ <col />+ <col />+ {isChatflow && <col className="w-36" />}+ <col className={isChatMode ? 'w-32' : undefined} />+ <col className="w-28" />+ <col className="w-28" />+ <col className="w-44" />+ <col className="w-44" />+ </colgroup><thead className="system-xs-medium-uppercase text-text-tertiary"><tr><td className="w-5 rounded-l-lg bg-background-section-burn pr-1 pl-2 whitespace-nowrap"></td>@@ -922,149 +232,178 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })</tr></thead><tbody className="system-sm-regular text-text-secondary">- {logs.data.map((log: any) => {- const { endUser, isLeftEmpty, isRightEmpty, leftValue, rightValue } =- getConversationRowValues({- isChatMode,- log,- noChatLabel: t(($) => $['table.empty.noChat'], { ns: 'appLog' }),- noOutputLabel: t(($) => $['table.empty.noOutput'], { ns: 'appLog' }),- })- return (- <tr- key={log.id}- className={cn(- 'cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover',- activeConversationId !== log.id ? '' : 'bg-background-default-hover',- )}- onClick={(event) => {- if ((event.target as HTMLElement).closest('button, a')) return- event.currentTarget- .querySelector<HTMLButtonElement>('button[data-log-detail-trigger]')- ?.click()- }}- >- <td className="h-4">- {!log.read_at && (- <div className="flex items-center p-3 pr-0.5">- <span- aria-hidden="true"- className="inline-block size-1.5 rounded-sm bg-util-colors-blue-blue-500"- ></span>- <span className="sr-only">- {t(($) => $['table.unread'], { ns: 'appLog' })}- </span>- </div>- )}- </td>- <td className="w-40 p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>- {renderTdValue(leftValue, isLeftEmpty, isChatMode && log.annotated)}- </td>- <td className="p-3 pr-2">{renderTdValue(endUser || defaultValue, !endUser)}</td>- {isChatflow && (- <td className="w-40 p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>- {statusTdRender(log.status_count)}- </td>- )}- <td className="p-3 pr-2" style={{ maxWidth: isChatMode ? 100 : 200 }}>- {renderTdValue(- rightValue,- isRightEmpty,- !isChatMode && !!log.annotation?.content,- log.annotation,- )}- </td>- <td className="p-3 pr-2">- {!log.user_feedback_stats.like && !log.user_feedback_stats.dislike ? (- renderTdValue(defaultValue, true)- ) : (- <>- {!!log.user_feedback_stats.like && (- <HandThumbIconWithCount- iconType="up"- count={log.user_feedback_stats.like}- />- )}- {!!log.user_feedback_stats.dislike && (- <HandThumbIconWithCount- iconType="down"- count={log.user_feedback_stats.dislike}- />- )}- </>- )}- </td>- <td className="p-3 pr-2">- {!log.admin_feedback_stats.like && !log.admin_feedback_stats.dislike ? (- renderTdValue(defaultValue, true)- ) : (- <>- {!!log.admin_feedback_stats.like && (- <HandThumbIconWithCount- iconType="up"- count={log.admin_feedback_stats.like}- />- )}- {!!log.admin_feedback_stats.dislike && (- <HandThumbIconWithCount- iconType="down"- count={log.admin_feedback_stats.dislike}- />- )}- </>- )}+ <Suspense fallback={<LogListSkeleton columns={isChatflow ? 9 : 8} />}>+ {!logs ? (+ <LogListSkeleton columns={isChatflow ? 9 : 8} />+ ) : logs.total === 0 ? (+ <tr>+ <td colSpan={isChatflow ? 9 : 8} className="h-80">+ <EmptyElement appDetail={appDetail} /></td>- <td className="w-40 p-3 pr-2">- {formatTime(- log.updated_at,- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,- )}- </td>- <td className="w-40 p-3 pr-2">- <DrawerTrigger- data-log-detail-trigger- className="w-full cursor-pointer rounded-sm text-left"+ </tr>+ ) : (+ logs.data.map((log) => {+ const { endUser, isLeftEmpty, isRightEmpty, leftValue, rightValue } =+ getConversationRowValues({+ isChatMode,+ log,+ noChatLabel: t(($) => $['table.empty.noChat'], { ns: 'appLog' }),+ noOutputLabel: t(($) => $['table.empty.noOutput'], { ns: 'appLog' }),+ })+ return (+ <tr+ key={log.id}+ className={cn(+ 'cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover',+ activeConversationId !== log.id ? '' : 'bg-background-default-hover',+ )}onClick={(event) => {- event.stopPropagation()- handleRowClick(log)+ if ((event.target as HTMLElement).closest('button, a')) return+ event.currentTarget+ .querySelector<HTMLButtonElement>('button[data-log-detail-trigger]')+ ?.click()}}>- {formatTime(- log.created_at,- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,+ <td className="h-4">+ {!log.read_at && (+ <div className="flex items-center p-3 pr-0.5">+ <span+ aria-hidden="true"+ className="inline-block size-1.5 rounded-sm bg-util-colors-blue-blue-500"+ ></span>+ <span className="sr-only">+ {t(($) => $['table.unread'], { ns: 'appLog' })}+ </span>+ </div>+ )}+ </td>+ <td className="w-40 p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>+ {renderTdValue(+ leftValue,+ isLeftEmpty,+ isChatMode && 'annotated' in log && log.annotated,+ )}+ </td>+ <td className="p-3 pr-2">+ {renderTdValue(endUser || defaultValue, !endUser)}+ </td>+ {isChatflow && (+ <td className="w-40 p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>+ {statusTdRender('status_count' in log ? log.status_count : undefined)}+ </td>)}- </DrawerTrigger>- </td>- </tr>- )- })}+ <td className="p-3 pr-2" style={{ maxWidth: isChatMode ? 100 : 200 }}>+ {renderTdValue(+ rightValue,+ isRightEmpty,+ !isChatMode && 'annotation' in log && !!log.annotation?.content,+ 'annotation' in log ? log.annotation : undefined,+ )}+ </td>+ <td className="p-3 pr-2">+ {!log.user_feedback_stats?.like && !log.user_feedback_stats?.dislike ? (+ renderTdValue(defaultValue, true)+ ) : (+ <>+ {!!log.user_feedback_stats?.like && (+ <HandThumbIconWithCount+ iconType="up"+ count={log.user_feedback_stats.like}+ />+ )}+ {!!log.user_feedback_stats?.dislike && (+ <HandThumbIconWithCount+ iconType="down"+ count={log.user_feedback_stats.dislike}+ />+ )}+ </>+ )}+ </td>+ <td className="p-3 pr-2">+ {!log.admin_feedback_stats?.like && !log.admin_feedback_stats?.dislike ? (+ renderTdValue(defaultValue, true)+ ) : (+ <>+ {!!log.admin_feedback_stats?.like && (+ <HandThumbIconWithCount+ iconType="up"+ count={log.admin_feedback_stats.like}+ />+ )}+ {!!log.admin_feedback_stats?.dislike && (+ <HandThumbIconWithCount+ iconType="down"+ count={log.admin_feedback_stats.dislike}+ />+ )}+ </>+ )}+ </td>+ <td className="w-40 p-3 pr-2">+ {log.updated_at+ ? formatTime(+ log.updated_at,+ t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,+ )+ : defaultValue}+ </td>+ <td className="w-40 p-3 pr-2">+ <DialogTrigger+ data-log-detail-trigger+ className="w-full cursor-pointer rounded-sm text-left"+ onClick={(event) => {+ event.stopPropagation()+ handleRowClick(log)+ }}+ >+ {log.created_at+ ? formatTime(+ log.created_at,+ t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,+ )+ : defaultValue}+ </DialogTrigger>+ </td>+ </tr>+ )+ })+ )}+ </Suspense></tbody></table>- <DrawerPortal>- <DrawerBackdrop className={cn(!isMobile && 'bg-transparent')} />- <DrawerViewport>- <DrawerPopup className="bg-components-panel-bg p-0! data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-4 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-160 data-[swipe-direction=right]:rounded-xl">- <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">- {isChatMode ? (- <ChatConversationDetailComp- appDetail={appDetail}- conversationId={currentConversation?.id}- onClose={onCloseDrawer}- />- ) : (- <CompletionConversationDetailComp- appDetail={appDetail}- conversationId={currentConversation?.id}- onClose={onCloseDrawer}- />- )}- </DrawerContent>- </DrawerPopup>- </DrawerViewport>- </DrawerPortal>- </Drawer>+ <DialogPortal>+ {isMobile && <DialogBackdrop />}+ <DialogViewport className="pointer-events-none">+ <DialogPopup+ ref={popupRef}+ initialFocus={popupRef}+ className="pointer-events-auto fixed top-16 right-2 bottom-4 flex w-[calc(100%-1rem)] max-w-160 flex-col overflow-hidden rounded-xl bg-components-panel-bg shadow-xl outline-hidden"+ >+ <div className="flex min-h-0 flex-1 flex-col">+ <ConversationSession appDetail={appDetail} conversationId={conversationIdInUrl} />+ </div>+ </DialogPopup>+ </DialogViewport>+ </DialogPortal>+ </Dialog></div>)}export default ConversationList++function ConversationSession({+ appDetail,+ conversationId,+}: {+ appDetail: AppDetailWithSite+ conversationId: string | null+}) {+ // Keep the closing conversation mounted until the Dialog finishes its exit transition.+ const [sessionId, setSessionId] = useState(conversationId)+ if (conversationId && conversationId !== sessionId) setSessionId(conversationId)+ return sessionId ? (+ <ConversationDetail key={sessionId} appDetail={appDetail} conversationId={sessionId} />+ ) : null+}diff --git a/web/app/components/app/log/loading.tsx b/web/app/components/app/log/loading.tsxnew file mode 100644index 00000000000..71cf9c0cf5c--- /dev/null+++ b/web/app/components/app/log/loading.tsx@@ -0,0 +1,36 @@+import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'++export function LogListSkeleton({ columns }: { columns: number }) {+ return (+ <tr aria-busy="true">+ <td colSpan={columns}>+ <SkeletonContainer className="gap-3">+ {Array.from({ length: 5 }, (_, index) => (+ <SkeletonRow key={index} className="h-12 gap-8 px-3">+ <SkeletonRectangle className="h-4 flex-1" />+ <SkeletonRectangle className="h-4 flex-1" />+ <SkeletonRectangle className="h-4 w-24" />+ </SkeletonRow>+ ))}+ </SkeletonContainer>+ </td>+ </tr>+ )+}++export function ConversationSkeleton() {+ return (+ <SkeletonContainer+ aria-busy="true"+ className="mx-1 mb-1 flex-1 gap-6 rounded-lg bg-background-section-burn p-4"+ >+ <SkeletonRectangle className="h-10 w-2/3 self-end rounded-xl" />+ <SkeletonContainer className="gap-3 rounded-xl bg-components-panel-bg p-4">+ <SkeletonRectangle className="h-4 w-1/3" />+ <SkeletonRectangle className="h-4 w-full" />+ <SkeletonRectangle className="h-4 w-4/5" />+ <SkeletonRectangle className="h-4 w-3/5" />+ </SkeletonContainer>+ </SkeletonContainer>+ )+}diff --git a/web/app/components/base/chat/chat/type.ts b/web/app/components/base/chat/chat/type.tsindex f2426590440..a9c7b2be0fe 100644--- a/web/app/components/base/chat/chat/type.ts+++ b/web/app/components/base/chat/chat/type.ts@@ -17,7 +17,6 @@ export type FeedbackType = {}export type FeedbackFunc = (messageId: string, feedback: FeedbackType) => Promise<void>-export type SubmitAnnotationFunc = (messageId: string, content: string) => Promise<unknown>export type ToolInfoInThought = {name: stringdiff --git a/web/app/components/base/chip/__tests__/index.spec.tsx b/web/app/components/base/chip/__tests__/index.spec.tsxindex 972d280e75c..d85516ec7e1 100644--- a/web/app/components/base/chip/__tests__/index.spec.tsx+++ b/web/app/components/base/chip/__tests__/index.spec.tsx@@ -53,3 +53,19 @@ describe('Chip', () => {).toBeInTheDocument()})})++it('disables selection and clearing together without hiding the current value', async () => {+ const user = userEvent.setup()+ const onSelect = vi.fn()+ const onClear = vi.fn()+ render(<Chip disabled value="active" items={items} onSelect={onSelect} onClear={onClear} />)+ const trigger = screen.getByRole('combobox', { name: 'Active' })+ const clear = screen.getByRole('button', { name: /common\.operation\.clear Active/ })+ expect(trigger).toBeDisabled()+ expect(clear).toBeDisabled()+ await user.click(trigger)+ await user.click(clear)+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument()+ expect(onSelect).not.toHaveBeenCalled()+ expect(onClear).not.toHaveBeenCalled()+})diff --git a/web/app/components/base/chip/index.tsx b/web/app/components/base/chip/index.tsxindex b9a72266fb0..dfc63f41157 100644--- a/web/app/components/base/chip/index.tsx+++ b/web/app/components/base/chip/index.tsx@@ -23,6 +23,7 @@ export type Item<T extends ItemValue = ItemValue> = {type Props<T extends ItemValue> = {id?: string+ disabled?: boolean'aria-labelledby'?: stringclassName?: stringpanelClassName?: string@@ -37,6 +38,7 @@ type Props<T extends ItemValue> = {function Chip<T extends ItemValue>({id,+ disabled = false,'aria-labelledby': ariaLabelledBy,className,panelClassName,@@ -58,6 +60,7 @@ function Chip<T extends ItemValue>({return (<Select<T>+ disabled={disabled}value={selectedItem?.value ?? null}itemToStringLabel={(itemValue: T) =>items.find((item) => Object.is(item.value, itemValue))?.name ?? ''@@ -120,8 +123,9 @@ function Chip<T extends ItemValue>({{hasValue && (<buttontype="button"+ disabled={disabled}aria-label={clearLabel}- className="group/clear absolute top-1/2 right-1.5 flex size-5 -translate-y-1/2 cursor-pointer touch-manipulation items-center justify-center rounded-md border-none bg-transparent p-0 outline-hidden focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid"+ className="group/clear absolute top-1/2 right-1.5 flex size-5 -translate-y-1/2 cursor-pointer touch-manipulation items-center justify-center rounded-md border-none bg-transparent p-0 outline-hidden focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid disabled:cursor-not-allowed disabled:opacity-50"onClick={onClear}><spandiff --git a/web/app/components/base/copy-icon/__tests__/index.spec.tsx b/web/app/components/base/copy-icon/__tests__/index.spec.tsxindex 5bbdc40fdb2..5038a3f83b7 100644--- a/web/app/components/base/copy-icon/__tests__/index.spec.tsx+++ b/web/app/components/base/copy-icon/__tests__/index.spec.tsx@@ -5,15 +5,11 @@ import CopyIcon from '..'it('copies the supplied embed content and resets feedback when the pointer leaves', async () => {const user = userEvent.setup()render(<CopyIcon content="Embed this app" />)- const button = screen.getByRole('button', { name: 'appOverview.overview.appInfo.embedded.copy' })+ const button = screen.getByRole('button', { name: 'common.operation.copy' })await user.click(button)expect(await navigator.clipboard.readText()).toBe('Embed this app')- expect(- await screen.findByRole('button', { name: 'appOverview.overview.appInfo.embedded.copied' }),- ).toBeInTheDocument()+ expect(await screen.findByRole('button', { name: 'common.operation.copied' })).toBeInTheDocument()await user.unhover(button)- expect(- screen.getByRole('button', { name: 'appOverview.overview.appInfo.embedded.copy' }),- ).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.copy' })).toBeInTheDocument()})diff --git a/web/app/components/base/copy-icon/index.tsx b/web/app/components/base/copy-icon/index.tsxindex f6b6f5ee93b..a913df2c6c6 100644--- a/web/app/components/base/copy-icon/index.tsx+++ b/web/app/components/base/copy-icon/index.tsx@@ -8,10 +8,8 @@ type Props = Readonly<{content: string}>-const prefixEmbedded = 'overview.appInfo.embedded'-const CopyIcon = ({ content }: Props) => {- const { t } = useTranslation(['appOverview'])+ const { t } = useTranslation(['common'])const { copied, copy, reset } = useClipboard()const handleCopy = useCallback(() => {@@ -19,8 +17,8 @@ const CopyIcon = ({ content }: Props) => {}, [copy, content])const tooltipText = copied- ? t(($) => $[`${prefixEmbedded}.copied`], { ns: 'appOverview' })- : t(($) => $[`${prefixEmbedded}.copy`], { ns: 'appOverview' })+ ? t(($) => $['operation.copied'], { ns: 'common' })+ : t(($) => $['operation.copy'], { ns: 'common' })/* v8 ignore next -- i18n test mock always returns a non-empty string; runtime fallback is defensive. -- @preserve */const safeTooltipText = tooltipText || ''diff --git a/web/models/log.ts b/web/models/log.tsindex c7de88d7d2a..327bcca3528 100644--- a/web/models/log.ts+++ b/web/models/log.ts@@ -1,7 +1,7 @@import type { Viewport } from 'reactflow'import type { Edge, Node } from '@/app/components/workflow/types'-export type LogAnnotation = {+type LogAnnotation = {id: stringcontent: stringaccount: {