diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat-session/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat-session/index.ts new file mode 100644 index 000000000..639903a38 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat-session/index.ts @@ -0,0 +1,2 @@ +export * from "./query" +export * from "./service" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat-session/query.ts b/apps/desktop/layer/renderer/src/modules/ai-chat-session/query.ts new file mode 100644 index 000000000..86e1d0f53 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat-session/query.ts @@ -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({ + 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({ + 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(), + ]) + }, + }) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts b/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts new file mode 100644 index 000000000..e62e88a87 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts @@ -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 { + 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 { + 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() diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx index 98d35da6d..636c8c438 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx @@ -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 = ({ chatId: externalChatId, }) => { const useAiContextStore = useMemo(createAIChatStore, []) + const chatActions = useAiContextStore((state) => state.chatActions) + + useEffect(() => { + ChatSliceActions.setActiveInstance(chatActions) + }, [chatActions]) const Element = ( @@ -65,3 +71,4 @@ export const AIChatRoot: FC = ({ } return Element } +AIChatRoot.displayName = "AIChatRoot" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx index fe23bdfef..f771db299 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx @@ -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 = () => { + + @@ -111,6 +114,15 @@ export const ChatPageHeader = () => { + + + + } + /> +
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 ( + +
+
+

{session.title || "Untitled Chat"}

+
+
+

+ +

+ {onDelete && ( + + )} +
+
+
+ ) +} + +const EmptyState = () => { + return ( +
+ +

All task reports read

+
+ ) +} + +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(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 = ( + + + {hasUnreadSessions && ( + + )} + + ) + + return ( + + {asChild ? ( + + {triggerElement || defaultTrigger} + + ) : ( + + {triggerElement || defaultTrigger} + {hasUnreadSessions && triggerElement && ( + + )} + + )} + + + {unreadSessions.length > 0 ? ( + unreadSessions.map((session) => ( + handleSessionSelect(session)} + onDelete={(e) => handleDeleteSession(session.chatId, e)} + isLoading={loadingChatId === session.chatId} + /> + )) + ) : ( + + )} + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts index e9e8c68d6..f2000db9a 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts @@ -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) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts index a7ba5b9c3..99ec0c367 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts @@ -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>, private chatInstance: ZustandChat, diff --git a/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-item-actions.tsx b/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-item-actions.tsx index d29fe812b..7bb8dcd90 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-item-actions.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-task/components/ai-item-actions.tsx @@ -35,9 +35,9 @@ export const ItemActions = ({ actions, enabled, onToggle }: ItemActionsProps) =>
{/* Action buttons group */}
- {actions.map((action, index) => ( + {actions.map((action) => ( + )}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-task/components/task-list.tsx b/apps/desktop/layer/renderer/src/modules/ai-task/components/task-list.tsx index ecc4131bf..d1e6b8537 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-task/components/task-list.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-task/components/task-list.tsx @@ -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(({ className }) => { const tasks = useAITaskListQuery() - const deleteTaskMutation = useDeleteAITaskMutation() - const updateTaskMutation = useUpdateAITaskMutation() - const [deletingId, setDeletingId] = useState(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(({ className }) => { return (
{tasks.map((task) => ( - + ))}
) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx index 3d62db8b6..bb22ab229 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx @@ -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 ( @@ -178,4 +178,5 @@ export const AIEntryLayout = () => { ) -} +}) +AIEntryLayout.displayName = "AIEntryLayout" diff --git a/locales/ai/en.json b/locales/ai/en.json index fc243a68e..d69e22a16 100644 --- a/locales/ai/en.json +++ b/locales/ai/en.json @@ -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", diff --git a/locales/ai/ja.json b/locales/ai/ja.json index 58145d895..82932db04 100644 --- a/locales/ai/ja.json +++ b/locales/ai/ja.json @@ -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使用パターンとインサイトの包括的概要", diff --git a/locales/ai/zh-CN.json b/locales/ai/zh-CN.json index 7458eb491..711f7b404 100644 --- a/locales/ai/zh-CN.json +++ b/locales/ai/zh-CN.json @@ -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": "令牌使用情况",