refactor(ai-task): update task session (#4624)
* fix(ai-chat): update session handling to mark chats as seen and improve unread message detection * fix(ai-chat): handle deletion of remote chat sessions when clearing cache * fix(ai-task): update task session retrieval and handle test run results - Adjusted session retrieval to match task ID format. - Enhanced error handling for test run mutations and added message fetching after successful test runs. * fix(ai-task): update types
This commit is contained in:
@@ -1,9 +1,15 @@
|
||||
import type { AIChatMessage, AIChatSession, ListSessionsQuery } from "@follow-app/client-sdk"
|
||||
import type { UIMessagePart } from "ai"
|
||||
|
||||
import { followApi } from "../../lib/api-client"
|
||||
import { queryClient } from "../../lib/query-client"
|
||||
import { AIPersistService } from "../ai-chat/services"
|
||||
import type { BizUIMessage, BizUIMetadata } from "../ai-chat/store/types"
|
||||
import type {
|
||||
BizUIDataTypes,
|
||||
BizUIMessage,
|
||||
BizUIMetadata,
|
||||
BizUITools,
|
||||
} from "../ai-chat/store/types"
|
||||
import { aiChatSessionKeys } from "./query"
|
||||
import { aiChatSessionStoreActions } from "./store"
|
||||
|
||||
@@ -98,11 +104,6 @@ class AIChatSessionServiceStatic {
|
||||
})
|
||||
await AIPersistService.upsertMessages(session.chatId, normalized)
|
||||
|
||||
await followApi.aiChatSessions.markSeen({
|
||||
chatId: session.chatId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
await this.loadSessionsFromDb()
|
||||
aiChatSessionStoreActions.setLastSyncedAt(new Date())
|
||||
|
||||
@@ -178,9 +179,7 @@ class AIChatSessionServiceStatic {
|
||||
return {
|
||||
id: msg.id,
|
||||
role: msg.role satisfies BizUIMessage["role"],
|
||||
// Remove this comment once @follow-app/client-sdk updated
|
||||
// @ts-expect-error TODO fix message part types
|
||||
parts: msg.messageParts,
|
||||
parts: msg.messageParts as UIMessagePart<BizUIDataTypes, BizUITools>[],
|
||||
metadata,
|
||||
createdAt: new Date(msg.createdAt),
|
||||
}
|
||||
|
||||
+34
-17
@@ -21,6 +21,7 @@ import { AIChatSessionService } from "~/modules/ai-chat-session"
|
||||
import {
|
||||
useAIChatSessionListQuery,
|
||||
useDeleteAIChatSessionMutation,
|
||||
useMarkChatSessionSeenMutation,
|
||||
} from "~/modules/ai-chat-session/query"
|
||||
import { AITaskModal, useCanCreateNewAITask } from "~/modules/ai-task"
|
||||
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
|
||||
@@ -40,14 +41,18 @@ interface SessionItemProps {
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
// Helper to determine if a session has unread messages
|
||||
const isUnreadTaskSession = (session: AIChatSession): boolean => {
|
||||
const isTaskSession = (session: AIChatSession): boolean => {
|
||||
if (!session.lastSeenAt || !session.updatedAt) return false
|
||||
if (!session.chatId.startsWith("ai-task")) return false
|
||||
return new Date(session.updatedAt) > new Date(session.lastSeenAt)
|
||||
return true
|
||||
}
|
||||
|
||||
// Helper to determine if a session has unread messages
|
||||
const isUnreadSession = (session: AIChatSession): boolean => {
|
||||
return new Date(session.updatedAt) > new Date(session.lastSeenAt)
|
||||
}
|
||||
const SessionItem = ({ session, onClick, onDelete, isLoading }: SessionItemProps) => {
|
||||
const hasUnreadMessages = isUnreadSession(session)
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
onClick={onClick}
|
||||
@@ -55,6 +60,13 @@ const SessionItem = ({ session, onClick, onDelete, isLoading }: SessionItemProps
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 justify-between">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
{hasUnreadMessages && (
|
||||
<span
|
||||
className="absolute -left-0.5 block size-2 shrink-0 rounded-full bg-accent"
|
||||
aria-label="Unread"
|
||||
role="status"
|
||||
/>
|
||||
)}
|
||||
<p className="mb-0.5 truncate font-medium">{session.title || "Untitled Chat"}</p>
|
||||
</div>
|
||||
<div className="relative flex min-w-0 items-center">
|
||||
@@ -100,14 +112,10 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor
|
||||
const { t } = useTranslation("ai")
|
||||
const [loadingChatId, setLoadingChatId] = useState<string | null>(null)
|
||||
const showSettings = useSettingModal()
|
||||
|
||||
// Only keep unread sessions for display
|
||||
const unreadSessions = useMemo(
|
||||
() => (sessions || []).filter((s) => isUnreadTaskSession(s)),
|
||||
[sessions],
|
||||
)
|
||||
|
||||
const hasUnreadSessions = unreadSessions.length > 0
|
||||
const markChatSessionSeenMutation = useMarkChatSessionSeenMutation()
|
||||
// Only keep task sessions for display
|
||||
const taskSessions = useMemo(() => (sessions || []).filter((s) => isTaskSession(s)), [sessions])
|
||||
const hasTaskSessions = taskSessions.length > 0
|
||||
|
||||
const { present } = useModalStack()
|
||||
const canCreateNewTask = useCanCreateNewAITask()
|
||||
@@ -128,7 +136,10 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor
|
||||
|
||||
const handleSessionSelect = useCallback(
|
||||
async (session: AIChatSession) => {
|
||||
if (session.chatId === currentChatId) return
|
||||
if (session.chatId === currentChatId) {
|
||||
console.warn("Session already active, no action taken")
|
||||
return
|
||||
}
|
||||
try {
|
||||
await AIChatSessionService.fetchAndPersistMessages(session)
|
||||
} catch (e) {
|
||||
@@ -139,8 +150,14 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor
|
||||
chatActions.setTimelineSummaryManualOverride(true)
|
||||
}
|
||||
chatActions.switchToChat(session.chatId)
|
||||
if (isUnreadSession(session)) {
|
||||
markChatSessionSeenMutation.mutate({
|
||||
chatId: session.chatId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
},
|
||||
[chatActions, currentChatId, shouldDisableTimelineSummary],
|
||||
[chatActions, currentChatId, markChatSessionSeenMutation, shouldDisableTimelineSummary],
|
||||
)
|
||||
|
||||
const handleDeleteSession = useCallback(
|
||||
@@ -194,7 +211,7 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor
|
||||
const defaultTrigger = (
|
||||
<ActionButton tooltip="Task Reports" className="relative">
|
||||
<i className="i-mgc-calendar-time-add-cute-re size-5 text-text-secondary" />
|
||||
{hasUnreadSessions && (
|
||||
{hasTaskSessions && (
|
||||
<span
|
||||
className="absolute right-1 top-1 block size-2 rounded-full bg-accent shadow-[0_0_0_2px_var(--color-bg-default)] dark:shadow-[0_0_0_2px_var(--color-bg-default)]"
|
||||
aria-label="Unread task reports"
|
||||
@@ -212,7 +229,7 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor
|
||||
) : (
|
||||
<DropdownMenuTrigger className="relative">
|
||||
{triggerElement || defaultTrigger}
|
||||
{hasUnreadSessions && triggerElement && (
|
||||
{hasTaskSessions && triggerElement && (
|
||||
<span
|
||||
className="absolute right-1 top-1 block size-2 rounded-full bg-accent shadow-[0_0_0_2px_var(--color-bg-default)] dark:shadow-[0_0_0_2px_var(--color-bg-default)]"
|
||||
aria-label="Unread task reports"
|
||||
@@ -222,8 +239,8 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor
|
||||
)}
|
||||
|
||||
<DropdownMenuContent align="end" className="w-80">
|
||||
{unreadSessions.length > 0 ? (
|
||||
unreadSessions.map((session) => (
|
||||
{taskSessions.length > 0 ? (
|
||||
taskSessions.map((session) => (
|
||||
<SessionItem
|
||||
key={session.chatId}
|
||||
session={session}
|
||||
|
||||
@@ -443,6 +443,11 @@ class AIPersistServiceStatic {
|
||||
|
||||
// Clear deleted sessions from cache
|
||||
chatIdsToDelete.forEach((chatId) => this.clearSessionCache(chatId))
|
||||
for (const chatId of chatIdsToDelete) {
|
||||
await followClient.api.aiChatSessions.delete({ chatId }).catch((error) => {
|
||||
console.error("Failed to delete remote chat sessions:", error)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { toast } from "sonner"
|
||||
|
||||
import { setAIPanelVisibility } from "~/atoms/settings/ai"
|
||||
import { useDialog, useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { followApi } from "~/lib/api-client"
|
||||
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"
|
||||
@@ -122,7 +123,7 @@ export const TaskItem = memo(({ task }: { task: AITask }) => {
|
||||
const statusColorClass = getStatusColor(status)
|
||||
|
||||
const taskSession = useMemo(
|
||||
() => sessions?.find((s) => s.chatId === task.id),
|
||||
() => sessions?.find((s) => s.chatId.startsWith(`ai-task-${task.id}`)),
|
||||
[sessions, task.id],
|
||||
)
|
||||
|
||||
@@ -175,10 +176,23 @@ export const TaskItem = memo(({ task }: { task: AITask }) => {
|
||||
onClick: async () => {
|
||||
const loadingId = toast.loading(t("tasks.toast.test_start"))
|
||||
try {
|
||||
await testRunMutation.mutateAsync({ id: task.id })
|
||||
const testRunResult = await testRunMutation.mutateAsync({ id: task.id })
|
||||
if (testRunResult.data.error) {
|
||||
throw new Error(testRunResult.data.error)
|
||||
}
|
||||
toast.success(t("tasks.toast.test_success"), {
|
||||
id: loadingId,
|
||||
})
|
||||
// @ts-ignore -- Remove once SDK types are updated
|
||||
const { sessionId } = testRunResult.data
|
||||
if (sessionId) {
|
||||
const session = (
|
||||
await followApi.aiChatSessions.get({
|
||||
chatId: sessionId,
|
||||
})
|
||||
).data
|
||||
await AIChatSessionService.fetchAndPersistMessages(session)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to run test:", error)
|
||||
toast.error(t("tasks.toast.test_failed"), {
|
||||
|
||||
Reference in New Issue
Block a user