feat(ai): add AI chat session management features (#4386)
* feat: add AI chat session queries * feat(ai): add ChatSessionDropdown component to manage chat sessions * refactor: renaming ChatSessionDropdown to TaskReportDropdown in headers * chore: clean code * feat: add AIChatSessionService for syncing chat session messages * refactor: improve unread session handling * feat: ensure chat session is marked as seen after message persistence * feat: implement pagination for fetching unseen remote messages * fix: prefer original message start time for createdAt in message conversion * feat: implement active chat in AI setting * chore: clean code * fix: code review * fix: add asChild prop to control DropdownMenuTrigger behavior * feat: add button to view scheduled tasks in settings * chore: enhance DropdownMenuTrigger with unread session indicator
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
export * from "./query"
|
||||
export * from "./service"
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
DeleteSessionRequest,
|
||||
GetMessagesQuery,
|
||||
GetUnreadQuery,
|
||||
ListSessionsQuery,
|
||||
MarkSeenRequest,
|
||||
SessionResponse,
|
||||
UpdateSessionRequest,
|
||||
} from "@follow-app/client-sdk"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
|
||||
import { followApi } from "~/lib/api-client"
|
||||
|
||||
const aiChatSessionKey = "ai-chat-session"
|
||||
export const aiChatSessionKeys = {
|
||||
lists: [aiChatSessionKey, "list"] as const,
|
||||
list: (filters?: ListSessionsQuery) => [aiChatSessionKey, "list", filters] as const,
|
||||
details: [aiChatSessionKey, "detail"] as const,
|
||||
detail: (chatId: string) => [aiChatSessionKey, "detail", chatId] as const,
|
||||
messages: [aiChatSessionKey, "messages"] as const,
|
||||
message: (chatId: string, filters?: GetMessagesQuery) =>
|
||||
[aiChatSessionKey, "messages", chatId, filters] as const,
|
||||
unread: [aiChatSessionKey, "unread"] as const,
|
||||
} as const
|
||||
|
||||
// Queries
|
||||
|
||||
export const useAIChatSessionListQuery = (filters?: ListSessionsQuery) => {
|
||||
const { data } = useQuery({
|
||||
queryKey: aiChatSessionKeys.list(filters),
|
||||
queryFn: () => followApi.aiChatSessions.list(filters).then((res) => res.data),
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export const useAIChatSessionQuery = (chatId: string | undefined, opts?: { enabled?: boolean }) => {
|
||||
const enabled = !!chatId && (opts?.enabled ?? true)
|
||||
const { data } = useQuery({
|
||||
queryKey: chatId ? aiChatSessionKeys.detail(chatId) : aiChatSessionKeys.details,
|
||||
queryFn: () =>
|
||||
followApi.aiChatSessions.get({ chatId: chatId as string }).then((res) => res.data),
|
||||
enabled,
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export const useAIChatMessagesQuery = (
|
||||
chatId: string | undefined,
|
||||
filters?: GetMessagesQuery,
|
||||
opts?: { enabled?: boolean },
|
||||
) => {
|
||||
const enabled = !!chatId && (opts?.enabled ?? true)
|
||||
const { data } = useQuery({
|
||||
queryKey: chatId ? aiChatSessionKeys.message(chatId, filters) : aiChatSessionKeys.messages,
|
||||
queryFn: () =>
|
||||
followApi.aiChatSessions.messages
|
||||
.get({ chatId: chatId as string, ...filters })
|
||||
.then((res) => res.data),
|
||||
enabled,
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export const useUnreadChatSessionsQuery = (filters?: GetUnreadQuery) => {
|
||||
const { data } = useQuery({
|
||||
queryKey: aiChatSessionKeys.unread,
|
||||
queryFn: () => followApi.aiChatSessions.unread(filters).then((res) => res.data),
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
// Mutations
|
||||
|
||||
export const useUpdateAIChatSessionMutation = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation<SessionResponse, unknown, UpdateSessionRequest>({
|
||||
mutationFn: (input) => followApi.aiChatSessions.update(input),
|
||||
onSuccess: async (res) => {
|
||||
const chatId = res?.data?.chatId ?? undefined
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
chatId
|
||||
? qc.invalidateQueries({ queryKey: aiChatSessionKeys.detail(chatId) })
|
||||
: Promise.resolve(),
|
||||
])
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useDeleteAIChatSessionMutation = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation<{ success: boolean }, unknown, DeleteSessionRequest>({
|
||||
mutationFn: (input) => followApi.aiChatSessions.delete(input),
|
||||
onSuccess: async (_res, vars) => {
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.detail(vars.chatId) }),
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.messages }),
|
||||
])
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useMarkChatSessionSeenMutation = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation<SessionResponse, unknown, MarkSeenRequest>({
|
||||
mutationFn: (input) => followApi.aiChatSessions.markSeen(input),
|
||||
onSuccess: async (res) => {
|
||||
const chatId = res?.data?.chatId ?? undefined
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.unread }),
|
||||
chatId
|
||||
? qc.invalidateQueries({ queryKey: aiChatSessionKeys.detail(chatId) })
|
||||
: Promise.resolve(),
|
||||
])
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { AIChatMessage, AIChatSession } from "@follow-app/client-sdk"
|
||||
|
||||
import { followApi } from "../../lib/api-client"
|
||||
import { queryClient } from "../../lib/query-client"
|
||||
import { AIPersistService } from "../ai-chat/services"
|
||||
import type { BizUIMessage } from "../ai-chat/store/types"
|
||||
import { aiChatSessionKeys } from "./query"
|
||||
|
||||
// Hard cap on pagination to prevent excessive API calls while keeping initial sync fast.
|
||||
const MAX_PAGES = 10
|
||||
|
||||
/**
|
||||
* Service for syncing AI chat session messages from remote API into local DB.
|
||||
*/
|
||||
class AIChatSessionServiceStatic {
|
||||
/**
|
||||
* Fetch messages for a chat session from the remote API and persist (upsert) them locally.
|
||||
* Returns the normalized BizUIMessage list that was persisted.
|
||||
*
|
||||
* Defensive in extracting the message array because the SDK response shape may evolve.
|
||||
*/
|
||||
async fetchAndPersistMessages(session: AIChatSession): Promise<BizUIMessage[]> {
|
||||
const unseenMessages = await this.fetchUnseenRemoteMessages(session.chatId, session.lastSeenAt)
|
||||
const normalized = unseenMessages.map(this.normalizeRemoteMessage)
|
||||
|
||||
await AIPersistService.ensureSession(session.chatId, session.title)
|
||||
await AIPersistService.upsertMessages(session.chatId, normalized)
|
||||
|
||||
await followApi.aiChatSessions.markSeen({
|
||||
chatId: session.chatId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
// Invalidate related queries so UI updates outside of hook-based mutation flows
|
||||
Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.detail(session.chatId) }),
|
||||
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.unread }),
|
||||
])
|
||||
return normalized
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch remote messages for a chat session that are newer than the provided lastSeenAt timestamp.
|
||||
* Implements keyset pagination using `before` / `nextBefore` and stops when:
|
||||
* - We have paged past (<=) lastSeenAt, or
|
||||
* - There is no further `nextBefore`, or
|
||||
* - A safety MAX_PAGES cap is reached.
|
||||
* Returns only unseen (newer) remote messages.
|
||||
*/
|
||||
private async fetchUnseenRemoteMessages(
|
||||
chatId: string,
|
||||
lastSeenAt: string,
|
||||
): Promise<AIChatMessage[]> {
|
||||
const allMessages: AIChatMessage[] = []
|
||||
const lastSeenAtDate = new Date(lastSeenAt)
|
||||
let before: string | undefined
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
const resp = await followApi.aiChatSessions.messages.get(
|
||||
before ? { chatId, before } : { chatId },
|
||||
)
|
||||
const { data } = resp
|
||||
const batch = data.messages
|
||||
allMessages.push(...batch)
|
||||
|
||||
const { nextBefore } = data
|
||||
if (!nextBefore || new Date(nextBefore) <= lastSeenAtDate) {
|
||||
break
|
||||
}
|
||||
before = nextBefore
|
||||
}
|
||||
return allMessages.sort(
|
||||
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a remote message object into BizUIMessage shape expected by the local chat system.
|
||||
*/
|
||||
private normalizeRemoteMessage = (msg: AIChatMessage): BizUIMessage => {
|
||||
const startTime = msg.createdAt
|
||||
const finishTime = msg.finishedAt ?? undefined
|
||||
const duration = finishTime
|
||||
? new Date(finishTime).getTime() - new Date(startTime).getTime()
|
||||
: undefined
|
||||
|
||||
const metadata: BizUIMessage["metadata"] = {
|
||||
finishTime,
|
||||
duration,
|
||||
}
|
||||
|
||||
const normalizedParts = msg.messageParts.filter(
|
||||
(i) => i.type === "text",
|
||||
) satisfies BizUIMessage["parts"]
|
||||
|
||||
return {
|
||||
id: msg.id,
|
||||
role: msg.role satisfies BizUIMessage["role"],
|
||||
parts: normalizedParts,
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const AIChatSessionService = new AIChatSessionServiceStatic()
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { FC, PropsWithChildren } from "react"
|
||||
import { useMemo, useRef } from "react"
|
||||
import { useEffect, useMemo, useRef } from "react"
|
||||
|
||||
import { Focusable } from "~/components/common/Focusable"
|
||||
import { HotkeyScope } from "~/constants"
|
||||
|
||||
import type { AIPanelRefs } from "../../store/AIChatContext"
|
||||
import { AIChatStoreContext, AIPanelRefsContext } from "../../store/AIChatContext"
|
||||
import { ChatSliceActions } from "../../store/chat-core/chat-actions"
|
||||
import { useChatActions, useCurrentChatId } from "../../store/hooks"
|
||||
import { createAIChatStore } from "../../store/store"
|
||||
|
||||
@@ -49,6 +50,11 @@ export const AIChatRoot: FC<AIChatRootProps> = ({
|
||||
chatId: externalChatId,
|
||||
}) => {
|
||||
const useAiContextStore = useMemo(createAIChatStore, [])
|
||||
const chatActions = useAiContextStore((state) => state.chatActions)
|
||||
|
||||
useEffect(() => {
|
||||
ChatSliceActions.setActiveInstance(chatActions)
|
||||
}, [chatActions])
|
||||
|
||||
const Element = (
|
||||
<AIChatStoreContext value={useAiContextStore}>
|
||||
@@ -65,3 +71,4 @@ export const AIChatRoot: FC<AIChatRootProps> = ({
|
||||
}
|
||||
return Element
|
||||
}
|
||||
AIChatRoot.displayName = "AIChatRoot"
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useBlockActions, useChatActions, useCurrentTitle } from "~/modules/ai-c
|
||||
|
||||
import { ChatMoreDropdown } from "./ChatMoreDropdown"
|
||||
import { EditableTitle } from "./EditableTitle"
|
||||
import { TaskReportDropdown } from "./TaskReportDropdown"
|
||||
|
||||
// Base header layout with shared logic inside
|
||||
const ChatHeaderLayout = ({
|
||||
@@ -80,6 +81,8 @@ export const ChatHeader = () => {
|
||||
<i className="i-mgc-add-cute-re text-text-secondary size-5" />
|
||||
</ActionButton>
|
||||
|
||||
<TaskReportDropdown />
|
||||
|
||||
<ChatMoreDropdown
|
||||
triggerElement={
|
||||
<ActionButton tooltip="More">
|
||||
@@ -111,6 +114,15 @@ export const ChatPageHeader = () => {
|
||||
<i className="i-mgc-add-cute-re text-text-secondary size-4" />
|
||||
</GlassButton>
|
||||
|
||||
<TaskReportDropdown
|
||||
asChild={false}
|
||||
triggerElement={
|
||||
<GlassButton description="Task Reports" size="sm">
|
||||
<i className="i-mgc-inbox-cute-re text-text-secondary size-4" />
|
||||
</GlassButton>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="bg-border mx-2 h-5 w-px" />
|
||||
<ChatMoreDropdown
|
||||
canToggleMode={false}
|
||||
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
import { ActionButton } from "@follow/components/ui/button/index.js"
|
||||
import type { AIChatSession } from "@follow-app/client-sdk"
|
||||
import type { ReactElement } from "react"
|
||||
import { useCallback, useMemo, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { RelativeDay } from "~/components/ui/datetime"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu/dropdown-menu"
|
||||
import { useDialog } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useChatActions, useCurrentChatId } from "~/modules/ai-chat/store/hooks"
|
||||
import { AIChatSessionService } from "~/modules/ai-chat-session"
|
||||
import {
|
||||
useAIChatSessionListQuery,
|
||||
useDeleteAIChatSessionMutation,
|
||||
} from "~/modules/ai-chat-session/query"
|
||||
|
||||
import { AIPersistService } from "../../services"
|
||||
|
||||
interface TaskReportDropdownProps {
|
||||
triggerElement?: ReactElement
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
interface SessionItemProps {
|
||||
session: AIChatSession
|
||||
onClick?: () => void
|
||||
onDelete?: (e: React.MouseEvent) => void
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
// Helper to determine if a session has unread messages
|
||||
const isSessionUnread = (session: AIChatSession): boolean => {
|
||||
if (!session.lastSeenAt || !session.updatedAt) return false
|
||||
return new Date(session.updatedAt) > new Date(session.lastSeenAt)
|
||||
}
|
||||
|
||||
const SessionItem = ({ session, onClick, onDelete, isLoading }: SessionItemProps) => {
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
onClick={onClick}
|
||||
className={`group relative ${onClick ? "cursor-pointer" : "cursor-default"}`}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 justify-between">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<p className="mb-0.5 truncate font-medium">{session.title || "Untitled Chat"}</p>
|
||||
</div>
|
||||
<div className="relative flex min-w-0 items-center">
|
||||
<p className="text-text-secondary ml-2 shrink-0 truncate text-xs">
|
||||
<RelativeDay date={new Date(session.createdAt)} />
|
||||
</p>
|
||||
{onDelete && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDelete}
|
||||
className="bg-accent absolute inset-y-0 right-0 flex items-center px-2 py-1 text-white opacity-0 shadow-lg backdrop-blur-sm group-data-[highlighted]:text-white group-data-[highlighted]:opacity-100"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<i className="i-mgc-loading-3-cute-re size-4 animate-spin" />
|
||||
) : (
|
||||
<i className="i-mgc-delete-2-cute-re size-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
const EmptyState = () => {
|
||||
return (
|
||||
<div className="flex flex-col items-center py-8 text-center">
|
||||
<i className="i-mgc-inbox-cute-re text-text-secondary mb-2 block size-8" />
|
||||
<p className="text-text-secondary text-sm">All task reports read</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskReportDropdownProps) => {
|
||||
const sessions = useAIChatSessionListQuery()
|
||||
const currentChatId = useCurrentChatId()
|
||||
const chatActions = useChatActions()
|
||||
const deleteSessionMutation = useDeleteAIChatSessionMutation()
|
||||
const { ask } = useDialog()
|
||||
const { t } = useTranslation("ai")
|
||||
const [loadingChatId, setLoadingChatId] = useState<string | null>(null)
|
||||
|
||||
// Only keep unread sessions for display
|
||||
const unreadSessions = useMemo(
|
||||
() => (sessions || []).filter((s) => isSessionUnread(s)),
|
||||
[sessions],
|
||||
)
|
||||
|
||||
const hasUnreadSessions = unreadSessions.length > 0
|
||||
|
||||
const handleSessionSelect = useCallback(
|
||||
async (session: AIChatSession) => {
|
||||
if (session.chatId === currentChatId) return
|
||||
try {
|
||||
await AIChatSessionService.fetchAndPersistMessages(session)
|
||||
} catch (e) {
|
||||
console.error("Failed to sync chat session messages:", e)
|
||||
toast.error("Failed to load chat messages")
|
||||
}
|
||||
chatActions.switchToChat(session.chatId)
|
||||
},
|
||||
[chatActions, currentChatId],
|
||||
)
|
||||
|
||||
const handleDeleteSession = useCallback(
|
||||
async (chatId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
|
||||
const session = sessions?.find((s) => s.chatId === chatId)
|
||||
if (!session) return
|
||||
|
||||
const confirm = await ask({
|
||||
title: t("delete_chat"),
|
||||
message: t("delete_chat_message", { title: session.title || "Untitled Chat" }),
|
||||
variant: "danger",
|
||||
})
|
||||
|
||||
if (!confirm) return
|
||||
|
||||
setLoadingChatId(chatId)
|
||||
try {
|
||||
await Promise.all([
|
||||
deleteSessionMutation.mutateAsync({ chatId }),
|
||||
AIPersistService.deleteSession(chatId),
|
||||
])
|
||||
toast.success(t("delete_chat_success"))
|
||||
|
||||
if (chatId === currentChatId) {
|
||||
chatActions.newChat()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete session:", error)
|
||||
toast.error(t("delete_chat_error"))
|
||||
} finally {
|
||||
setLoadingChatId(null)
|
||||
}
|
||||
},
|
||||
[sessions, ask, t, currentChatId, chatActions, deleteSessionMutation],
|
||||
)
|
||||
|
||||
const defaultTrigger = (
|
||||
<ActionButton tooltip="Task Reports" className="relative">
|
||||
<i className="i-mgc-inbox-cute-re text-text-secondary size-5" />
|
||||
{hasUnreadSessions && (
|
||||
<span
|
||||
className="bg-accent absolute right-1 top-1 block size-2 rounded-full shadow-[0_0_0_2px_var(--color-bg-default)] dark:shadow-[0_0_0_2px_var(--color-bg-default)]"
|
||||
aria-label="Unread task reports"
|
||||
/>
|
||||
)}
|
||||
</ActionButton>
|
||||
)
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
{asChild ? (
|
||||
<DropdownMenuTrigger asChild={asChild}>
|
||||
{triggerElement || defaultTrigger}
|
||||
</DropdownMenuTrigger>
|
||||
) : (
|
||||
<DropdownMenuTrigger className="relative">
|
||||
{triggerElement || defaultTrigger}
|
||||
{hasUnreadSessions && triggerElement && (
|
||||
<span
|
||||
className="bg-accent absolute right-1 top-1 block size-2 rounded-full shadow-[0_0_0_2px_var(--color-bg-default)] dark:shadow-[0_0_0_2px_var(--color-bg-default)]"
|
||||
aria-label="Unread task reports"
|
||||
/>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
)}
|
||||
|
||||
<DropdownMenuContent align="end" className="w-80">
|
||||
{unreadSessions.length > 0 ? (
|
||||
unreadSessions.map((session) => (
|
||||
<SessionItem
|
||||
key={session.chatId}
|
||||
session={session}
|
||||
onClick={() => handleSessionSelect(session)}
|
||||
onDelete={(e) => handleDeleteSession(session.chatId, e)}
|
||||
isLoading={loadingChatId === session.chatId}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<EmptyState />
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -105,21 +105,25 @@ class AIPersistServiceStatic {
|
||||
messages.map((message) => {
|
||||
// Store parts as-is since they're stored as JSON and the UI can handle them
|
||||
const convertedParts = message.parts as any[]
|
||||
const createdAt =
|
||||
message.metadata?.finishTime && typeof message.metadata?.duration === "number"
|
||||
? new Date(
|
||||
new Date(message.metadata.finishTime).getTime() - message.metadata.duration,
|
||||
)
|
||||
: new Date()
|
||||
|
||||
return {
|
||||
id: message.id,
|
||||
chatId,
|
||||
role: message.role,
|
||||
contentFormat: "plaintext" as const,
|
||||
|
||||
createdAt: new Date(),
|
||||
createdAt,
|
||||
status: "completed" as const,
|
||||
finishedAt: message.metadata?.finishTime
|
||||
? new Date(message.metadata.finishTime)
|
||||
: undefined,
|
||||
messageParts: convertedParts,
|
||||
metadata: message.metadata,
|
||||
} as typeof aiChatMessagesTable.$inferInsert
|
||||
} satisfies typeof aiChatMessagesTable.$inferInsert
|
||||
}),
|
||||
)
|
||||
.onConflictDoUpdate({
|
||||
@@ -157,12 +161,17 @@ class AIPersistServiceStatic {
|
||||
messages
|
||||
.filter((message) => message.parts.length > 0)
|
||||
.map((message) => {
|
||||
const createdAt =
|
||||
message.metadata?.finishTime && typeof message.metadata?.duration === "number"
|
||||
? new Date(
|
||||
new Date(message.metadata.finishTime).getTime() - message.metadata.duration,
|
||||
)
|
||||
: new Date()
|
||||
return {
|
||||
id: message.id,
|
||||
chatId,
|
||||
role: message.role,
|
||||
contentFormat: "plaintext" as const,
|
||||
createdAt: new Date(),
|
||||
createdAt,
|
||||
status: "completed" as const,
|
||||
finishedAt: message.metadata?.finishTime
|
||||
? new Date(message.metadata.finishTime)
|
||||
|
||||
@@ -10,6 +10,21 @@ import { ZustandChat } from "./chat-instance"
|
||||
import type { ChatSlice } from "./types"
|
||||
|
||||
export class ChatSliceActions {
|
||||
// Hold reference to the most recently constructed (active) ChatSliceActions instance
|
||||
private static _current: ChatSliceActions | null = null
|
||||
|
||||
/**
|
||||
* Get the currently active ChatSliceActions instance.
|
||||
*/
|
||||
static getActiveInstance(): ChatSliceActions | null {
|
||||
if (!this._current) return null
|
||||
return this._current
|
||||
}
|
||||
|
||||
static setActiveInstance(instance: ChatSliceActions | null) {
|
||||
this._current = instance
|
||||
}
|
||||
|
||||
constructor(
|
||||
private params: Parameters<StateCreator<ChatSlice, [], [], ChatSlice>>,
|
||||
private chatInstance: ZustandChat,
|
||||
|
||||
@@ -35,9 +35,9 @@ export const ItemActions = ({ actions, enabled, onToggle }: ItemActionsProps) =>
|
||||
<div className="ml-4 flex items-center gap-3">
|
||||
{/* Action buttons group */}
|
||||
<div className="flex items-center gap-1 opacity-60 transition-opacity group-hover:opacity-100">
|
||||
{actions.map((action, index) => (
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
key={index}
|
||||
key={action.title}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={action.onClick}
|
||||
|
||||
@@ -20,6 +20,7 @@ import { useCurrentModal } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useCreateAITaskMutation, useUpdateAITaskMutation } from "~/modules/ai-task/query"
|
||||
import type { ScheduleType } from "~/modules/ai-task/types"
|
||||
import { scheduleSchema } from "~/modules/ai-task/types"
|
||||
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
|
||||
|
||||
import { ScheduleConfig } from "./schedule-config"
|
||||
|
||||
@@ -133,6 +134,7 @@ export const AITaskModal = ({ task, prompt, onSubmit }: AITaskModalProps) => {
|
||||
const createAITaskMutation = useCreateAITaskMutation()
|
||||
const updateAITaskMutation = useUpdateAITaskMutation()
|
||||
const { t } = useTranslation("ai")
|
||||
const settingModalPresent = useSettingModal()
|
||||
|
||||
const isEditing = !!task
|
||||
|
||||
@@ -274,8 +276,18 @@ export const AITaskModal = ({ task, prompt, onSubmit }: AITaskModalProps) => {
|
||||
|
||||
{/* Form Actions */}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div />
|
||||
<div className="flex items-center justify-end">
|
||||
{!task && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => settingModalPresent("ai")}
|
||||
className="text-text-tertiary hover:text-text-secondary mr-auto flex items-center gap-1 text-xs underline-offset-2 hover:underline disabled:opacity-50"
|
||||
disabled={currentMutation.isPending}
|
||||
>
|
||||
<i className="i-mgc-settings-7-cute-re size-3" />
|
||||
{t("tasks.view_in_settings")}
|
||||
</button>
|
||||
)}
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { AITask, TaskSchedule } from "@follow-app/client-sdk"
|
||||
import dayjs from "dayjs"
|
||||
import { memo } from "react"
|
||||
import { memo, useCallback, useMemo, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { setAIPanelVisibility } from "~/atoms/settings/ai"
|
||||
import { useDialog, useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { ChatSliceActions } from "~/modules/ai-chat/store/chat-core/chat-actions"
|
||||
import { AIChatSessionService } from "~/modules/ai-chat-session"
|
||||
import { useAIChatSessionListQuery } from "~/modules/ai-chat-session/query"
|
||||
import type { ActionButton } from "~/modules/ai-task/components/ai-item-actions"
|
||||
import { ItemActions } from "~/modules/ai-task/components/ai-item-actions"
|
||||
|
||||
import { useDeleteAITaskMutation, useUpdateAITaskMutation } from "../query"
|
||||
import { AITaskModal } from "./ai-task-modal"
|
||||
|
||||
interface TaskItemProps {
|
||||
task: AITask
|
||||
isDeleting: boolean
|
||||
onDelete: (id: string, name: string) => void
|
||||
onToggle: (id: string, name: string, currentEnabled: boolean) => void
|
||||
}
|
||||
|
||||
const formatScheduleText = (schedule: TaskSchedule) => {
|
||||
if (!schedule) return "Unknown schedule"
|
||||
|
||||
@@ -76,11 +76,23 @@ const getStatusColor = (status: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
export const TaskItem = memo<TaskItemProps>(({ task, isDeleting, onDelete, onToggle }) => {
|
||||
export const TaskItem = memo(({ task }: { task: AITask }) => {
|
||||
const { present } = useModalStack()
|
||||
const deleteTaskMutation = useDeleteAITaskMutation()
|
||||
const updateTaskMutation = useUpdateAITaskMutation()
|
||||
const { ask } = useDialog()
|
||||
const { t } = useTranslation()
|
||||
const sessions = useAIChatSessionListQuery()
|
||||
// const chatActions = useChatActions()
|
||||
const [openingReport, setOpeningReport] = useState(false)
|
||||
const status = getTaskStatus(task)
|
||||
const statusColorClass = getStatusColor(status)
|
||||
|
||||
const taskSession = useMemo(
|
||||
() => sessions?.find((s) => s.chatId === task.id),
|
||||
[sessions, task.id],
|
||||
)
|
||||
|
||||
const handleEditTask = (task: AITask) => {
|
||||
present({
|
||||
title: "Edit AI Task",
|
||||
@@ -89,7 +101,43 @@ export const TaskItem = memo<TaskItemProps>(({ task, isDeleting, onDelete, onTog
|
||||
})
|
||||
}
|
||||
|
||||
const isDeleting = deleteTaskMutation.isPending
|
||||
|
||||
const handleOpenReport = useCallback(async () => {
|
||||
if (!taskSession) {
|
||||
toast.error("No report session found for this task yet.")
|
||||
return
|
||||
}
|
||||
setOpeningReport(true)
|
||||
try {
|
||||
await AIChatSessionService.fetchAndPersistMessages(taskSession)
|
||||
} catch (e) {
|
||||
console.error("Failed to sync chat session messages:", e)
|
||||
toast.error("Failed to load chat messages")
|
||||
}
|
||||
setAIPanelVisibility(true)
|
||||
const chatActions = ChatSliceActions.getActiveInstance()
|
||||
if (!chatActions) {
|
||||
console.error("No active chat session found.")
|
||||
}
|
||||
chatActions?.switchToChat(taskSession.chatId)
|
||||
setOpeningReport(false)
|
||||
toast("Switch to the chat panel to view reports.")
|
||||
}, [taskSession])
|
||||
|
||||
const actions: ActionButton[] = [
|
||||
// Only show if the task has at least one run
|
||||
...(taskSession
|
||||
? [
|
||||
{
|
||||
icon: "i-mgc-history-cute-re" as const,
|
||||
onClick: handleOpenReport,
|
||||
title: "View reports",
|
||||
loading: openingReport,
|
||||
disabled: openingReport,
|
||||
} satisfies ActionButton,
|
||||
]
|
||||
: []),
|
||||
{
|
||||
icon: "i-mgc-edit-cute-re",
|
||||
onClick: () => handleEditTask(task),
|
||||
@@ -97,7 +145,24 @@ export const TaskItem = memo<TaskItemProps>(({ task, isDeleting, onDelete, onTog
|
||||
},
|
||||
{
|
||||
icon: "i-mgc-delete-2-cute-re",
|
||||
onClick: () => onDelete(task.id, task.name),
|
||||
onClick: async () => {
|
||||
const confirmed = await ask({
|
||||
title: "Delete Task",
|
||||
// translation fallback pattern; primary key then default string
|
||||
message: `Are you sure you want to delete the task "${task.name}"?`,
|
||||
confirmText: t("words.delete", { ns: "common" }),
|
||||
cancelText: t("words.cancel", { ns: "common" }),
|
||||
variant: "danger",
|
||||
})
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await deleteTaskMutation.mutateAsync({ id: task.id })
|
||||
toast.success("Task deleted successfully")
|
||||
} catch (error) {
|
||||
console.error("Failed to delete task:", error)
|
||||
toast.error("Failed to delete task. Please try again.")
|
||||
}
|
||||
},
|
||||
title: "Delete task",
|
||||
disabled: isDeleting,
|
||||
loading: isDeleting,
|
||||
@@ -144,7 +209,14 @@ export const TaskItem = memo<TaskItemProps>(({ task, isDeleting, onDelete, onTog
|
||||
<ItemActions
|
||||
actions={actions}
|
||||
enabled={task.isEnabled}
|
||||
onToggle={() => onToggle(task.id, task.name, task.isEnabled)}
|
||||
onToggle={async () => {
|
||||
try {
|
||||
await updateTaskMutation.mutateAsync({ id: task.id, isEnabled: !task.isEnabled })
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle task:", error)
|
||||
toast.error("Failed to update task. Please try again.")
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import { memo, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
import { memo } from "react"
|
||||
|
||||
import { useDialog } from "~/components/ui/modal/stacked/hooks"
|
||||
|
||||
import { useAITaskListQuery, useDeleteAITaskMutation, useUpdateAITaskMutation } from "../query"
|
||||
import { useAITaskListQuery } from "../query"
|
||||
import { TaskItem } from "./task-item"
|
||||
|
||||
interface TaskListProps {
|
||||
@@ -14,48 +10,6 @@ interface TaskListProps {
|
||||
|
||||
export const AITaskList = memo<TaskListProps>(({ className }) => {
|
||||
const tasks = useAITaskListQuery()
|
||||
const deleteTaskMutation = useDeleteAITaskMutation()
|
||||
const updateTaskMutation = useUpdateAITaskMutation()
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null)
|
||||
|
||||
const { ask } = useDialog()
|
||||
const { t } = useTranslation()
|
||||
const handleDeleteTask = async (id: string, name: string) => {
|
||||
const confirmed = await ask({
|
||||
title: "Delete Task",
|
||||
message: `Are you sure you want to delete the task "${name}"?`,
|
||||
confirmText: t("words.delete", { ns: "common" }),
|
||||
cancelText: "Cancel",
|
||||
variant: "danger",
|
||||
})
|
||||
|
||||
if (!confirmed) {
|
||||
return
|
||||
}
|
||||
|
||||
setDeletingId(id)
|
||||
try {
|
||||
await deleteTaskMutation.mutateAsync({ id })
|
||||
toast.success("Task deleted successfully")
|
||||
} catch (error) {
|
||||
console.error("Failed to delete task:", error)
|
||||
toast.error("Failed to delete task. Please try again.")
|
||||
} finally {
|
||||
setDeletingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggleTask = async (id: string, name: string, currentEnabled: boolean) => {
|
||||
try {
|
||||
await updateTaskMutation.mutateAsync({
|
||||
id,
|
||||
isEnabled: !currentEnabled,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle task:", error)
|
||||
toast.error("Failed to update task. Please try again.")
|
||||
}
|
||||
}
|
||||
|
||||
if (tasks === undefined) {
|
||||
return null
|
||||
@@ -78,13 +32,7 @@ export const AITaskList = memo<TaskListProps>(({ className }) => {
|
||||
return (
|
||||
<div className={cn("space-y-4", className)}>
|
||||
{tasks.map((task) => (
|
||||
<TaskItem
|
||||
key={task.id}
|
||||
task={task}
|
||||
isDeleting={deletingId === task.id}
|
||||
onDelete={handleDeleteTask}
|
||||
onToggle={handleToggleTask}
|
||||
/>
|
||||
<TaskItem key={task.id} task={task} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { PanelSplitter } from "@follow/components/ui/divider/index.js"
|
||||
import { defaultUISettings } from "@follow/shared/settings/defaults"
|
||||
import { cn } from "@follow/utils"
|
||||
import { AnimatePresence } from "motion/react"
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react"
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from "react"
|
||||
import { useResizable } from "react-resizable-layout"
|
||||
import { useParams } from "react-router"
|
||||
|
||||
@@ -170,7 +170,7 @@ const AIEntryLayoutImpl = () => {
|
||||
)
|
||||
}
|
||||
|
||||
export const AIEntryLayout = () => {
|
||||
export const AIEntryLayout = memo(function AIEntryLayout() {
|
||||
return (
|
||||
<AIChatRoot wrapFocusable={false}>
|
||||
<AIEntryLayoutImpl />
|
||||
@@ -178,4 +178,5 @@ export const AIEntryLayout = () => {
|
||||
<AISplineButton />
|
||||
</AIChatRoot>
|
||||
)
|
||||
}
|
||||
})
|
||||
AIEntryLayout.displayName = "AIEntryLayout"
|
||||
|
||||
@@ -158,6 +158,7 @@
|
||||
"tasks.validation.prompt_required": "Prompt is required",
|
||||
"tasks.validation.title_max": "Title must be less than 50 characters",
|
||||
"tasks.validation.title_required": "Title is required",
|
||||
"tasks.view_in_settings": "View scheduled tasks in Settings",
|
||||
"token_usage.description": "Monitor your AI token consumption and limits",
|
||||
"token_usage.resets_at": "Resets at",
|
||||
"token_usage.title": "Token Usage",
|
||||
|
||||
@@ -126,6 +126,7 @@
|
||||
"tasks.validation.prompt_required": "プロンプトは必須です",
|
||||
"tasks.validation.title_max": "タイトルは50文字未満である必要があります",
|
||||
"tasks.validation.title_required": "タイトルは必須です",
|
||||
"tasks.view_in_settings": "設定でスケジュールされたタスクを表示",
|
||||
"usage_analysis.active_session": "アクティブセッション",
|
||||
"usage_analysis.current_usage": "現在の使用状況",
|
||||
"usage_analysis.detailed_description": "AI使用パターンとインサイトの包括的概要",
|
||||
|
||||
@@ -154,6 +154,7 @@
|
||||
"tasks.validation.prompt_required": "指令为必填项",
|
||||
"tasks.validation.title_max": "标题必须少于 50 个字符",
|
||||
"tasks.validation.title_required": "标题为必填项",
|
||||
"tasks.view_in_settings": "在设置中查看已计划任务",
|
||||
"token_usage.description": "监控您的AI令牌消耗和限制",
|
||||
"token_usage.resets_at": "重置时间",
|
||||
"token_usage.title": "令牌使用情况",
|
||||
|
||||
Reference in New Issue
Block a user