mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-24 09:03:11 +00:00
177 lines
7.5 KiB
TypeScript
177 lines
7.5 KiB
TypeScript
'use client'
|
|
|
|
import { useChat } from '@ai-sdk/react'
|
|
import { DefaultChatTransport, type AbstractChat, type ChatStatus, type UIMessage } from 'ai'
|
|
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useEffect,
|
|
useMemo,
|
|
useRef,
|
|
useState,
|
|
type ReactNode,
|
|
} from 'react'
|
|
|
|
import { useIsMobileMeasured } from '@/hooks/use-mobile'
|
|
import type { CampaignRole } from '@/lib/campaignRoles'
|
|
import {
|
|
readSollinhaChatSession,
|
|
writeSollinhaChatSession,
|
|
type SollinhaChatSessionOpenOrigin,
|
|
} from '@/lib/sollinhaChatSession'
|
|
|
|
type AISidebarContextValue = {
|
|
/** The chat is showing — single source of truth across panel (desktop) and drawer (mobile). */
|
|
open: boolean
|
|
isMobile: boolean
|
|
/** The first matchMedia measurement has landed (false during the hydration frame). */
|
|
measured: boolean
|
|
/** Authenticated campaign role — drives the opening-chip curation (B191). */
|
|
role: CampaignRole
|
|
messages: UIMessage[]
|
|
status: ChatStatus
|
|
sendMessage: AbstractChat<UIMessage>['sendMessage']
|
|
/** Opens/closes the chat. The desktop Panel and the mobile Drawer react to `open`. */
|
|
setOpen: (open: boolean) => void
|
|
/** Toggles the chat. */
|
|
toggle: () => void
|
|
}
|
|
|
|
const AISidebarContext = createContext<AISidebarContextValue | null>(null)
|
|
|
|
export const CampaignAISidebarProvider = ({
|
|
role,
|
|
children,
|
|
}: {
|
|
role: CampaignRole
|
|
children: ReactNode
|
|
}) => {
|
|
const [open, setOpen] = useState(false)
|
|
const { isMobile, measured } = useIsMobileMeasured()
|
|
|
|
const chat = useChat({
|
|
id: 'campaign-sollinha',
|
|
transport: useMemo(() => new DefaultChatTransport({ api: '/campanha/api/ai-chat' }), []),
|
|
})
|
|
const { messages, setMessages, status } = chat
|
|
|
|
// B188: restore the conversation and the open state from the tab's
|
|
// `sessionStorage` after mount — never during SSR, where restored messages
|
|
// would diverge from the server-rendered chat on the hydration frame.
|
|
// `sessionRestored` gates the persist effect so the mount commit (empty
|
|
// pre-restore values) cannot overwrite a stored session.
|
|
//
|
|
// OPS22: the decision needs the REAL viewport, so the restore waits for the
|
|
// first `measured` commit (where `isMobile` is already correct). A legacy
|
|
// settle-originated `open: true` (the pre-B203 desktop panel reconcile,
|
|
// B167) is layout truth, not user intent — restoring it on a mobile viewport made
|
|
// the drawer open "by itself" whenever a desktop tab visited a mobile page
|
|
// in the same session (the e2e login at desktop width + mobile agenda
|
|
// reproduced it deterministically). Only a user-originated open (FAB /
|
|
// header button / drawer swipe) restores on mobile.
|
|
const [sessionRestored, setSessionRestored] = useState(false)
|
|
const sessionReadRef = useRef(false)
|
|
const restoredOpenByRef = useRef<SollinhaChatSessionOpenOrigin>('settle')
|
|
// B199: the snapshot of the last settle-complete messages — the ONLY
|
|
// content an `open` write made mid-stream may persist (writing live
|
|
// messages would freeze a half-received turn in the session).
|
|
const settledMessagesRef = useRef<UIMessage[]>([])
|
|
// B199: the `open` value of the last write by either persist effect — lets
|
|
// the mid-stream effect skip status transitions that leave `open` untouched.
|
|
const lastWrittenOpenRef = useRef(open)
|
|
useEffect(() => {
|
|
if (sessionReadRef.current || !measured) return
|
|
sessionReadRef.current = true
|
|
const session = readSollinhaChatSession(role)
|
|
if (session) {
|
|
setMessages(session.messages)
|
|
// B199: the mid-stream `open` write must never clobber a restored
|
|
// conversation with an empty snapshot — seed it from the restore itself.
|
|
settledMessagesRef.current = session.messages
|
|
const openBy = session.openBy ?? 'settle'
|
|
restoredOpenByRef.current = openBy
|
|
if (session.open && (openBy === 'user' || !isMobile)) setOpen(true)
|
|
}
|
|
setSessionRestored(true)
|
|
}, [setMessages, measured, isMobile, role])
|
|
|
|
// OPS22: every user surface (FAB, header button, drawer swipe) opens/closes
|
|
// the chat through the context `setOpen`/`toggle` — those mark the intent.
|
|
// Only the restore calls the raw state setter instead, so a restored open
|
|
// never counts as a user action.
|
|
const userToggledOpenRef = useRef(false)
|
|
const requestOpen = useCallback(
|
|
(next: boolean) => {
|
|
userToggledOpenRef.current = true
|
|
setOpen(next)
|
|
},
|
|
[setOpen],
|
|
)
|
|
|
|
// B188: persist the conversation only once the chat has settled — writing
|
|
// during streaming would freeze a half-received message in the session
|
|
// (a reload mid-stream loses only that in-flight turn). Empty state is still
|
|
// written: closing an empty chat must overwrite a stored `open: true`,
|
|
// otherwise a reload would reopen a drawer the user just closed. The
|
|
// persisted `openBy` tells the next page whether the open was the user's
|
|
// (restore it anywhere) or the legacy desktop settle's (desktop-only, OPS22).
|
|
const openByForWrite = (): SollinhaChatSessionOpenOrigin =>
|
|
userToggledOpenRef.current || restoredOpenByRef.current === 'user' ? 'user' : 'settle'
|
|
useEffect(() => {
|
|
if (!sessionRestored || status !== 'ready') return
|
|
settledMessagesRef.current = messages
|
|
lastWrittenOpenRef.current = open
|
|
writeSollinhaChatSession(messages, open, role, openByForWrite())
|
|
}, [sessionRestored, status, messages, open, role])
|
|
|
|
// B199: persist `open` without waiting for the settle — closing the drawer
|
|
// mid-stream must reach the storage immediately, or a reload would restore
|
|
// the stale `open: true` and resurrect the drawer. Messages stay at the last
|
|
// settle-complete snapshot until the next settle (in the abort path the
|
|
// snapshot IS the terminal content — the documented B188 cut). Skipping
|
|
// `ready` avoids a duplicate write of the settle effect above, and the
|
|
// `lastWrittenOpenRef` guard skips plain status transitions that leave
|
|
// `open` untouched. Deliberately no `messages` dep: never persist a live
|
|
// stream, only the open flag over the snapshot.
|
|
useEffect(() => {
|
|
if (!sessionRestored || status === 'ready' || lastWrittenOpenRef.current === open) return
|
|
lastWrittenOpenRef.current = open
|
|
writeSollinhaChatSession(settledMessagesRef.current, open, role, openByForWrite())
|
|
}, [sessionRestored, status, open, role])
|
|
|
|
// The chat has two surfaces keyed by viewport — the desktop panel and the
|
|
// mobile drawer — and both derive from the SAME `open` flag. Crossing the
|
|
// breakpoint therefore needs no migration of its own: the surface that renders
|
|
// just follows `open && viewport`. B203: a fresh session starts closed on
|
|
// every viewport — `open` begins false and only leaves it via a session
|
|
// restore (see above) or a user action (`requestOpen`/`toggle`). A fresh
|
|
// mobile visit keeps `open` false (no spontaneous chat). When a session was
|
|
// restored, the restored `open` wins instead — a chat closed before the
|
|
// reload must not be forced back open (B188).
|
|
const toggle = useCallback(() => {
|
|
userToggledOpenRef.current = true
|
|
setOpen(!open)
|
|
}, [open, setOpen])
|
|
|
|
const value = useMemo(
|
|
() => ({
|
|
open,
|
|
isMobile,
|
|
measured,
|
|
role,
|
|
messages,
|
|
status,
|
|
sendMessage: chat.sendMessage,
|
|
setOpen: requestOpen,
|
|
toggle,
|
|
}),
|
|
[open, isMobile, measured, role, messages, status, chat.sendMessage, requestOpen, toggle],
|
|
)
|
|
|
|
return <AISidebarContext.Provider value={value}>{children}</AISidebarContext.Provider>
|
|
}
|
|
|
|
export const useAISidebar = (): AISidebarContextValue | null => {
|
|
return useContext(AISidebarContext)
|
|
}
|