@adminide-stack/yantra-mobile 12.0.41 → 12.0.42-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/components/AppsMenu/AppsMenu.js +2 -2
- package/lib/components/AppsMenu/AppsMenu.js.map +1 -1
- package/lib/components/GatewayToolbarButtonMobile.js +3 -4
- package/lib/components/GatewayToolbarButtonMobile.js.map +1 -1
- package/lib/components/KeyboardComposerDock.js +27 -0
- package/lib/components/KeyboardComposerDock.js.map +1 -0
- package/lib/components/NavigationHeader/ChatHistoryToggleMobile.js +6 -0
- package/lib/components/NavigationHeader/ChatHistoryToggleMobile.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderMoreMenu.js +67 -0
- package/lib/components/NavigationHeader/HeaderMoreMenu.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderSettingsMenu.js +132 -0
- package/lib/components/NavigationHeader/HeaderSettingsMenu.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderSheet.js +130 -0
- package/lib/components/NavigationHeader/HeaderSheet.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderSkillsButton.js +120 -0
- package/lib/components/NavigationHeader/HeaderSkillsButton.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderTasksButton.js +157 -0
- package/lib/components/NavigationHeader/HeaderTasksButton.js.map +1 -0
- package/lib/components/NavigationHeader/HeaderToolbarButton.js +68 -0
- package/lib/components/NavigationHeader/HeaderToolbarButton.js.map +1 -0
- package/lib/components/NavigationHeader/NavigationHeader.js +35 -63
- package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
- package/lib/compute.js +1 -1
- package/lib/compute.js.map +1 -1
- package/lib/contexts/GatewayContext.js +8 -1
- package/lib/contexts/GatewayContext.js.map +1 -1
- package/lib/features/chat/temporaryChatStore.js +19 -0
- package/lib/features/chat/temporaryChatStore.js.map +1 -0
- package/lib/hooks/useAgentSessionState.js +5 -0
- package/lib/hooks/useAgentSessionState.js.map +1 -0
- package/lib/hooks/useCdecliChannel.js +84 -2
- package/lib/hooks/useCdecliChannel.js.map +1 -1
- package/lib/hooks/useChatApi.js +22 -1
- package/lib/hooks/useChatApi.js.map +1 -1
- package/lib/hooks/useChatStream.js +81 -11
- package/lib/hooks/useChatStream.js.map +1 -1
- package/lib/hooks/useKeyboardBottomOffset.js +22 -0
- package/lib/hooks/useKeyboardBottomOffset.js.map +1 -0
- package/lib/hooks/useMarketplaceTemplateGroups.js +1 -1
- package/lib/hooks/useMarketplaceTemplateGroups.js.map +1 -1
- package/lib/routes.json +1 -1
- package/lib/screens/Chat/index.js +56 -100
- package/lib/screens/Chat/index.js.map +1 -1
- package/lib/screens/ChatHistory/index.js +12 -1
- package/lib/screens/ChatHistory/index.js.map +1 -1
- package/lib/screens/Home/HomeScreen.js +58 -58
- package/lib/screens/Home/HomeScreen.js.map +1 -1
- package/lib/screens/Home/components/BuildTemplatesSection.js +12 -33
- package/lib/screens/Home/components/BuildTemplatesSection.js.map +1 -1
- package/lib/screens/Home/components/ChatHistoryLanding.js +16 -3
- package/lib/screens/Home/components/ChatHistoryLanding.js.map +1 -1
- package/lib/screens/Home/components/HomeSuggestions.js +7 -2
- package/lib/screens/Home/components/HomeSuggestions.js.map +1 -1
- package/package.json +5 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatApi.js","sources":["../../src/hooks/useChatApi.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { AiAgentMessageRole, PostTypeEnum, RoomType, SortEnum } from 'common';\nimport {\n GetChannelsByUserWithLastMessageDocument,\n useAddChannelMutation,\n useGetChannelsByUserWithLastMessageQuery,\n useMessagesQuery,\n useSendMessagesMutation,\n} from 'common/graphql';\nimport type {\n IAccountCreateChatSessionInput,\n IAccountSaveChatMessagesInput as IAccountSaveChatMessagesInputBase,\n} from 'common/server';\nimport { useCallback, useMemo } from 'react';\nimport { v4 as uuidv4 } from 'uuid';\n\nconst MESSAGES_PAGE_LIMIT = 100;\n\n/** Same variables as web Inbox / AIAgent: list AI assistant channels for the current user. */\nexport const AI_ASSISTANT_CHANNELS_QUERY_VARS = {\n criteria: { type: RoomType.Aiassistant },\n limit: 100,\n skip: 0,\n sort: { key: 'updatedAt', value: SortEnum.Desc },\n};\n\nexport const HISTORY_PAGE_SIZE = 20;\n\n/**\n * Variables for the channels-based chat history list (`ChatHistoryLanding`).\n *\n * IMPORTANT: pass the user's org `slug` (e.g. `tarun-upadhyay-qraw`) so the\n * `channelsByUser` resolver's `$in: [criteria.orgName, orgId]` includes\n * channels stored under the slug. When `criteria.orgName` is omitted, the\n * `$in` collapses to just `[orgId]` and channels saved with the slug as\n * `orgName` (the mobile create path) never match. That's the cause of the\n * silently-empty history screen.\n *\n * Kept as a builder (not a constant) because the slug varies per user and\n * because Apollo treats different `variables` as different cached entries —\n * if the create mutation refetches a no-orgName variant, the orgName-variant\n * the screen watches stays stale.\n */\nexport function getHistoryChannelsQueryVariables(orgName?: string | null, options?: { skip?: number; limit?: number }) {\n const trimmedOrg = typeof orgName === 'string' && orgName.trim().length > 0 ? orgName.trim() : undefined;\n return {\n criteria: {\n type: RoomType.Aiassistant,\n ...(trimmedOrg ? { orgName: trimmedOrg } : {}),\n },\n limit: options?.limit ?? HISTORY_PAGE_SIZE,\n skip: options?.skip ?? 0,\n sort: { key: 'updatedAt' as const, value: SortEnum.Desc },\n };\n}\n\n/** @deprecated Use {@link getHistoryChannelsQueryVariables} so `orgName` is included. */\nexport const HISTORY_QUERY_BASE = getHistoryChannelsQueryVariables();\n\n/**\n * Variables for the chat-history feed on the mobile `ChatHistory` screen.\n *\n * First page uses `HISTORY_PAGE_SIZE` (20) posts; \"Load older\" paginates by post\n * `skip` in increments of 20. Rows are still one per channel (collapsed from posts).\n *\n * This query intentionally hits `messages` (not `channelsByUser`) — the same\n * pattern the web sidebar uses (`useNewChatPageHistorySessions`). Reasons:\n * 1. `channelsByUser` is server-side gated by an injected `orgName` /\n * `members` filter that can mismatch when channels were stored with an\n * org slug while the resolver injects the org id. The `messages`\n * resolver filters Post directly by `editedBy: accountId`, so the\n * user's own AI-assistant posts always show up.\n * 2. The user-authored post IS the conversation's natural title — no need\n * to walk `lastMessage.propsConfiguration.contents.parent` to recover\n * the original prompt.\n *\n * - `type: AIASSISTANT` scopes to AI chat (not direct/service rooms).\n * - `props.role: 'user'` selects only the user's turns. The assistant reply\n * is ignored here; it would override the title with the agent's words.\n * - `editedBy: accountUserId` scopes to the current user's own posts,\n * independent of channel membership / org name.\n */\nexport function getChatHistoryMessagesQueryVariables(\n accountUserId: string,\n options?: { skip?: number; limit?: number },\n) {\n return {\n limit: options?.limit ?? HISTORY_PAGE_SIZE,\n skip: options?.skip ?? 0,\n sort: { key: 'updatedAt' as const, value: SortEnum.Desc },\n type: PostTypeEnum.Aiassistant,\n editedBy: accountUserId,\n props: { role: 'user' },\n };\n}\n\nexport type ChatHistoryMode = 'chat' | 'deep-search';\n\nexport interface ChatHistorySession {\n /** Channel id — used to navigate to the Chat screen. */\n channelId: string;\n /** User's most recent prompt in this channel (used as the row title). */\n title: string;\n /** Second line: latest post `message` field (same as Manus subtitle). */\n preview: string;\n /** Conversation mode (chat / deep-search), inferred from channel display name / title. */\n mode: ChatHistoryMode;\n /** Most-recent activity timestamp (sort key + bucket key for Today/Yesterday/…). */\n updatedAt: Date;\n createdAt: Date;\n /**\n * True when no concrete prompt was recoverable (no parent, no user turn, no\n * meaningful channel.title). UI renders the title in a quieter style.\n */\n isPlaceholder: boolean;\n}\n\n/**\n * Collapse a list of user-authored AI assistant posts (newest first) into one\n * row per channel. First post per `channel.id` wins the title, which — because\n * the query is sorted by `updatedAt DESC` — is the user's latest prompt in\n * that channel. Posts whose `channel.id` is missing (unexpected, but possible\n * if the resolver omits the relation) are skipped.\n */\nexport function chatHistorySessionsFromMessages(\n data: { messages?: { data?: unknown[] | null } | null } | null | undefined,\n): ChatHistorySession[] {\n const rows = data?.messages?.data;\n if (!rows?.length) return [];\n\n const seen = new Set<string>();\n const sessions: ChatHistorySession[] = [];\n\n for (const post of rows as any[]) {\n const channelId = post?.channel?.id ? String(post.channel.id) : '';\n if (channelId && !seen.has(channelId)) {\n seen.add(channelId);\n\n const rawTitle = String(post?.message ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n const updatedAt = post?.updatedAt ? new Date(post.updatedAt) : new Date();\n const createdAt = post?.createdAt ? new Date(post.createdAt) : updatedAt;\n const title = rawTitle || 'New chat';\n\n sessions.push({\n channelId,\n title,\n preview: '',\n mode: 'chat',\n updatedAt,\n createdAt,\n isPlaceholder: !rawTitle,\n });\n }\n }\n\n return sessions;\n}\n\n/**\n * Mobile parity hook for the web sidebar's `useNewChatPageHistorySessions`.\n *\n * Returns one row per channel where the user has authored at least one AI assistant\n * post, with the title taken from that user's latest prompt. Skipped when\n * `accountUserId` isn't known yet (we don't want to fire a query without it).\n */\nexport function useChatHistorySessionsFromMessages(\n accountUserId: string | null | undefined,\n options?: { skip?: boolean },\n) {\n const skip = options?.skip || !accountUserId;\n const { data, loading, error, refetch } = useMessagesQuery({\n variables: accountUserId ? getChatHistoryMessagesQueryVariables(accountUserId) : undefined,\n skip,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n context: { cacheKey: 'new-chat-history-messages' },\n });\n\n const sessions = useMemo(() => chatHistorySessionsFromMessages(data), [data]);\n const sourcePostCount = data?.messages?.data?.length ?? 0;\n\n return { sessions, loading, error, refetch, sourcePostCount };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Channels-based chat history (parent + lastMessage) */\n/* -------------------------------------------------------------------------- */\n\ninterface ChannelLastMessageLike {\n message?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n props?: { role?: string | null } | null;\n propsConfiguration?: {\n contents?: {\n role?: string | null;\n parent?: {\n message?: string | null;\n props?: { role?: string | null } | null;\n } | null;\n } | null;\n content?: { role?: string | null } | null;\n } | null;\n}\n\ninterface ChannelLike {\n id?: string | null;\n type?: string | null;\n displayName?: string | null;\n title?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n lastMessage?: ChannelLastMessageLike | null;\n}\n\nfunction getLastMessageRole(lastMessage: ChannelLastMessageLike | null | undefined): string {\n return String(\n lastMessage?.propsConfiguration?.contents?.role ??\n lastMessage?.propsConfiguration?.content?.role ??\n lastMessage?.props?.role ??\n '',\n ).toUpperCase();\n}\n\nfunction getParentUserPrompt(lastMessage: ChannelLastMessageLike | null | undefined): string {\n const parent = lastMessage?.propsConfiguration?.contents?.parent;\n if (!parent) return '';\n return String(parent?.message ?? '').trim();\n}\n\nfunction detectMode(channel: ChannelLike): ChatHistoryMode {\n const display = String(channel?.displayName ?? '').toLowerCase();\n const title = String(channel?.title ?? '').toLowerCase();\n if (display.startsWith('deep-search') || title.startsWith('deep search') || title.startsWith('deep-search')) {\n return 'deep-search';\n }\n return 'chat';\n}\n\n/**\n * Drop the internal slug we use as `channel.title` for server-side mode detection\n * (`chat-channel-<uuid>` / `deep-search-<uuid>`) so it doesn't leak into the row\n * label. The server sometimes also reformats this slug into `displayName` as\n * title-cased text with spaces (e.g. `\"Deep Search b64be4f7 9fe6 …\"`) — those\n * are equally machine-generated and must NOT be shown to the user.\n *\n * Pattern accepts:\n * • `deep-search-<uuid>` / `chat-channel-<uuid>` (raw, mode signal)\n * • `Deep Search <uuid>` / `Chat Channel <uuid>` (display-cased, server-reformatted)\n * • UUID may use hyphens, spaces, or be partially truncated as long as the\n * trailing chunk is hex.\n */\nfunction cleanChannelTitle(rawTitle: string | null | undefined): string {\n const t = String(rawTitle ?? '').trim();\n if (!t) return '';\n if (/^(chat[\\s-]channel|deep[\\s-]search)[\\s-][0-9a-f][0-9a-f\\s-]{7,}\\.?$/i.test(t)) return '';\n // Creation defaults carry no meaning either (parity with the browser sidebar).\n if (/^(new chat|workflow|deep search)$/i.test(t)) return '';\n return t;\n}\n\n/** `[Active connectors: …]` routing prefix on persisted gateway user posts. */\nconst ACTIVE_CONNECTORS_PREFIX_RE = /^\\s*\\[Active connectors:[^\\]]*\\]\\s*/i;\n\nfunction cleanMessageText(raw: string): string {\n return raw.replace(ACTIVE_CONNECTORS_PREFIX_RE, '').trim();\n}\n\n/**\n * Map one channel into a session row (Manus-style two-line list):\n *\n * **Title (line 1):** `lastMessage.propsConfiguration.contents.parent.message`\n * when present (the user turn the thread is anchored on). Otherwise fall back\n * to the last post body if that post is still a user message, then a\n * machine-slug-stripped channel title, then a machine-slug-stripped\n * `displayName`, then `\"Thinking…\"`. Machine slugs (`deep-search-<uuid>`,\n * `chat-channel-<uuid>`, and their server-reformatted display variants)\n * are filtered via `cleanChannelTitle`, so they never reach the row.\n *\n * **Preview (line 2):** `lastMessage.message` as returned by the API (trimmed,\n * whitespace collapsed). Agent errors that start with `⚠` stay visible in the\n * subtitle, matching the reference UI.\n *\n * If preview text equals the title after trim, the second line is omitted\n * (single-line channel, no duplicate).\n */\nexport function buildSessionFromChannel(channel: ChannelLike): ChatHistorySession | null {\n const channelId = String(channel?.id ?? '');\n if (!channelId) return null;\n\n const lastMessage = channel?.lastMessage ?? null;\n const lastMessageRole = getLastMessageRole(lastMessage);\n const parentUserPrompt = getParentUserPrompt(lastMessage);\n const parentTrimmed = cleanMessageText(parentUserPrompt);\n\n const userTurn =\n lastMessageRole === 'USER' && lastMessage?.message ? cleanMessageText(String(lastMessage.message)) : '';\n const cleanedChannelTitle = cleanChannelTitle(channel?.title);\n /**\n * Apply the same machine-slug cleaner to `displayName`. The server\n * sometimes derives displayName from the title (`\"deep-search-<uuid>\"`\n * → `\"Deep Search <uuid>\"`), so without this the slug bypasses\n * `cleanedChannelTitle` and lands directly in the row label.\n */\n const cleanedDisplayName = cleanChannelTitle(channel?.displayName);\n\n // A real channel title (brain headline / first-message name set at creation)\n // wins over raw message text — parity with the browser sidebar.\n let resolvedTitle = cleanedChannelTitle || parentTrimmed || userTurn || cleanedDisplayName;\n if (!resolvedTitle) {\n // Message-less channels with a friendly default show it instead of the\n // in-progress placeholder.\n const rawDefault = String(channel?.title ?? '').trim();\n if (rawDefault && !/^(chat[\\s-]channel|deep[\\s-]search)[\\s-][0-9a-f][0-9a-f\\s-]{7,}\\.?$/i.test(rawDefault)) {\n resolvedTitle = rawDefault;\n }\n }\n const isPlaceholder = !resolvedTitle;\n /**\n * When every signal fails — typical when a send just landed and the\n * server hasn't yet persisted the message that would populate\n * `propsConfiguration.contents.parent.message` — show `\"Thinking…\"`\n * instead of an empty label or the raw machine slug. The row's mode\n * tile still signals chat vs deep-search, so the user has enough\n * context to recognize the entry without leaking implementation noise.\n */\n if (isPlaceholder) resolvedTitle = 'Thinking…';\n\n const rawPreview = String(lastMessage?.message ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n let preview = rawPreview;\n if (preview && preview === parentTrimmed) preview = '';\n\n const sortAt = (() => {\n const candidates = [channel?.updatedAt, lastMessage?.updatedAt, lastMessage?.createdAt, channel?.createdAt];\n for (const candidate of candidates) {\n if (candidate) {\n const t = new Date(candidate).getTime();\n if (Number.isFinite(t) && t > 0) return t;\n }\n }\n return Date.now();\n })();\n\n const createdAtRaw = channel?.createdAt ? new Date(channel.createdAt).getTime() : sortAt;\n\n return {\n channelId,\n title: resolvedTitle,\n preview,\n mode: detectMode(channel),\n updatedAt: new Date(sortAt),\n createdAt: new Date(Number.isFinite(createdAtRaw) ? createdAtRaw : sortAt),\n isPlaceholder,\n };\n}\n\n/** Collapse a `channelsByUser` response into session rows for the history list. */\nexport function chatHistorySessionsFromChannels(\n data: { channelsByUser?: (ChannelLike | null)[] | null } | null | undefined,\n): ChatHistorySession[] {\n const channels = (data?.channelsByUser ?? []) as (ChannelLike | null)[];\n return channels\n .filter((c): c is ChannelLike => Boolean(c?.id) && (!c?.type || c.type === RoomType.Aiassistant))\n .map((c) => buildSessionFromChannel(c))\n .filter((row): row is ChatHistorySession => row !== null)\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n}\n\n/**\n * Chat history feed driven by `channelsByUser`. Each row: parent prompt as title,\n * `lastMessage.message` as subtitle (Manus-style), when the API provides them.\n *\n * Caller MUST pass `orgName` (the org slug). Without it, the resolver only\n * matches channels whose `orgName` field equals the user's `orgId`, which is\n * never the case for mobile-created channels (those store the slug). The hook\n * suspends the query (`skip: true`) until `orgName` is known, so we never\n * fire a guaranteed-empty request.\n *\n * Pagination is by channel count (one channel = one row in this query),\n * unlike the messages-based path which paginates by raw post rows.\n */\nexport function useChatHistorySessionsFromChannels(orgName: string | null | undefined, options?: { skip?: boolean }) {\n const skip = options?.skip || !orgName;\n const variables = useMemo(() => getHistoryChannelsQueryVariables(orgName), [orgName]);\n\n const { data, loading, error, refetch } = useGetChannelsByUserWithLastMessageQuery({\n variables,\n skip,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n context: { cacheKey: 'chat-history-channels-list' },\n });\n\n const sessions = useMemo(() => chatHistorySessionsFromChannels(data), [data]);\n const sourceChannelCount = data?.channelsByUser?.length ?? 0;\n /**\n * `sessionsLoaded` means \"we have data we can show\", regardless of whether a\n * background revalidation is still in flight. Same contract as `messagesLoaded`\n * in `useChatMessages` — lets the screen show the cached list (or empty state)\n * immediately on revisit instead of flashing a loader for the network round-trip.\n */\n const sessionsLoaded = data !== undefined;\n\n return { sessions, loading, sessionsLoaded, error, refetch, sourceChannelCount };\n}\n\nfunction stripModelCostHeader(content: string): string {\n const normalized = content.replace(/\\r\\n/g, '\\n');\n return normalized.replace(\n /^\\s*(?:[^\\w\\n]+\\s*)?[a-z0-9][a-z0-9._-]*\\s*\\(\\s*\\$[\\d.]+\\s*\\/\\s*MTok\\s+in\\s*\\)\\s*\\n+/i,\n '',\n );\n}\n\nfunction sanitizeAssistantContentByRole(role: unknown, content: string): string {\n return role === 'assistant' ? stripModelCostHeader(content) : content;\n}\n\nfunction omitContent<T extends Record<string, any>>(value: T | null | undefined): Omit<T, 'content'> {\n const clone = { ...(value ?? {}) } as Record<string, any>;\n delete clone.content;\n return clone as Omit<T, 'content'>;\n}\n\nexport interface ChatSessionUI {\n id: string;\n title: string;\n createdAt: Date;\n updatedAt: Date;\n messageCount?: number;\n}\n\nexport function useChatSessions(options?: { includeArchived?: boolean; skip?: boolean }) {\n const { data, loading, error, refetch } = useGetChannelsByUserWithLastMessageQuery({\n variables: AI_ASSISTANT_CHANNELS_QUERY_VARS,\n skip: options?.skip,\n fetchPolicy: 'cache-and-network',\n });\n\n const sessions: ChatSessionUI[] = useMemo(() => {\n const channels = data?.channelsByUser ?? [];\n return channels\n .filter((c): c is NonNullable<typeof c> => Boolean(c?.id))\n .map((channel) => ({\n id: channel.id,\n title: channel.title || channel.displayName || 'New Chat',\n createdAt: new Date(channel.createdAt ?? Date.now()),\n updatedAt: new Date(channel.updatedAt ?? Date.now()),\n messageCount: undefined,\n }));\n }, [data]);\n\n return { sessions, loading, error, refetch };\n}\n\nexport interface ChatMessageUI {\n id: string;\n sessionId: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n attachments?: Array<{ id: string; name: string; type: string; mimeType?: string; size?: number; url?: string }>;\n tokenCount?: number;\n model?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface MinimalFile {\n id?: string | null;\n name?: string | null;\n mimeType?: string | null;\n size?: number | null;\n url?: string | null;\n}\n\ninterface MinimalPost {\n id?: string | null;\n message?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n channel?: { id?: string | null } | null;\n files?: { data?: MinimalFile[] | null } | null;\n props?: { role?: string | null; tokenCount?: number | null; model?: string | null } | null;\n propsConfiguration?: {\n contents?: { role?: string | null } | null;\n content?: { role?: string | null } | null;\n } | null;\n}\n\nfunction mapPostToChatMessageUI(post: MinimalPost, fallbackChannelId: string): ChatMessageUI {\n const props = (post.props ?? {}) as Record<string, any>;\n const contents = post.propsConfiguration?.contents ?? {};\n const roleRaw = props.role ?? contents.role ?? post.propsConfiguration?.content?.role;\n let role: ChatMessageUI['role'] = 'assistant';\n if (roleRaw === 'user' || roleRaw === AiAgentMessageRole.User) role = 'user';\n else if (roleRaw === 'assistant' || roleRaw === AiAgentMessageRole.Assistant) role = 'assistant';\n else if (roleRaw === 'system') role = 'system';\n\n const rawContent = post?.message ?? '';\n const content = sanitizeAssistantContentByRole(role, rawContent);\n\n return {\n id: post?.id ?? uuidv4(),\n sessionId: post?.channel?.id ?? fallbackChannelId,\n role,\n content,\n attachments: (post?.files?.data ?? []).map((file) => ({\n id: file.id ?? uuidv4(),\n name: file.name ?? 'file',\n type: typeof file.mimeType === 'string' && file.mimeType.startsWith('image/') ? 'screenshot' : 'file',\n mimeType: file.mimeType ?? undefined,\n size: file.size ?? undefined,\n url: file.url ?? undefined,\n })),\n tokenCount: props.tokenCount ?? undefined,\n model: props.model ?? undefined,\n createdAt: post?.createdAt ? new Date(post.createdAt) : new Date(),\n updatedAt: post?.updatedAt ? new Date(post.updatedAt) : new Date(),\n };\n}\n\nexport function useChatMessages(sessionId: string | null, options?: { skip?: boolean }) {\n const { data, loading, error, refetch } = useMessagesQuery({\n variables: {\n channelId: sessionId ?? undefined,\n parentId: null,\n limit: MESSAGES_PAGE_LIMIT,\n skip: 0,\n },\n skip: !sessionId || options?.skip,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n /**\n * Cache key is per-channel so switching sessions doesn't read another channel's response.\n * Keeping this as a constant ('messages-list') used to cause cross-session bleed in the\n * custom Apollo link before reaching the normalized cache.\n */\n context: { cacheKey: sessionId ? `messages-list:${sessionId}` : 'messages-list' },\n });\n\n /**\n * `messagesLoaded` means \"we have data we can show\", regardless of whether a\n * background revalidation is in flight. With `cache-and-network`, Apollo\n * fills `data` from cache synchronously while `loading` is still true for\n * the network round-trip — gating hydration on `!loading` made every chat\n * revisit show a loader for the network latency even though the messages\n * were already cached. The chat stream re-hydrates whenever `data` changes,\n * so the fresh network response still swaps in silently afterward.\n */\n const messagesLoaded = data !== undefined;\n\n const messages: ChatMessageUI[] = useMemo(() => {\n if (!sessionId) return [];\n const rows = data?.messages?.data ?? [];\n return rows\n .map((post) => mapPostToChatMessageUI(post as MinimalPost, sessionId))\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n }, [data, sessionId]);\n\n return { messages, loading, messagesLoaded, error, refetch };\n}\n\nexport type IAccountSaveChatMessagesInput = IAccountSaveChatMessagesInputBase & {\n mode?: 'plan' | 'build';\n createdBy?: string;\n};\n\n/** Backend/gateway may have already inserted the post (E11000 duplicate `_id`). */\nfunction isDuplicatePostError(error: unknown): boolean {\n const parts: string[] = [];\n if (error && typeof error === 'object' && 'graphQLErrors' in error) {\n const gqlErrors = (error as { graphQLErrors?: Array<{ message?: string }> }).graphQLErrors ?? [];\n parts.push(...gqlErrors.map((e) => e?.message ?? ''));\n }\n if (error instanceof Error) {\n parts.push(error.message);\n } else if (error != null) {\n parts.push(String(error));\n }\n const msg = parts.join(' ');\n return /E11000|duplicate key/i.test(msg);\n}\n\nexport function useChatMutations() {\n const [addChannelMutation, { loading: createChannelLoading }] = useAddChannelMutation();\n const [sendMessagesMutation, { loading: sendMessagesLoading }] = useSendMessagesMutation();\n\n const createChannel = useCallback(\n async (input?: IAccountCreateChatSessionInput): Promise<ChatSessionUI> => {\n const {\n orgName: orgNameArg,\n projectId: projectIdArg,\n ...inputForSettings\n } = (input ?? {}) as IAccountCreateChatSessionInput & {\n orgName?: string | null;\n projectId?: string | null;\n };\n const orgName =\n typeof orgNameArg === 'string' && orgNameArg.trim().length > 0 ? orgNameArg.trim() : undefined;\n const projectId =\n typeof projectIdArg === 'string' && projectIdArg.trim().length > 0 ? projectIdArg.trim() : undefined;\n\n const settings = {\n title: input?.title ?? 'New Chat',\n description: input?.systemPrompt ?? null,\n isShared: false,\n sharedSlug: null,\n isArchived: false,\n isPinned: false,\n model: input?.model ?? null,\n systemPrompt: input?.systemPrompt ?? null,\n ...inputForSettings,\n };\n\n const { data } = await addChannelMutation({\n variables: {\n channelId: input?.id ?? null,\n name: input?.title ?? 'New Chat',\n description: input?.systemPrompt ?? null,\n type: RoomType.Aiassistant,\n settings,\n ...(orgName ? { orgName } : {}),\n ...(projectId ? { projectId } : {}),\n },\n /**\n * Refetch every cache slot the rest of the app is watching for\n * channel lists. Apollo keys cached results by `variables`, so each\n * shape we emit here must match a watched query exactly.\n *\n * Variants:\n * 1. Legacy limit:100 list (web parity, no `criteria.orgName`).\n * 2. Mobile history-screen variant WITH `criteria.orgName` so the\n * resolver's `$in: [slug, orgId]` matches mobile-created channels.\n * 3. Same variant WITHOUT orgName, in case the screen mounted before\n * org settings resolved.\n */\n refetchQueries: [\n { query: GetChannelsByUserWithLastMessageDocument, variables: AI_ASSISTANT_CHANNELS_QUERY_VARS },\n ...(orgName\n ? [\n {\n query: GetChannelsByUserWithLastMessageDocument,\n variables: getHistoryChannelsQueryVariables(orgName),\n },\n ]\n : []),\n { query: GetChannelsByUserWithLastMessageDocument, variables: HISTORY_QUERY_BASE },\n ],\n awaitRefetchQueries: true,\n });\n\n if (!data?.createChannel?.id) {\n throw new Error('Failed to create channel');\n }\n\n const channel = data.createChannel;\n const title = channel.title ?? input?.title ?? 'New Chat';\n const now = new Date();\n\n return {\n id: channel.id,\n title,\n createdAt: now,\n updatedAt: now,\n };\n },\n [addChannelMutation],\n );\n\n const saveMessages = useCallback(\n async (\n input: IAccountSaveChatMessagesInput,\n ): Promise<{\n userMessage: ChatMessageUI;\n assistantMessage: ChatMessageUI;\n session: ChatSessionUI;\n }> => {\n const sanitizedAssistantContent = stripModelCostHeader(input.assistantMessage.content ?? '');\n const assistantMessageWithoutContent = omitContent((input.assistantMessage as any) ?? {});\n\n let userPost: MinimalPost | null | undefined;\n try {\n const userResult = await sendMessagesMutation({\n variables: {\n channelId: input.sessionId,\n type: RoomType.Aiassistant,\n content: input.userMessage.content ?? '',\n ...(input.createdBy ? { createdBy: input.createdBy } : {}),\n extraProps: {\n type: PostTypeEnum.Aiassistant,\n role: 'user',\n attachments: input.userMessage.attachments ?? [],\n isActive: true,\n status: 'complete',\n ...(input.userMessage as any),\n ...(input.mode ? { mode: input.mode } : {}),\n },\n } as any,\n });\n userPost = userResult.data?.sendMessage as MinimalPost | undefined;\n } catch (err) {\n if (!isDuplicatePostError(err)) {\n throw err;\n }\n console.warn('[saveMessages] user post already persisted (skipping duplicate insert)');\n }\n\n /**\n * Keep the prompting user post id in metadata. `sendMessage.postId` is the id of\n * the post being created, so reusing the user post id for the assistant reply would\n * collide and leave only the user message persisted.\n */\n const userPostId = userPost?.id ?? null;\n\n let assistantPost: MinimalPost | null | undefined;\n try {\n const assistantResult = await sendMessagesMutation({\n variables: {\n channelId: input.sessionId,\n type: RoomType.Aiassistant,\n content: sanitizedAssistantContent,\n extraProps: {\n type: PostTypeEnum.Aiassistant,\n role: 'assistant',\n attachments: input.assistantMessage.attachments ?? [],\n tokenCount: input.assistantMessage.tokenCount,\n latencyMs: input.assistantMessage.latencyMs,\n model: input.assistantMessage.model,\n finishReason: (input.assistantMessage as any).finishReason ?? null,\n isActive: true,\n status: 'complete',\n ...assistantMessageWithoutContent,\n ...(userPostId ? { parentId: userPostId } : {}),\n ...(input.mode ? { mode: input.mode } : {}),\n },\n } as any,\n });\n assistantPost = assistantResult.data?.sendMessage as MinimalPost | undefined;\n } catch (err) {\n if (!isDuplicatePostError(err)) {\n throw err;\n }\n console.warn('[saveMessages] assistant post already persisted (skipping duplicate insert)');\n }\n\n if (!userPost && !assistantPost) {\n throw new Error('Failed to send messages');\n }\n\n const now = new Date();\n const fallbackUser: ChatMessageUI = {\n id: userPostId ?? uuidv4(),\n sessionId: input.sessionId,\n role: 'user',\n content: input.userMessage.content ?? '',\n createdAt: now,\n updatedAt: now,\n };\n const fallbackAssistant: ChatMessageUI = {\n id: uuidv4(),\n sessionId: input.sessionId,\n role: 'assistant',\n content: sanitizedAssistantContent,\n createdAt: now,\n updatedAt: now,\n tokenCount: input.assistantMessage.tokenCount,\n model: input.assistantMessage.model,\n };\n return {\n userMessage: userPost ? mapPostToChatMessageUI(userPost, input.sessionId) : fallbackUser,\n assistantMessage: assistantPost\n ? mapPostToChatMessageUI(assistantPost, input.sessionId)\n : fallbackAssistant,\n session: {\n id: input.sessionId,\n title: 'Chat',\n createdAt: now,\n updatedAt: now,\n },\n };\n },\n [sendMessagesMutation],\n );\n\n return {\n createChannel,\n createSession: createChannel,\n saveMessages,\n loading: { create: createChannelLoading, saveMessages: sendMessagesLoading },\n };\n}\n"],"names":["uuidv4","_a","_b","_c","_d","_e"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,mBAAsB,GAAA,GAAA;AAGrB,MAAM,gCAAmC,GAAA;AAAA,EAC9C,QAAU,EAAA;AAAA,IACR,MAAM,QAAS,CAAA;AAAA,GACjB;AAAA,EACA,KAAO,EAAA,GAAA;AAAA,EACP,IAAM,EAAA,CAAA;AAAA,EACN,IAAM,EAAA;AAAA,IACJ,GAAK,EAAA,WAAA;AAAA,IACL,OAAO,QAAS,CAAA;AAAA;AAEpB;AACO,MAAM,iBAAoB,GAAA;AAiBjB,SAAA,gCAAA,CAAiC,SAAyB,OAGvE,EAAA;AAxCH,EAAA,IAAA,EAAA,EAAA,EAAA;AAyCE,EAAM,MAAA,UAAA,GAAa,OAAO,OAAA,KAAY,QAAY,IAAA,OAAA,CAAQ,IAAK,EAAA,CAAE,MAAS,GAAA,CAAA,GAAI,OAAQ,CAAA,IAAA,EAAS,GAAA,MAAA;AAC/F,EAAO,OAAA;AAAA,IACL,QAAU,EAAA,cAAA,CAAA;AAAA,MACR,MAAM,QAAS,CAAA;AAAA,KAAA,EACX,UAAa,GAAA;AAAA,MACf,OAAS,EAAA;AAAA,QACP,EAAC,CAAA;AAAA,IAEP,KAAA,EAAA,CAAO,EAAS,GAAA,OAAA,IAAA,IAAA,GAAA,MAAA,GAAA,OAAA,CAAA,KAAA,KAAT,IAAkB,GAAA,EAAA,GAAA,iBAAA;AAAA,IACzB,IAAA,EAAA,CAAM,EAAS,GAAA,OAAA,IAAA,IAAA,GAAA,MAAA,GAAA,OAAA,CAAA,IAAA,KAAT,IAAiB,GAAA,EAAA,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B,CAAA,UAAA;AAAA,MACnC,KAAA,EAAO,MAAM,gBAAiB,CAAA;AAAA,KAChC;AACA,IAAO,OAAA;AAAA,MACL,aAAa,QAAW,GAAA,sBAAA,CAAuB,QAAU,EAAA,KAAA,CAAM,SAAS,CAAI,GAAA,YAAA;AAAA,MAC5E,kBAAkB,aAAgB,GAAA,sBAAA,CAAuB,aAAe,EAAA,KAAA,CAAM,SAAS,CAAI,GAAA,iBAAA;AAAA,MAC3F,OAAS,EAAA;AAAA,QACP,IAAI,KAAM,CAAA,SAAA;AAAA,QACV,KAAO,EAAA,MAAA;AAAA,QACP,SAAW,EAAA,GAAA;AAAA,QACX,SAAW,EAAA;AAAA;AACb,KACF;AAAA,GACF,EAAG,CAAC,oBAAoB,CAAC,CAAA;AACzB,EAAO,OAAA;AAAA,IACL,aAAA;AAAA,IACA,aAAe,EAAA,aAAA;AAAA,IACf,YAAA;AAAA,IACA,OAAS,EAAA;AAAA,MACP,MAAQ,EAAA,oBAAA;AAAA,MACR,YAAc,EAAA;AAAA;AAChB,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"useChatApi.js","sources":["../../src/hooks/useChatApi.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { AiAgentMessageRole, PostTypeEnum, RoomType, SortEnum } from 'common';\nimport {\n GetChannelsByUserWithLastMessageDocument,\n useAddChannelMutation,\n useGetChannelsByUserWithLastMessageQuery,\n useMessagesQuery,\n useSendMessagesMutation,\n} from 'common/graphql';\nimport type {\n IAccountCreateChatSessionInput,\n IAccountSaveChatMessagesInput as IAccountSaveChatMessagesInputBase,\n} from 'common/server';\nimport { useCallback, useMemo } from 'react';\nimport { v4 as uuidv4 } from 'uuid';\n\nconst MESSAGES_PAGE_LIMIT = 100;\n\n/** Same variables as web Inbox / AIAgent: list AI assistant channels for the current user. */\nexport const AI_ASSISTANT_CHANNELS_QUERY_VARS = {\n criteria: { type: RoomType.Aiassistant },\n limit: 100,\n skip: 0,\n sort: { key: 'updatedAt', value: SortEnum.Desc },\n};\n\nexport const HISTORY_PAGE_SIZE = 20;\n\n/**\n * Variables for the channels-based chat history list (`ChatHistoryLanding`).\n *\n * IMPORTANT: pass the user's org `slug` (e.g. `tarun-upadhyay-qraw`) so the\n * `channelsByUser` resolver's `$in: [criteria.orgName, orgId]` includes\n * channels stored under the slug. When `criteria.orgName` is omitted, the\n * `$in` collapses to just `[orgId]` and channels saved with the slug as\n * `orgName` (the mobile create path) never match. That's the cause of the\n * silently-empty history screen.\n *\n * Kept as a builder (not a constant) because the slug varies per user and\n * because Apollo treats different `variables` as different cached entries —\n * if the create mutation refetches a no-orgName variant, the orgName-variant\n * the screen watches stays stale.\n */\nexport function getHistoryChannelsQueryVariables(orgName?: string | null, options?: { skip?: number; limit?: number }) {\n const trimmedOrg = typeof orgName === 'string' && orgName.trim().length > 0 ? orgName.trim() : undefined;\n return {\n criteria: {\n type: RoomType.Aiassistant,\n ...(trimmedOrg ? { orgName: trimmedOrg } : {}),\n },\n limit: options?.limit ?? HISTORY_PAGE_SIZE,\n skip: options?.skip ?? 0,\n sort: { key: 'updatedAt' as const, value: SortEnum.Desc },\n };\n}\n\n/** @deprecated Use {@link getHistoryChannelsQueryVariables} so `orgName` is included. */\nexport const HISTORY_QUERY_BASE = getHistoryChannelsQueryVariables();\n\n/**\n * Variables for the chat-history feed on the mobile `ChatHistory` screen.\n *\n * First page uses `HISTORY_PAGE_SIZE` (20) posts; \"Load older\" paginates by post\n * `skip` in increments of 20. Rows are still one per channel (collapsed from posts).\n *\n * This query intentionally hits `messages` (not `channelsByUser`) — the same\n * pattern the web sidebar uses (`useNewChatPageHistorySessions`). Reasons:\n * 1. `channelsByUser` is server-side gated by an injected `orgName` /\n * `members` filter that can mismatch when channels were stored with an\n * org slug while the resolver injects the org id. The `messages`\n * resolver filters Post directly by `editedBy: accountId`, so the\n * user's own AI-assistant posts always show up.\n * 2. The user-authored post IS the conversation's natural title — no need\n * to walk `lastMessage.propsConfiguration.contents.parent` to recover\n * the original prompt.\n *\n * - `type: AIASSISTANT` scopes to AI chat (not direct/service rooms).\n * - `props.role: 'user'` selects only the user's turns. The assistant reply\n * is ignored here; it would override the title with the agent's words.\n * - `editedBy: accountUserId` scopes to the current user's own posts,\n * independent of channel membership / org name.\n */\nexport function getChatHistoryMessagesQueryVariables(\n accountUserId: string,\n options?: { skip?: number; limit?: number },\n) {\n return {\n limit: options?.limit ?? HISTORY_PAGE_SIZE,\n skip: options?.skip ?? 0,\n sort: { key: 'updatedAt' as const, value: SortEnum.Desc },\n type: PostTypeEnum.Aiassistant,\n editedBy: accountUserId,\n props: { role: 'user' },\n };\n}\n\nexport type ChatHistoryMode = 'chat' | 'deep-search' | 'build';\n\nexport interface ChatHistorySession {\n /** Channel id — used to navigate to the Chat screen. */\n channelId: string;\n /** User's most recent prompt in this channel (used as the row title). */\n title: string;\n /** Second line: latest post `message` field (same as Manus subtitle). */\n preview: string;\n /** Conversation mode (chat / deep-search / build), inferred from channel title or last message. */\n mode: ChatHistoryMode;\n /** Most-recent activity timestamp (sort key + bucket key for Today/Yesterday/…). */\n updatedAt: Date;\n createdAt: Date;\n /**\n * True when no concrete prompt was recoverable (no parent, no user turn, no\n * meaningful channel.title). UI renders the title in a quieter style.\n */\n isPlaceholder: boolean;\n}\n\n/**\n * Collapse a list of user-authored AI assistant posts (newest first) into one\n * row per channel. First post per `channel.id` wins the title, which — because\n * the query is sorted by `updatedAt DESC` — is the user's latest prompt in\n * that channel. Posts whose `channel.id` is missing (unexpected, but possible\n * if the resolver omits the relation) are skipped.\n */\nexport function chatHistorySessionsFromMessages(\n data: { messages?: { data?: unknown[] | null } | null } | null | undefined,\n): ChatHistorySession[] {\n const rows = data?.messages?.data;\n if (!rows?.length) return [];\n\n const seen = new Set<string>();\n const sessions: ChatHistorySession[] = [];\n\n for (const post of rows as any[]) {\n const channelId = post?.channel?.id ? String(post.channel.id) : '';\n if (channelId && !seen.has(channelId)) {\n seen.add(channelId);\n\n const rawTitle = String(post?.message ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n const updatedAt = post?.updatedAt ? new Date(post.updatedAt) : new Date();\n const createdAt = post?.createdAt ? new Date(post.createdAt) : updatedAt;\n const title = rawTitle || 'New chat';\n\n sessions.push({\n channelId,\n title,\n preview: '',\n mode: 'chat',\n updatedAt,\n createdAt,\n isPlaceholder: !rawTitle,\n });\n }\n }\n\n return sessions;\n}\n\n/**\n * Mobile parity hook for the web sidebar's `useNewChatPageHistorySessions`.\n *\n * Returns one row per channel where the user has authored at least one AI assistant\n * post, with the title taken from that user's latest prompt. Skipped when\n * `accountUserId` isn't known yet (we don't want to fire a query without it).\n */\nexport function useChatHistorySessionsFromMessages(\n accountUserId: string | null | undefined,\n options?: { skip?: boolean },\n) {\n const skip = options?.skip || !accountUserId;\n const { data, loading, error, refetch } = useMessagesQuery({\n variables: accountUserId ? getChatHistoryMessagesQueryVariables(accountUserId) : undefined,\n skip,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n context: { cacheKey: 'new-chat-history-messages' },\n });\n\n const sessions = useMemo(() => chatHistorySessionsFromMessages(data), [data]);\n const sourcePostCount = data?.messages?.data?.length ?? 0;\n\n return { sessions, loading, error, refetch, sourcePostCount };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Channels-based chat history (parent + lastMessage) */\n/* -------------------------------------------------------------------------- */\n\ninterface ChannelLastMessageLike {\n message?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n props?: { role?: string | null; mode?: string | null } | null;\n propsConfiguration?: {\n contents?: {\n role?: string | null;\n mode?: string | null;\n template?: string | null;\n parent?: {\n message?: string | null;\n props?: { role?: string | null } | null;\n } | null;\n fragment?: {\n title?: string | null;\n sandboxUrl?: string | null;\n sandboxId?: string | null;\n } | null;\n } | null;\n content?: { role?: string | null; mode?: string | null } | null;\n } | null;\n}\n\ninterface ChannelLike {\n id?: string | null;\n type?: string | null;\n displayName?: string | null;\n title?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n lastMessage?: ChannelLastMessageLike | null;\n}\n\nfunction getLastMessageRole(lastMessage: ChannelLastMessageLike | null | undefined): string {\n return String(\n lastMessage?.propsConfiguration?.contents?.role ??\n lastMessage?.propsConfiguration?.content?.role ??\n lastMessage?.props?.role ??\n '',\n ).toUpperCase();\n}\n\nfunction getParentUserPrompt(lastMessage: ChannelLastMessageLike | null | undefined): string {\n const parent = lastMessage?.propsConfiguration?.contents?.parent;\n if (!parent) return '';\n return String(parent?.message ?? '').trim();\n}\n\nfunction isBuildLastMessage(lastMessage: ChannelLastMessageLike | null | undefined): boolean {\n if (!lastMessage) return false;\n const contents = lastMessage.propsConfiguration?.contents;\n const mode = String(\n contents?.mode ?? lastMessage.propsConfiguration?.content?.mode ?? lastMessage?.props?.mode ?? '',\n ).toLowerCase();\n if (mode === 'build' || mode === 'workflow') return true;\n const fragment = contents?.fragment;\n if (fragment?.sandboxUrl || fragment?.sandboxId) return true;\n if (String(contents?.template ?? '').trim()) return true;\n return false;\n}\n\nfunction detectMode(channel: ChannelLike): ChatHistoryMode {\n if (isBuildLastMessage(channel?.lastMessage)) {\n return 'build';\n }\n const display = String(channel?.displayName ?? '').toLowerCase();\n const title = String(channel?.title ?? '').toLowerCase();\n if (display.startsWith('build-channel') || title.startsWith('build-channel') || title.startsWith('build channel')) {\n return 'build';\n }\n const parent = getParentUserPrompt(channel?.lastMessage).toLowerCase();\n if (/^build\\s*me\\s*:/.test(parent)) {\n return 'build';\n }\n if (display.startsWith('deep-search') || title.startsWith('deep search') || title.startsWith('deep-search')) {\n return 'deep-search';\n }\n return 'chat';\n}\n\n/**\n * Drop the internal slug we use as `channel.title` for server-side mode detection\n * (`chat-channel-<uuid>` / `deep-search-<uuid>`) so it doesn't leak into the row\n * label. The server sometimes also reformats this slug into `displayName` as\n * title-cased text with spaces (e.g. `\"Deep Search b64be4f7 9fe6 …\"`) — those\n * are equally machine-generated and must NOT be shown to the user.\n *\n * Pattern accepts:\n * • `deep-search-<uuid>` / `chat-channel-<uuid>` (raw, mode signal)\n * • `Deep Search <uuid>` / `Chat Channel <uuid>` (display-cased, server-reformatted)\n * • UUID may use hyphens, spaces, or be partially truncated as long as the\n * trailing chunk is hex.\n */\nfunction cleanChannelTitle(rawTitle: string | null | undefined): string {\n const t = String(rawTitle ?? '').trim();\n if (!t) return '';\n if (/^(chat[\\s-]channel|deep[\\s-]search|build[\\s-]channel)[\\s-][0-9a-f][0-9a-f\\s-]{7,}\\.?$/i.test(t)) return '';\n // Creation defaults carry no meaning either (parity with the browser sidebar).\n if (/^(new chat|workflow|deep search)$/i.test(t)) return '';\n return t;\n}\n\n/** `[Active connectors: …]` routing prefix on persisted gateway user posts. */\nconst ACTIVE_CONNECTORS_PREFIX_RE = /^\\s*\\[Active connectors:[^\\]]*\\]\\s*/i;\n\nfunction cleanMessageText(raw: string): string {\n return raw.replace(ACTIVE_CONNECTORS_PREFIX_RE, '').trim();\n}\n\n/**\n * Map one channel into a session row (Manus-style two-line list):\n *\n * **Title (line 1):** `lastMessage.propsConfiguration.contents.parent.message`\n * when present (the user turn the thread is anchored on). Otherwise fall back\n * to the last post body if that post is still a user message, then a\n * machine-slug-stripped channel title, then a machine-slug-stripped\n * `displayName`, then `\"Thinking…\"`. Machine slugs (`deep-search-<uuid>`,\n * `chat-channel-<uuid>`, and their server-reformatted display variants)\n * are filtered via `cleanChannelTitle`, so they never reach the row.\n *\n * **Preview (line 2):** `lastMessage.message` as returned by the API (trimmed,\n * whitespace collapsed). Agent errors that start with `⚠` stay visible in the\n * subtitle, matching the reference UI.\n *\n * If preview text equals the title after trim, the second line is omitted\n * (single-line channel, no duplicate).\n */\nexport function buildSessionFromChannel(channel: ChannelLike): ChatHistorySession | null {\n const channelId = String(channel?.id ?? '');\n if (!channelId) return null;\n\n const lastMessage = channel?.lastMessage ?? null;\n const lastMessageRole = getLastMessageRole(lastMessage);\n const parentUserPrompt = getParentUserPrompt(lastMessage);\n const parentTrimmed = cleanMessageText(parentUserPrompt);\n\n const userTurn =\n lastMessageRole === 'USER' && lastMessage?.message ? cleanMessageText(String(lastMessage.message)) : '';\n const cleanedChannelTitle = cleanChannelTitle(channel?.title);\n /**\n * Apply the same machine-slug cleaner to `displayName`. The server\n * sometimes derives displayName from the title (`\"deep-search-<uuid>\"`\n * → `\"Deep Search <uuid>\"`), so without this the slug bypasses\n * `cleanedChannelTitle` and lands directly in the row label.\n */\n const cleanedDisplayName = cleanChannelTitle(channel?.displayName);\n\n // A real channel title (brain headline / first-message name set at creation)\n // wins over raw message text — parity with the browser sidebar.\n let resolvedTitle = cleanedChannelTitle || parentTrimmed || userTurn || cleanedDisplayName;\n if (!resolvedTitle) {\n // Message-less channels with a friendly default show it instead of the\n // in-progress placeholder.\n const rawDefault = String(channel?.title ?? '').trim();\n if (rawDefault && !/^(chat[\\s-]channel|deep[\\s-]search)[\\s-][0-9a-f][0-9a-f\\s-]{7,}\\.?$/i.test(rawDefault)) {\n resolvedTitle = rawDefault;\n }\n }\n const isPlaceholder = !resolvedTitle;\n /**\n * When every signal fails — typical when a send just landed and the\n * server hasn't yet persisted the message that would populate\n * `propsConfiguration.contents.parent.message` — show `\"Thinking…\"`\n * instead of an empty label or the raw machine slug. The row's mode\n * tile still signals chat vs deep-search, so the user has enough\n * context to recognize the entry without leaking implementation noise.\n */\n if (isPlaceholder) resolvedTitle = 'Thinking…';\n\n const rawPreview = String(lastMessage?.message ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n let preview = rawPreview;\n if (preview && preview === parentTrimmed) preview = '';\n\n const sortAt = (() => {\n const candidates = [channel?.updatedAt, lastMessage?.updatedAt, lastMessage?.createdAt, channel?.createdAt];\n for (const candidate of candidates) {\n if (candidate) {\n const t = new Date(candidate).getTime();\n if (Number.isFinite(t) && t > 0) return t;\n }\n }\n return Date.now();\n })();\n\n const createdAtRaw = channel?.createdAt ? new Date(channel.createdAt).getTime() : sortAt;\n\n return {\n channelId,\n title: resolvedTitle,\n preview,\n mode: detectMode(channel),\n updatedAt: new Date(sortAt),\n createdAt: new Date(Number.isFinite(createdAtRaw) ? createdAtRaw : sortAt),\n isPlaceholder,\n };\n}\n\n/** Collapse a `channelsByUser` response into session rows for the history list. */\nexport function chatHistorySessionsFromChannels(\n data: { channelsByUser?: (ChannelLike | null)[] | null } | null | undefined,\n): ChatHistorySession[] {\n const channels = (data?.channelsByUser ?? []) as (ChannelLike | null)[];\n return channels\n .filter((c): c is ChannelLike => Boolean(c?.id) && (!c?.type || c.type === RoomType.Aiassistant))\n .map((c) => buildSessionFromChannel(c))\n .filter((row): row is ChatHistorySession => row !== null)\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());\n}\n\n/**\n * Chat history feed driven by `channelsByUser`. Each row: parent prompt as title,\n * `lastMessage.message` as subtitle (Manus-style), when the API provides them.\n *\n * Caller MUST pass `orgName` (the org slug). Without it, the resolver only\n * matches channels whose `orgName` field equals the user's `orgId`, which is\n * never the case for mobile-created channels (those store the slug). The hook\n * suspends the query (`skip: true`) until `orgName` is known, so we never\n * fire a guaranteed-empty request.\n *\n * Pagination is by channel count (one channel = one row in this query),\n * unlike the messages-based path which paginates by raw post rows.\n */\nexport function useChatHistorySessionsFromChannels(orgName: string | null | undefined, options?: { skip?: boolean }) {\n const skip = options?.skip || !orgName;\n const variables = useMemo(() => getHistoryChannelsQueryVariables(orgName), [orgName]);\n\n const { data, loading, error, refetch } = useGetChannelsByUserWithLastMessageQuery({\n variables,\n skip,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n context: { cacheKey: 'chat-history-channels-list' },\n });\n\n const sessions = useMemo(() => chatHistorySessionsFromChannels(data), [data]);\n const sourceChannelCount = data?.channelsByUser?.length ?? 0;\n /**\n * `sessionsLoaded` means \"we have data we can show\", regardless of whether a\n * background revalidation is still in flight. Same contract as `messagesLoaded`\n * in `useChatMessages` — lets the screen show the cached list (or empty state)\n * immediately on revisit instead of flashing a loader for the network round-trip.\n */\n const sessionsLoaded = data !== undefined;\n\n return { sessions, loading, sessionsLoaded, error, refetch, sourceChannelCount };\n}\n\nfunction stripModelCostHeader(content: string): string {\n const normalized = content.replace(/\\r\\n/g, '\\n');\n return normalized.replace(\n /^\\s*(?:[^\\w\\n]+\\s*)?[a-z0-9][a-z0-9._-]*\\s*\\(\\s*\\$[\\d.]+\\s*\\/\\s*MTok\\s+in\\s*\\)\\s*\\n+/i,\n '',\n );\n}\n\nfunction sanitizeAssistantContentByRole(role: unknown, content: string): string {\n return role === 'assistant' ? stripModelCostHeader(content) : content;\n}\n\nfunction omitContent<T extends Record<string, any>>(value: T | null | undefined): Omit<T, 'content'> {\n const clone = { ...(value ?? {}) } as Record<string, any>;\n delete clone.content;\n return clone as Omit<T, 'content'>;\n}\n\nexport interface ChatSessionUI {\n id: string;\n title: string;\n createdAt: Date;\n updatedAt: Date;\n messageCount?: number;\n}\n\nexport function useChatSessions(options?: { includeArchived?: boolean; skip?: boolean }) {\n const { data, loading, error, refetch } = useGetChannelsByUserWithLastMessageQuery({\n variables: AI_ASSISTANT_CHANNELS_QUERY_VARS,\n skip: options?.skip,\n fetchPolicy: 'cache-and-network',\n });\n\n const sessions: ChatSessionUI[] = useMemo(() => {\n const channels = data?.channelsByUser ?? [];\n return channels\n .filter((c): c is NonNullable<typeof c> => Boolean(c?.id))\n .map((channel) => ({\n id: channel.id,\n title: channel.title || channel.displayName || 'New Chat',\n createdAt: new Date(channel.createdAt ?? Date.now()),\n updatedAt: new Date(channel.updatedAt ?? Date.now()),\n messageCount: undefined,\n }));\n }, [data]);\n\n return { sessions, loading, error, refetch };\n}\n\nexport interface ChatMessageUI {\n id: string;\n sessionId: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n attachments?: Array<{ id: string; name: string; type: string; mimeType?: string; size?: number; url?: string }>;\n tokenCount?: number;\n model?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface MinimalFile {\n id?: string | null;\n name?: string | null;\n mimeType?: string | null;\n size?: number | null;\n url?: string | null;\n}\n\ninterface MinimalPost {\n id?: string | null;\n message?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n channel?: { id?: string | null } | null;\n files?: { data?: MinimalFile[] | null } | null;\n props?: { role?: string | null; tokenCount?: number | null; model?: string | null } | null;\n propsConfiguration?: {\n contents?: { role?: string | null } | null;\n content?: { role?: string | null } | null;\n } | null;\n}\n\nfunction mapPostToChatMessageUI(post: MinimalPost, fallbackChannelId: string): ChatMessageUI {\n const props = (post.props ?? {}) as Record<string, any>;\n const contents = post.propsConfiguration?.contents ?? {};\n const roleRaw = props.role ?? contents.role ?? post.propsConfiguration?.content?.role;\n let role: ChatMessageUI['role'] = 'assistant';\n if (roleRaw === 'user' || roleRaw === AiAgentMessageRole.User) role = 'user';\n else if (roleRaw === 'assistant' || roleRaw === AiAgentMessageRole.Assistant) role = 'assistant';\n else if (roleRaw === 'system') role = 'system';\n\n const rawContent = post?.message ?? '';\n const content = sanitizeAssistantContentByRole(role, rawContent);\n\n return {\n id: post?.id ?? uuidv4(),\n sessionId: post?.channel?.id ?? fallbackChannelId,\n role,\n content,\n attachments: (post?.files?.data ?? []).map((file) => ({\n id: file.id ?? uuidv4(),\n name: file.name ?? 'file',\n type: typeof file.mimeType === 'string' && file.mimeType.startsWith('image/') ? 'screenshot' : 'file',\n mimeType: file.mimeType ?? undefined,\n size: file.size ?? undefined,\n url: file.url ?? undefined,\n })),\n tokenCount: props.tokenCount ?? undefined,\n model: props.model ?? undefined,\n createdAt: post?.createdAt ? new Date(post.createdAt) : new Date(),\n updatedAt: post?.updatedAt ? new Date(post.updatedAt) : new Date(),\n };\n}\n\nexport function useChatMessages(sessionId: string | null, options?: { skip?: boolean }) {\n const { data, loading, error, refetch } = useMessagesQuery({\n variables: {\n channelId: sessionId ?? undefined,\n parentId: null,\n limit: MESSAGES_PAGE_LIMIT,\n skip: 0,\n },\n skip: !sessionId || options?.skip,\n fetchPolicy: 'cache-and-network',\n notifyOnNetworkStatusChange: true,\n /**\n * Cache key is per-channel so switching sessions doesn't read another channel's response.\n * Keeping this as a constant ('messages-list') used to cause cross-session bleed in the\n * custom Apollo link before reaching the normalized cache.\n */\n context: { cacheKey: sessionId ? `messages-list:${sessionId}` : 'messages-list' },\n });\n\n /**\n * `messagesLoaded` means \"we have data we can show\", regardless of whether a\n * background revalidation is in flight. With `cache-and-network`, Apollo\n * fills `data` from cache synchronously while `loading` is still true for\n * the network round-trip — gating hydration on `!loading` made every chat\n * revisit show a loader for the network latency even though the messages\n * were already cached. The chat stream re-hydrates whenever `data` changes,\n * so the fresh network response still swaps in silently afterward.\n */\n const messagesLoaded = data !== undefined;\n\n const messages: ChatMessageUI[] = useMemo(() => {\n if (!sessionId) return [];\n const rows = data?.messages?.data ?? [];\n return rows\n .map((post) => mapPostToChatMessageUI(post as MinimalPost, sessionId))\n .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n }, [data, sessionId]);\n\n return { messages, loading, messagesLoaded, error, refetch };\n}\n\nexport type IAccountSaveChatMessagesInput = IAccountSaveChatMessagesInputBase & {\n mode?: 'plan' | 'build';\n createdBy?: string;\n};\n\n/** Backend/gateway may have already inserted the post (E11000 duplicate `_id`). */\nfunction isDuplicatePostError(error: unknown): boolean {\n const parts: string[] = [];\n if (error && typeof error === 'object' && 'graphQLErrors' in error) {\n const gqlErrors = (error as { graphQLErrors?: Array<{ message?: string }> }).graphQLErrors ?? [];\n parts.push(...gqlErrors.map((e) => e?.message ?? ''));\n }\n if (error instanceof Error) {\n parts.push(error.message);\n } else if (error != null) {\n parts.push(String(error));\n }\n const msg = parts.join(' ');\n return /E11000|duplicate key/i.test(msg);\n}\n\nexport function useChatMutations() {\n const [addChannelMutation, { loading: createChannelLoading }] = useAddChannelMutation();\n const [sendMessagesMutation, { loading: sendMessagesLoading }] = useSendMessagesMutation();\n\n const createChannel = useCallback(\n async (input?: IAccountCreateChatSessionInput): Promise<ChatSessionUI> => {\n const {\n orgName: orgNameArg,\n projectId: projectIdArg,\n ...inputForSettings\n } = (input ?? {}) as IAccountCreateChatSessionInput & {\n orgName?: string | null;\n projectId?: string | null;\n };\n const orgName =\n typeof orgNameArg === 'string' && orgNameArg.trim().length > 0 ? orgNameArg.trim() : undefined;\n const projectId =\n typeof projectIdArg === 'string' && projectIdArg.trim().length > 0 ? projectIdArg.trim() : undefined;\n\n const settings = {\n title: input?.title ?? 'New Chat',\n description: input?.systemPrompt ?? null,\n isShared: false,\n sharedSlug: null,\n isArchived: false,\n isPinned: false,\n model: input?.model ?? null,\n systemPrompt: input?.systemPrompt ?? null,\n ...inputForSettings,\n };\n\n const { data } = await addChannelMutation({\n variables: {\n channelId: input?.id ?? null,\n name: input?.title ?? 'New Chat',\n description: input?.systemPrompt ?? null,\n type: RoomType.Aiassistant,\n settings,\n ...(orgName ? { orgName } : {}),\n ...(projectId ? { projectId } : {}),\n },\n /**\n * Refetch every cache slot the rest of the app is watching for\n * channel lists. Apollo keys cached results by `variables`, so each\n * shape we emit here must match a watched query exactly.\n *\n * Variants:\n * 1. Legacy limit:100 list (web parity, no `criteria.orgName`).\n * 2. Mobile history-screen variant WITH `criteria.orgName` so the\n * resolver's `$in: [slug, orgId]` matches mobile-created channels.\n * 3. Same variant WITHOUT orgName, in case the screen mounted before\n * org settings resolved.\n */\n refetchQueries: [\n { query: GetChannelsByUserWithLastMessageDocument, variables: AI_ASSISTANT_CHANNELS_QUERY_VARS },\n ...(orgName\n ? [\n {\n query: GetChannelsByUserWithLastMessageDocument,\n variables: getHistoryChannelsQueryVariables(orgName),\n },\n ]\n : []),\n { query: GetChannelsByUserWithLastMessageDocument, variables: HISTORY_QUERY_BASE },\n ],\n awaitRefetchQueries: true,\n });\n\n if (!data?.createChannel?.id) {\n throw new Error('Failed to create channel');\n }\n\n const channel = data.createChannel;\n const title = channel.title ?? input?.title ?? 'New Chat';\n const now = new Date();\n\n return {\n id: channel.id,\n title,\n createdAt: now,\n updatedAt: now,\n };\n },\n [addChannelMutation],\n );\n\n const saveMessages = useCallback(\n async (\n input: IAccountSaveChatMessagesInput,\n ): Promise<{\n userMessage: ChatMessageUI;\n assistantMessage: ChatMessageUI;\n session: ChatSessionUI;\n }> => {\n const sanitizedAssistantContent = stripModelCostHeader(input.assistantMessage.content ?? '');\n const assistantMessageWithoutContent = omitContent((input.assistantMessage as any) ?? {});\n\n let userPost: MinimalPost | null | undefined;\n try {\n const userResult = await sendMessagesMutation({\n variables: {\n channelId: input.sessionId,\n type: RoomType.Aiassistant,\n content: input.userMessage.content ?? '',\n ...(input.createdBy ? { createdBy: input.createdBy } : {}),\n extraProps: {\n type: PostTypeEnum.Aiassistant,\n role: 'user',\n attachments: input.userMessage.attachments ?? [],\n isActive: true,\n status: 'complete',\n ...(input.userMessage as any),\n ...(input.mode ? { mode: input.mode } : {}),\n },\n } as any,\n });\n userPost = userResult.data?.sendMessage as MinimalPost | undefined;\n } catch (err) {\n if (!isDuplicatePostError(err)) {\n throw err;\n }\n console.warn('[saveMessages] user post already persisted (skipping duplicate insert)');\n }\n\n /**\n * Keep the prompting user post id in metadata. `sendMessage.postId` is the id of\n * the post being created, so reusing the user post id for the assistant reply would\n * collide and leave only the user message persisted.\n */\n const userPostId = userPost?.id ?? null;\n\n let assistantPost: MinimalPost | null | undefined;\n try {\n const assistantResult = await sendMessagesMutation({\n variables: {\n channelId: input.sessionId,\n type: RoomType.Aiassistant,\n content: sanitizedAssistantContent,\n extraProps: {\n type: PostTypeEnum.Aiassistant,\n role: 'assistant',\n attachments: input.assistantMessage.attachments ?? [],\n tokenCount: input.assistantMessage.tokenCount,\n latencyMs: input.assistantMessage.latencyMs,\n model: input.assistantMessage.model,\n finishReason: (input.assistantMessage as any).finishReason ?? null,\n isActive: true,\n status: 'complete',\n ...assistantMessageWithoutContent,\n ...(userPostId ? { parentId: userPostId } : {}),\n ...(input.mode ? { mode: input.mode } : {}),\n },\n } as any,\n });\n assistantPost = assistantResult.data?.sendMessage as MinimalPost | undefined;\n } catch (err) {\n if (!isDuplicatePostError(err)) {\n throw err;\n }\n console.warn('[saveMessages] assistant post already persisted (skipping duplicate insert)');\n }\n\n if (!userPost && !assistantPost) {\n throw new Error('Failed to send messages');\n }\n\n const now = new Date();\n const fallbackUser: ChatMessageUI = {\n id: userPostId ?? uuidv4(),\n sessionId: input.sessionId,\n role: 'user',\n content: input.userMessage.content ?? '',\n createdAt: now,\n updatedAt: now,\n };\n const fallbackAssistant: ChatMessageUI = {\n id: uuidv4(),\n sessionId: input.sessionId,\n role: 'assistant',\n content: sanitizedAssistantContent,\n createdAt: now,\n updatedAt: now,\n tokenCount: input.assistantMessage.tokenCount,\n model: input.assistantMessage.model,\n };\n return {\n userMessage: userPost ? mapPostToChatMessageUI(userPost, input.sessionId) : fallbackUser,\n assistantMessage: assistantPost\n ? mapPostToChatMessageUI(assistantPost, input.sessionId)\n : fallbackAssistant,\n session: {\n id: input.sessionId,\n title: 'Chat',\n createdAt: now,\n updatedAt: now,\n },\n };\n },\n [sendMessagesMutation],\n );\n\n return {\n createChannel,\n createSession: createChannel,\n saveMessages,\n loading: { create: createChannelLoading, saveMessages: sendMessagesLoading },\n };\n}\n"],"names":["uuidv4","_a","_b","_c","_d","_e"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,mBAAsB,GAAA,GAAA;AAGrB,MAAM,gCAAmC,GAAA;AAAA,EAC9C,QAAU,EAAA;AAAA,IACR,MAAM,QAAS,CAAA;AAAA,GACjB;AAAA,EACA,KAAO,EAAA,GAAA;AAAA,EACP,IAAM,EAAA,CAAA;AAAA,EACN,IAAM,EAAA;AAAA,IACJ,GAAK,EAAA,WAAA;AAAA,IACL,OAAO,QAAS,CAAA;AAAA;AAEpB;AACO,MAAM,iBAAoB,GAAA;AAiBjB,SAAA,gCAAA,CAAiC,SAAyB,OAGvE,EAAA;AAxCH,EAAA,IAAA,EAAA,EAAA,EAAA;AAyCE,EAAM,MAAA,UAAA,GAAa,OAAO,OAAA,KAAY,QAAY,IAAA,OAAA,CAAQ,IAAK,EAAA,CAAE,MAAS,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,CAAI,GAAA,iBAAA;AAAA,MAC3F,OAAS,EAAA;AAAA,QACP,IAAI,KAAM,CAAA,SAAA;AAAA,QACV,KAAO,EAAA,MAAA;AAAA,QACP,SAAW,EAAA,GAAA;AAAA,QACX,SAAW,EAAA;AAAA;AACb,KACF;AAAA,GACF,EAAG,CAAC,oBAAoB,CAAC,CAAA;AACzB,EAAO,OAAA;AAAA,IACL,aAAA;AAAA,IACA,aAAe,EAAA,aAAA;AAAA,IACf,YAAA;AAAA,IACA,OAAS,EAAA;AAAA,MACP,MAAQ,EAAA,oBAAA;AAAA,MACR,YAAc,EAAA;AAAA;AAChB,GACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {useState,useRef,useCallback,useMemo,useEffect}from'react';import {useChatMutations,useChatMessages}from'./useChatApi.js';import {useCdecliChannel}from'./useCdecliChannel.js';import {usePrerequisiteIds}from'./usePrerequisiteIds.js';var __defProp = Object.defineProperty;
|
|
1
|
+
import {useState,useRef,useCallback,useMemo,useEffect}from'react';import {useChatMutations,useChatMessages}from'./useChatApi.js';import {useCdecliChannel,isNoActiveSessionError}from'./useCdecliChannel.js';import {usePrerequisiteIds}from'./usePrerequisiteIds.js';var __defProp = Object.defineProperty;
|
|
2
2
|
var __defProps = Object.defineProperties;
|
|
3
3
|
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
4
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
@@ -33,6 +33,12 @@ function useChatStream(sessionId, routing = {
|
|
|
33
33
|
const [isStreaming, setIsStreaming] = useState(false);
|
|
34
34
|
const [error, setError] = useState(null);
|
|
35
35
|
const isSendingRef = useRef(false);
|
|
36
|
+
const pendingSteersRef = useRef([]);
|
|
37
|
+
const sessionLiveRef = useRef(false);
|
|
38
|
+
const flushPendingSteersRef = useRef(async () => {
|
|
39
|
+
});
|
|
40
|
+
const sendMessageRef = useRef(async () => {
|
|
41
|
+
});
|
|
36
42
|
const [cdecliStreamOverrideId, setCdecliStreamOverrideId] = useState(void 0);
|
|
37
43
|
const userMsgForSaveRef = useRef(null);
|
|
38
44
|
const saveSessionIdRef = useRef(null);
|
|
@@ -55,6 +61,7 @@ function useChatStream(sessionId, routing = {
|
|
|
55
61
|
const finalizeCdecliRound = useCallback((assistantContent) => {
|
|
56
62
|
saveSessionIdRef.current = null;
|
|
57
63
|
userMsgForSaveRef.current = null;
|
|
64
|
+
sessionLiveRef.current = false;
|
|
58
65
|
setResponse("");
|
|
59
66
|
setIsLoading(false);
|
|
60
67
|
setIsStreaming(false);
|
|
@@ -69,6 +76,10 @@ function useChatStream(sessionId, routing = {
|
|
|
69
76
|
const cdecliCallbacks = useMemo(() => ({
|
|
70
77
|
onChunk: (text) => {
|
|
71
78
|
setResponse((r) => r + text);
|
|
79
|
+
if (!sessionLiveRef.current) {
|
|
80
|
+
sessionLiveRef.current = true;
|
|
81
|
+
void flushPendingSteersRef.current();
|
|
82
|
+
}
|
|
72
83
|
},
|
|
73
84
|
onComplete: (text) => {
|
|
74
85
|
var _a;
|
|
@@ -77,6 +88,7 @@ function useChatStream(sessionId, routing = {
|
|
|
77
88
|
}
|
|
78
89
|
if (isCdecliAgentFailureOutput(text)) {
|
|
79
90
|
cdecliRoundHandledRef.current = true;
|
|
91
|
+
pendingSteersRef.current = [];
|
|
80
92
|
setError("CDeCLI agent error. Check gateway status and server-side LLM configuration.");
|
|
81
93
|
finalizeCdecliRound(text);
|
|
82
94
|
return;
|
|
@@ -84,8 +96,11 @@ function useChatStream(sessionId, routing = {
|
|
|
84
96
|
cdecliRoundHandledRef.current = true;
|
|
85
97
|
const sid = saveSessionIdRef.current;
|
|
86
98
|
const um = userMsgForSaveRef.current;
|
|
99
|
+
const leftover = pendingSteersRef.current;
|
|
100
|
+
pendingSteersRef.current = [];
|
|
87
101
|
saveSessionIdRef.current = null;
|
|
88
102
|
userMsgForSaveRef.current = null;
|
|
103
|
+
sessionLiveRef.current = false;
|
|
89
104
|
setMessages((prev) => [...prev, {
|
|
90
105
|
role: "assistant",
|
|
91
106
|
content: text
|
|
@@ -122,17 +137,47 @@ function useChatStream(sessionId, routing = {
|
|
|
122
137
|
console.error("[useChatStream] saveMessages (cdecli):", e);
|
|
123
138
|
});
|
|
124
139
|
}
|
|
140
|
+
if (leftover.length > 0) {
|
|
141
|
+
const [first, ...rest] = leftover;
|
|
142
|
+
pendingSteersRef.current = rest;
|
|
143
|
+
queueMicrotask(() => {
|
|
144
|
+
void sendMessageRef.current(first, void 0, sid, true);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
125
147
|
},
|
|
126
148
|
onError: (err) => {
|
|
127
149
|
if (cdecliRoundHandledRef.current) return;
|
|
128
150
|
cdecliRoundHandledRef.current = true;
|
|
151
|
+
pendingSteersRef.current = [];
|
|
129
152
|
setError(err || "CDeCLI stream error.");
|
|
130
153
|
finalizeCdecliRound();
|
|
131
154
|
}
|
|
132
155
|
}), [saveMessages, accountUserId, finalizeCdecliRound]);
|
|
133
156
|
const {
|
|
134
|
-
sendMessage: sendCdecliMessage
|
|
157
|
+
sendMessage: sendCdecliMessage,
|
|
158
|
+
steer: steerCdecliMessage,
|
|
159
|
+
cancel: cancelCdecliTurn
|
|
135
160
|
} = useCdecliChannel(routing.channelConnected, routing.accountId, streamChannelId, cdecliCallbacks);
|
|
161
|
+
const flushPendingSteers = useCallback(async () => {
|
|
162
|
+
if (!sessionLiveRef.current || !isSendingRef.current) return;
|
|
163
|
+
const sid = saveSessionIdRef.current;
|
|
164
|
+
if (!sid) return;
|
|
165
|
+
while (pendingSteersRef.current.length > 0 && sessionLiveRef.current && isSendingRef.current) {
|
|
166
|
+
const next = pendingSteersRef.current[0];
|
|
167
|
+
const result = await steerCdecliMessage(next, sid);
|
|
168
|
+
if (result.ok) {
|
|
169
|
+
pendingSteersRef.current.shift();
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (isNoActiveSessionError(result.error)) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
pendingSteersRef.current.shift();
|
|
176
|
+
setError(result.error || "Could not send follow-up. Try again.");
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
}, [steerCdecliMessage]);
|
|
180
|
+
flushPendingSteersRef.current = flushPendingSteers;
|
|
136
181
|
useEffect(() => {
|
|
137
182
|
if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {
|
|
138
183
|
setCdecliStreamOverrideId(void 0);
|
|
@@ -172,17 +217,32 @@ function useChatStream(sessionId, routing = {
|
|
|
172
217
|
setResponse("");
|
|
173
218
|
}
|
|
174
219
|
}, [sessionId, backendMessages, backendMessagesLoaded]);
|
|
175
|
-
const sendMessage = useCallback(async (content, attachments, sessionIdOverride) => {
|
|
220
|
+
const sendMessage = useCallback(async (content, attachments, sessionIdOverride, alreadyVisible = false) => {
|
|
176
221
|
if (!content.trim()) return;
|
|
177
222
|
const effectiveSessionId = sessionIdOverride !== void 0 ? sessionIdOverride : sessionId;
|
|
178
223
|
const rt = routingRef.current;
|
|
224
|
+
const trimmed = content.trim();
|
|
179
225
|
const userMessage = {
|
|
180
226
|
role: "user",
|
|
181
|
-
content:
|
|
227
|
+
content: trimmed,
|
|
182
228
|
attachments
|
|
183
229
|
};
|
|
230
|
+
if (isSendingRef.current) {
|
|
231
|
+
if (!rt.channelConnected || !effectiveSessionId) {
|
|
232
|
+
setError(!rt.channelConnected ? "CDeCLI is not connected yet. Check gateway status in the header." : "Missing chat session id.");
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
setMessages((prev) => [...prev, userMessage]);
|
|
236
|
+
setError(null);
|
|
237
|
+
pendingSteersRef.current = [...pendingSteersRef.current, trimmed];
|
|
238
|
+
void flushPendingSteers();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
184
241
|
isSendingRef.current = true;
|
|
185
|
-
|
|
242
|
+
sessionLiveRef.current = false;
|
|
243
|
+
if (!alreadyVisible) {
|
|
244
|
+
setMessages((prev) => [...prev, userMessage]);
|
|
245
|
+
}
|
|
186
246
|
setResponse("");
|
|
187
247
|
setIsLoading(true);
|
|
188
248
|
setIsStreaming(true);
|
|
@@ -192,7 +252,7 @@ function useChatStream(sessionId, routing = {
|
|
|
192
252
|
cdecliRoundHandledRef.current = false;
|
|
193
253
|
if (!rt.channelConnected) {
|
|
194
254
|
setError("CDeCLI is not connected yet. Check gateway status in the header.");
|
|
195
|
-
setMessages((p) => p.slice(0, -1));
|
|
255
|
+
if (!alreadyVisible) setMessages((p) => p.slice(0, -1));
|
|
196
256
|
isSendingRef.current = false;
|
|
197
257
|
setIsLoading(false);
|
|
198
258
|
setIsStreaming(false);
|
|
@@ -202,7 +262,7 @@ function useChatStream(sessionId, routing = {
|
|
|
202
262
|
}
|
|
203
263
|
if (!effectiveSessionId) {
|
|
204
264
|
setError("Missing chat session id.");
|
|
205
|
-
setMessages((p) => p.slice(0, -1));
|
|
265
|
+
if (!alreadyVisible) setMessages((p) => p.slice(0, -1));
|
|
206
266
|
isSendingRef.current = false;
|
|
207
267
|
setIsLoading(false);
|
|
208
268
|
setIsStreaming(false);
|
|
@@ -216,20 +276,30 @@ function useChatStream(sessionId, routing = {
|
|
|
216
276
|
setTimeout(resolve, 0);
|
|
217
277
|
});
|
|
218
278
|
}
|
|
219
|
-
const ok = await sendCdecliMessage(
|
|
279
|
+
const ok = await sendCdecliMessage(trimmed, effectiveSessionId);
|
|
220
280
|
if (!ok && !cdecliRoundHandledRef.current) {
|
|
221
281
|
cdecliRoundHandledRef.current = true;
|
|
222
282
|
setError("Failed to send message via CDeCLI. Check gateway connection.");
|
|
223
|
-
setMessages((p) => p.slice(0, -1));
|
|
283
|
+
if (!alreadyVisible) setMessages((p) => p.slice(0, -1));
|
|
224
284
|
isSendingRef.current = false;
|
|
225
285
|
setIsLoading(false);
|
|
226
286
|
setIsStreaming(false);
|
|
227
287
|
userMsgForSaveRef.current = null;
|
|
228
288
|
saveSessionIdRef.current = null;
|
|
229
289
|
}
|
|
230
|
-
}, [sessionId, sendCdecliMessage]);
|
|
290
|
+
}, [sessionId, sendCdecliMessage, flushPendingSteers]);
|
|
291
|
+
sendMessageRef.current = sendMessage;
|
|
231
292
|
const cancel = useCallback(() => {
|
|
232
|
-
|
|
293
|
+
var _a;
|
|
294
|
+
pendingSteersRef.current = [];
|
|
295
|
+
sessionLiveRef.current = false;
|
|
296
|
+
const sid = (_a = saveSessionIdRef.current) != null ? _a : sessionId;
|
|
297
|
+
void cancelCdecliTurn(sid != null ? sid : "messenger");
|
|
298
|
+
if (!cdecliRoundHandledRef.current) {
|
|
299
|
+
cdecliRoundHandledRef.current = true;
|
|
300
|
+
finalizeCdecliRound();
|
|
301
|
+
}
|
|
302
|
+
}, [cancelCdecliTurn, finalizeCdecliRound, sessionId]);
|
|
233
303
|
const clearMessages = useCallback(() => {
|
|
234
304
|
setMessages([]);
|
|
235
305
|
setResponse("");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatStream.js","sources":["../../src/hooks/useChatStream.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useChatMutations, useChatMessages } from './useChatApi';\nimport { useCdecliChannel } from './useCdecliChannel';\nimport { usePrerequisiteIds } from './usePrerequisiteIds';\n\n/** Agent returned an error while the cdecli-serve channel stayed connected (e.g. bad LLM API key). */\nfunction isCdecliAgentFailureOutput(text: string): boolean {\n const t = text.trim();\n if (!t) return false;\n return (\n /⚠\\s*Error:/.test(t) ||\n /LLM stream error/i.test(t) ||\n /Incorrect API key/i.test(t) ||\n /invalid_api_key/i.test(t) ||\n /authentication_error/i.test(t)\n );\n}\n\nexport interface MessageAttachment {\n id: string;\n name: string;\n type: 'file' | 'screenshot';\n dataUrl?: string;\n mimeType?: string;\n size?: number;\n url?: string;\n}\n\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n attachments?: MessageAttachment[];\n metadata?: {\n tokenUsage?: { inputTokens: number; outputTokens: number; totalTokens: number };\n model?: string;\n };\n}\n\n/** Mobile chat routes exclusively through CDeCLI (messenger-gateway). */\nexport interface UseChatStreamRouting {\n channelConnected: boolean;\n accountId: string;\n /** When `'backend'`, the gateway persists posts — skip client `saveMessages`. */\n persistenceMode?: 'backend' | 'frontend';\n}\n\nexport function useChatStream(\n sessionId: string | null,\n routing: UseChatStreamRouting = {\n channelConnected: false,\n accountId: 'default',\n persistenceMode: 'backend',\n },\n) {\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [response, setResponse] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const [isStreaming, setIsStreaming] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const isSendingRef = useRef(false);\n\n /** Ensures GraphQL stream subscriptions use the id from createChannel+send before the next parent render. */\n const [cdecliStreamOverrideId, setCdecliStreamOverrideId] = useState<string | undefined>(undefined);\n const userMsgForSaveRef = useRef<ChatMessage | null>(null);\n const saveSessionIdRef = useRef<string | null>(null);\n /** Blocks duplicate cdecli `onComplete` from appending assistant twice / saving twice per send. */\n const cdecliRoundHandledRef = useRef(false);\n const routingRef = useRef(routing);\n routingRef.current = routing;\n\n const { saveMessages } = useChatMutations();\n const { accountUserId } = usePrerequisiteIds();\n const {\n messages: backendMessages,\n loading: backendMessagesLoading,\n messagesLoaded: backendMessagesLoaded,\n } = useChatMessages(sessionId);\n const lastHydratedSessionIdRef = useRef<string | null>(null);\n\n const streamChannelId = sessionId || cdecliStreamOverrideId;\n\n const finalizeCdecliRound = useCallback((assistantContent?: string) => {\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n setResponse('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n if (assistantContent !== undefined) {\n setMessages((prev) => [...prev, { role: 'assistant' as const, content: assistantContent }]);\n }\n }, []);\n\n const cdecliCallbacks = useMemo(\n () => ({\n onChunk: (text: string) => {\n setResponse((r) => r + text);\n },\n onComplete: (text: string) => {\n if (cdecliRoundHandledRef.current) {\n return;\n }\n\n if (isCdecliAgentFailureOutput(text)) {\n cdecliRoundHandledRef.current = true;\n setError('CDeCLI agent error. Check gateway status and server-side LLM configuration.');\n finalizeCdecliRound(text);\n return;\n }\n\n cdecliRoundHandledRef.current = true;\n\n const sid = saveSessionIdRef.current;\n const um = userMsgForSaveRef.current;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n\n setMessages((prev) => [...prev, { role: 'assistant' as const, content: text }]);\n setResponse('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n\n const rt = routingRef.current;\n const persistClientSide = rt.persistenceMode !== 'backend';\n\n if (sid && um && persistClientSide) {\n saveMessages({\n sessionId: sid,\n ...(accountUserId ? { createdBy: accountUserId } : {}),\n userMessage: {\n content: um.content,\n attachments: um.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type,\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\n },\n assistantMessage: {\n content: text,\n tokenCount: undefined,\n model: 'cdecli-serve',\n },\n }).catch((e) => {\n console.error('[useChatStream] saveMessages (cdecli):', e);\n });\n }\n },\n onError: (err: string) => {\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n setError(err || 'CDeCLI stream error.');\n finalizeCdecliRound();\n },\n }),\n [saveMessages, accountUserId, finalizeCdecliRound],\n );\n\n const { sendMessage: sendCdecliMessage } = useCdecliChannel(\n routing.channelConnected,\n routing.accountId,\n streamChannelId,\n cdecliCallbacks,\n );\n\n useEffect(() => {\n if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {\n setCdecliStreamOverrideId(undefined);\n }\n }, [sessionId, cdecliStreamOverrideId]);\n\n useEffect(() => {\n if (isSendingRef.current) return;\n\n if (!sessionId) {\n setMessages([]);\n setResponse('');\n lastHydratedSessionIdRef.current = null;\n return;\n }\n\n const sessionChanged = lastHydratedSessionIdRef.current !== sessionId;\n if (sessionChanged) {\n setMessages([]);\n setResponse('');\n lastHydratedSessionIdRef.current = sessionId;\n }\n\n if (backendMessagesLoaded) {\n const formatted: ChatMessage[] = (backendMessages ?? []).map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content ?? '',\n metadata: msg.tokenCount\n ? {\n tokenUsage: {\n inputTokens: 0,\n outputTokens: msg.tokenCount,\n totalTokens: msg.tokenCount,\n },\n model: msg.model,\n }\n : undefined,\n }));\n setMessages(formatted);\n setResponse('');\n }\n }, [sessionId, backendMessages, backendMessagesLoaded]);\n\n const sendMessage = useCallback(\n async (content: string, attachments?: MessageAttachment[], sessionIdOverride?: string | null) => {\n if (!content.trim()) return;\n\n const effectiveSessionId = sessionIdOverride !== undefined ? sessionIdOverride : sessionId;\n const rt = routingRef.current;\n\n const userMessage: ChatMessage = {\n role: 'user',\n content: content.trim(),\n attachments,\n };\n\n isSendingRef.current = true;\n setMessages((prev) => [...prev, userMessage]);\n setResponse('');\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n userMsgForSaveRef.current = userMessage;\n saveSessionIdRef.current = effectiveSessionId ?? null;\n cdecliRoundHandledRef.current = false;\n\n if (!rt.channelConnected) {\n setError('CDeCLI is not connected yet. Check gateway status in the header.');\n setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n return;\n }\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n return;\n }\n\n if (sessionIdOverride) {\n setCdecliStreamOverrideId(sessionIdOverride);\n await new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n }\n\n const ok = await sendCdecliMessage(content.trim(), effectiveSessionId);\n if (!ok && !cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n setError('Failed to send message via CDeCLI. Check gateway connection.');\n setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n }\n },\n [sessionId, sendCdecliMessage],\n );\n\n const cancel = useCallback(() => {\n /* CDeCLI streams are not abortable client-side; no-op for API parity. */\n }, []);\n\n const clearMessages = useCallback(() => {\n setMessages([]);\n setResponse('');\n setError(null);\n }, []);\n\n const messagesLoading = !!sessionId && backendMessagesLoading && !backendMessagesLoaded;\n\n return {\n messages,\n response,\n error,\n isLoading,\n isStreaming,\n messagesLoading,\n hasMessages: messages.length > 0 || !!response,\n sendMessage,\n cancel,\n clearMessages,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,SAAS,2BAA2B,IAAuB,EAAA;AACzD,EAAM,MAAA,CAAA,GAAI,KAAK,IAAK,EAAA;AACpB,EAAI,IAAA,CAAC,GAAU,OAAA,KAAA;AACf,EAAA,OAAO,aAAa,IAAK,CAAA,CAAC,KAAK,mBAAoB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,oBAAA,CAAqB,IAAK,CAAA,CAAC,KAAK,kBAAmB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,uBAAA,CAAwB,KAAK,CAAC,CAAA;AAC5J;AA+BgB,SAAA,aAAA,CAAc,WAA0B,OAAgC,GAAA;AAAA,EACtF,gBAAkB,EAAA,KAAA;AAAA,EAClB,SAAW,EAAA,SAAA;AAAA,EACX,eAAiB,EAAA;AACnB,CAAG,EAAA;AACD,EAAA,MAAM,CAAC,QAAU,EAAA,WAAW,CAAI,GAAA,QAAA,CAAwB,EAAE,CAAA;AAC1D,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAI,SAAS,EAAE,CAAA;AAC3C,EAAA,MAAM,CAAC,SAAA,EAAW,YAAY,CAAA,GAAI,SAAS,KAAK,CAAA;AAChD,EAAA,MAAM,CAAC,WAAA,EAAa,cAAc,CAAA,GAAI,SAAS,KAAK,CAAA;AACpD,EAAA,MAAM,CAAC,KAAA,EAA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OAAU,GAAA,IAAA;AAAA;AAC7B,GACC,EAAA,CAAC,SAAW,EAAA,iBAAiB,CAAC,CAAA;AACjC,EAAM,MAAA,MAAA,GAAS,YAAY,MAAM;AAAA,GAEjC,EAAG,EAAE,CAAA;AACL,EAAM,MAAA,aAAA,GAAgB,YAAY,MAAM;AACtC,IAAA,WAAA,CAAY,EAAE,CAAA;AACd,IAAA,WAAA,CAAY,EAAE,CAAA;AACd,IAAA,QAAA,CAAS,IAAI,CAAA;AAAA,GACf,EAAG,EAAE,CAAA;AACL,EAAA,MAAM,eAAkB,GAAA,CAAC,CAAC,SAAA,IAAa,0BAA0B,CAAC,qBAAA;AAClE,EAAO,OAAA;AAAA,IACL,QAAA;AAAA,IACA,QAAA;AAAA,IACA,KAAA;AAAA,IACA,SAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,WAAa,EAAA,QAAA,CAAS,MAAS,GAAA,CAAA,IAAK,CAAC,CAAC,QAAA;AAAA,IACtC,WAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"useChatStream.js","sources":["../../src/hooks/useChatStream.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useChatMutations, useChatMessages } from './useChatApi';\nimport { isNoActiveSessionError, useCdecliChannel } from './useCdecliChannel';\nimport { usePrerequisiteIds } from './usePrerequisiteIds';\n\n/** Agent returned an error while the cdecli-serve channel stayed connected (e.g. bad LLM API key). */\nfunction isCdecliAgentFailureOutput(text: string): boolean {\n const t = text.trim();\n if (!t) return false;\n return (\n /⚠\\s*Error:/.test(t) ||\n /LLM stream error/i.test(t) ||\n /Incorrect API key/i.test(t) ||\n /invalid_api_key/i.test(t) ||\n /authentication_error/i.test(t)\n );\n}\n\nexport interface MessageAttachment {\n id: string;\n name: string;\n type: 'file' | 'screenshot';\n dataUrl?: string;\n mimeType?: string;\n size?: number;\n url?: string;\n}\n\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n attachments?: MessageAttachment[];\n metadata?: {\n tokenUsage?: { inputTokens: number; outputTokens: number; totalTokens: number };\n model?: string;\n };\n}\n\n/** Mobile chat routes exclusively through CDeCLI (messenger-gateway). */\nexport interface UseChatStreamRouting {\n channelConnected: boolean;\n accountId: string;\n /** When `'backend'`, the gateway persists posts — skip client `saveMessages`. */\n persistenceMode?: 'backend' | 'frontend';\n}\n\nexport function useChatStream(\n sessionId: string | null,\n routing: UseChatStreamRouting = {\n channelConnected: false,\n accountId: 'default',\n persistenceMode: 'backend',\n },\n) {\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [response, setResponse] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const [isStreaming, setIsStreaming] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const isSendingRef = useRef(false);\n /** Follow-ups typed before cdecli has an active session. Flushed after the first token. */\n const pendingSteersRef = useRef<string[]>([]);\n /** True once this turn has produced at least one stream chunk (steer is valid). */\n const sessionLiveRef = useRef(false);\n const flushPendingSteersRef = useRef<() => Promise<void>>(async () => {});\n const sendMessageRef = useRef<\n (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible?: boolean,\n ) => Promise<void>\n >(async () => {});\n\n /** Ensures GraphQL stream subscriptions use the id from createChannel+send before the next parent render. */\n const [cdecliStreamOverrideId, setCdecliStreamOverrideId] = useState<string | undefined>(undefined);\n const userMsgForSaveRef = useRef<ChatMessage | null>(null);\n const saveSessionIdRef = useRef<string | null>(null);\n /** Blocks duplicate cdecli `onComplete` from appending assistant twice / saving twice per send. */\n const cdecliRoundHandledRef = useRef(false);\n const routingRef = useRef(routing);\n routingRef.current = routing;\n\n const { saveMessages } = useChatMutations();\n const { accountUserId } = usePrerequisiteIds();\n const {\n messages: backendMessages,\n loading: backendMessagesLoading,\n messagesLoaded: backendMessagesLoaded,\n } = useChatMessages(sessionId);\n const lastHydratedSessionIdRef = useRef<string | null>(null);\n\n const streamChannelId = sessionId || cdecliStreamOverrideId;\n\n const finalizeCdecliRound = useCallback((assistantContent?: string) => {\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n sessionLiveRef.current = false;\n setResponse('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n if (assistantContent !== undefined) {\n setMessages((prev) => [...prev, { role: 'assistant' as const, content: assistantContent }]);\n }\n }, []);\n\n const cdecliCallbacks = useMemo(\n () => ({\n onChunk: (text: string) => {\n setResponse((r) => r + text);\n if (!sessionLiveRef.current) {\n sessionLiveRef.current = true;\n void flushPendingSteersRef.current();\n }\n },\n onComplete: (text: string) => {\n if (cdecliRoundHandledRef.current) {\n return;\n }\n\n if (isCdecliAgentFailureOutput(text)) {\n cdecliRoundHandledRef.current = true;\n pendingSteersRef.current = [];\n setError('CDeCLI agent error. Check gateway status and server-side LLM configuration.');\n finalizeCdecliRound(text);\n return;\n }\n\n cdecliRoundHandledRef.current = true;\n\n const sid = saveSessionIdRef.current;\n const um = userMsgForSaveRef.current;\n const leftover = pendingSteersRef.current;\n pendingSteersRef.current = [];\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n sessionLiveRef.current = false;\n\n setMessages((prev) => [...prev, { role: 'assistant' as const, content: text }]);\n setResponse('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n\n const rt = routingRef.current;\n const persistClientSide = rt.persistenceMode !== 'backend';\n\n if (sid && um && persistClientSide) {\n saveMessages({\n sessionId: sid,\n ...(accountUserId ? { createdBy: accountUserId } : {}),\n userMessage: {\n content: um.content,\n attachments: um.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type,\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\n },\n assistantMessage: {\n content: text,\n tokenCount: undefined,\n model: 'cdecli-serve',\n },\n }).catch((e) => {\n console.error('[useChatStream] saveMessages (cdecli):', e);\n });\n }\n\n if (leftover.length > 0) {\n const [first, ...rest] = leftover;\n pendingSteersRef.current = rest;\n queueMicrotask(() => {\n void sendMessageRef.current(first, undefined, sid, true);\n });\n }\n },\n onError: (err: string) => {\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n pendingSteersRef.current = [];\n setError(err || 'CDeCLI stream error.');\n finalizeCdecliRound();\n },\n }),\n [saveMessages, accountUserId, finalizeCdecliRound],\n );\n\n const {\n sendMessage: sendCdecliMessage,\n steer: steerCdecliMessage,\n cancel: cancelCdecliTurn,\n } = useCdecliChannel(routing.channelConnected, routing.accountId, streamChannelId, cdecliCallbacks);\n\n const flushPendingSteers = useCallback(async () => {\n if (!sessionLiveRef.current || !isSendingRef.current) return;\n const sid = saveSessionIdRef.current;\n if (!sid) return;\n\n while (pendingSteersRef.current.length > 0 && sessionLiveRef.current && isSendingRef.current) {\n const next = pendingSteersRef.current[0];\n const result = await steerCdecliMessage(next, sid);\n if (result.ok) {\n pendingSteersRef.current.shift();\n continue;\n }\n if (isNoActiveSessionError(result.error)) {\n return;\n }\n pendingSteersRef.current.shift();\n setError(result.error || 'Could not send follow-up. Try again.');\n return;\n }\n }, [steerCdecliMessage]);\n\n flushPendingSteersRef.current = flushPendingSteers;\n\n useEffect(() => {\n if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {\n setCdecliStreamOverrideId(undefined);\n }\n }, [sessionId, cdecliStreamOverrideId]);\n\n useEffect(() => {\n if (isSendingRef.current) return;\n\n if (!sessionId) {\n setMessages([]);\n setResponse('');\n lastHydratedSessionIdRef.current = null;\n return;\n }\n\n const sessionChanged = lastHydratedSessionIdRef.current !== sessionId;\n if (sessionChanged) {\n setMessages([]);\n setResponse('');\n lastHydratedSessionIdRef.current = sessionId;\n }\n\n if (backendMessagesLoaded) {\n const formatted: ChatMessage[] = (backendMessages ?? []).map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content ?? '',\n metadata: msg.tokenCount\n ? {\n tokenUsage: {\n inputTokens: 0,\n outputTokens: msg.tokenCount,\n totalTokens: msg.tokenCount,\n },\n model: msg.model,\n }\n : undefined,\n }));\n setMessages(formatted);\n setResponse('');\n }\n }, [sessionId, backendMessages, backendMessagesLoaded]);\n\n const sendMessage = useCallback(\n async (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible = false,\n ) => {\n if (!content.trim()) return;\n\n const effectiveSessionId = sessionIdOverride !== undefined ? sessionIdOverride : sessionId;\n const rt = routingRef.current;\n const trimmed = content.trim();\n\n const userMessage: ChatMessage = {\n role: 'user',\n content: trimmed,\n attachments,\n };\n\n /**\n * A turn is already in flight. Keep the follow-up visible and queue it.\n * cdecli rejects steer until the agent session exists (\"no active session\"),\n * which is after the first token. Flush then. Never error/LogBox for that race.\n */\n if (isSendingRef.current) {\n if (!rt.channelConnected || !effectiveSessionId) {\n setError(\n !rt.channelConnected\n ? 'CDeCLI is not connected yet. Check gateway status in the header.'\n : 'Missing chat session id.',\n );\n return;\n }\n setMessages((prev) => [...prev, userMessage]);\n setError(null);\n pendingSteersRef.current = [...pendingSteersRef.current, trimmed];\n void flushPendingSteers();\n return;\n }\n\n isSendingRef.current = true;\n sessionLiveRef.current = false;\n if (!alreadyVisible) {\n setMessages((prev) => [...prev, userMessage]);\n }\n setResponse('');\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n userMsgForSaveRef.current = userMessage;\n saveSessionIdRef.current = effectiveSessionId ?? null;\n cdecliRoundHandledRef.current = false;\n\n if (!rt.channelConnected) {\n setError('CDeCLI is not connected yet. Check gateway status in the header.');\n if (!alreadyVisible) setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n return;\n }\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n if (!alreadyVisible) setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n return;\n }\n\n if (sessionIdOverride) {\n setCdecliStreamOverrideId(sessionIdOverride);\n await new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n }\n\n const ok = await sendCdecliMessage(trimmed, effectiveSessionId);\n if (!ok && !cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n setError('Failed to send message via CDeCLI. Check gateway connection.');\n if (!alreadyVisible) setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n }\n },\n [sessionId, sendCdecliMessage, flushPendingSteers],\n );\n\n sendMessageRef.current = sendMessage;\n\n const cancel = useCallback(() => {\n pendingSteersRef.current = [];\n sessionLiveRef.current = false;\n const sid = saveSessionIdRef.current ?? sessionId;\n void cancelCdecliTurn(sid ?? 'messenger');\n if (!cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n finalizeCdecliRound();\n }\n }, [cancelCdecliTurn, finalizeCdecliRound, sessionId]);\n\n const clearMessages = useCallback(() => {\n setMessages([]);\n setResponse('');\n setError(null);\n }, []);\n\n const messagesLoading = !!sessionId && backendMessagesLoading && !backendMessagesLoaded;\n\n return {\n messages,\n response,\n error,\n isLoading,\n isStreaming,\n messagesLoading,\n hasMessages: messages.length > 0 || !!response,\n sendMessage,\n cancel,\n clearMessages,\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,SAAS,2BAA2B,IAAuB,EAAA;AACzD,EAAM,MAAA,CAAA,GAAI,KAAK,IAAK,EAAA;AACpB,EAAI,IAAA,CAAC,GAAU,OAAA,KAAA;AACf,EAAA,OAAO,aAAa,IAAK,CAAA,CAAC,KAAK,mBAAoB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,oBAAA,CAAqB,IAAK,CAAA,CAAC,KAAK,kBAAmB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,uBAAA,CAAwB,KAAK,CAA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AACd,IAAA,QAAA,CAAS,IAAI,CAAA;AAAA,GACf,EAAG,EAAE,CAAA;AACL,EAAA,MAAM,eAAkB,GAAA,CAAC,CAAC,SAAA,IAAa,0BAA0B,CAAC,qBAAA;AAClE,EAAO,OAAA;AAAA,IACL,QAAA;AAAA,IACA,QAAA;AAAA,IACA,KAAA;AAAA,IACA,SAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,WAAa,EAAA,QAAA,CAAS,MAAS,GAAA,CAAA,IAAK,CAAC,CAAC,QAAA;AAAA,IACtC,WAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {useState,useEffect}from'react';import {Platform,Keyboard}from'react-native';function useKeyboardBottomOffset() {
|
|
2
|
+
const [keyboardHeight, setKeyboardHeight] = useState(0);
|
|
3
|
+
useEffect(() => {
|
|
4
|
+
const showEvent = Platform.OS === "ios" ? "keyboardWillShow" : "keyboardDidShow";
|
|
5
|
+
const hideEvent = Platform.OS === "ios" ? "keyboardWillHide" : "keyboardDidHide";
|
|
6
|
+
const show = Keyboard.addListener(showEvent, (event) => {
|
|
7
|
+
var _a, _b;
|
|
8
|
+
setKeyboardHeight((_b = (_a = event.endCoordinates) == null ? void 0 : _a.height) != null ? _b : 0);
|
|
9
|
+
});
|
|
10
|
+
const hide = Keyboard.addListener(hideEvent, () => {
|
|
11
|
+
setKeyboardHeight(0);
|
|
12
|
+
});
|
|
13
|
+
return () => {
|
|
14
|
+
show.remove();
|
|
15
|
+
hide.remove();
|
|
16
|
+
};
|
|
17
|
+
}, []);
|
|
18
|
+
return {
|
|
19
|
+
keyboardHeight,
|
|
20
|
+
keyboardVisible: keyboardHeight > 0
|
|
21
|
+
};
|
|
22
|
+
}export{useKeyboardBottomOffset};//# sourceMappingURL=useKeyboardBottomOffset.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useKeyboardBottomOffset.js","sources":["../../src/hooks/useKeyboardBottomOffset.ts"],"sourcesContent":["/**\n * Keyboard visibility for compacting chrome (suggestions, template peeks).\n * Composer lift is handled by KeyboardComposerDock, not this hook.\n */\nimport { useEffect, useState } from 'react';\nimport { Keyboard, Platform } from 'react-native';\n\nexport type KeyboardBottomOffset = {\n keyboardHeight: number;\n keyboardVisible: boolean;\n};\n\nexport function useKeyboardBottomOffset(): KeyboardBottomOffset {\n const [keyboardHeight, setKeyboardHeight] = useState(0);\n\n useEffect(() => {\n const showEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow';\n const hideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide';\n\n const show = Keyboard.addListener(showEvent, (event) => {\n setKeyboardHeight(event.endCoordinates?.height ?? 0);\n });\n const hide = Keyboard.addListener(hideEvent, () => {\n setKeyboardHeight(0);\n });\n\n return () => {\n show.remove();\n hide.remove();\n };\n }, []);\n\n return {\n keyboardHeight,\n keyboardVisible: keyboardHeight > 0,\n };\n}\n"],"names":[],"mappings":"oFAUO,SAAS,uBAAgD,GAAA;AAC9D,EAAA,MAAM,CAAC,cAAA,EAAgB,iBAAiB,CAAA,GAAI,SAAS,CAAC,CAAA;AACtD,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,MAAM,SAAY,GAAA,QAAA,CAAS,EAAO,KAAA,KAAA,GAAQ,kBAAqB,GAAA,iBAAA;AAC/D,IAAA,MAAM,SAAY,GAAA,QAAA,CAAS,EAAO,KAAA,KAAA,GAAQ,kBAAqB,GAAA,iBAAA;AAC/D,IAAA,MAAM,IAAO,GAAA,QAAA,CAAS,WAAY,CAAA,SAAA,EAAW,CAAS,KAAA,KAAA;AAf1D,MAAA,IAAA,EAAA,EAAA,EAAA;AAgBM,MAAA,iBAAA,CAAA,CAAkB,EAAM,GAAA,CAAA,EAAA,GAAA,KAAA,CAAA,cAAA,KAAN,IAAsB,GAAA,MAAA,GAAA,EAAA,CAAA,MAAA,KAAtB,YAAgC,CAAC,CAAA;AAAA,KACpD,CAAA;AACD,IAAA,MAAM,IAAO,GAAA,QAAA,CAAS,WAAY,CAAA,SAAA,EAAW,MAAM;AACjD,MAAA,iBAAA,CAAkB,CAAC,CAAA;AAAA,KACpB,CAAA;AACD,IAAA,OAAO,MAAM;AACX,MAAA,IAAA,CAAK,MAAO,EAAA;AACZ,MAAA,IAAA,CAAK,MAAO,EAAA;AAAA,KACd;AAAA,GACF,EAAG,EAAE,CAAA;AACL,EAAO,OAAA;AAAA,IACL,cAAA;AAAA,IACA,iBAAiB,cAAiB,GAAA;AAAA,GACpC;AACF"}
|
|
@@ -33,7 +33,7 @@ import {useSettings}from'@adminide-stack/platform-client';import {ConfigurationT
|
|
|
33
33
|
}, [canFetch, payload]);
|
|
34
34
|
return {
|
|
35
35
|
groups,
|
|
36
|
-
loading: canFetch
|
|
36
|
+
loading: canFetch && loading && groups.length === 0,
|
|
37
37
|
error: canFetch ? error : void 0
|
|
38
38
|
};
|
|
39
39
|
}export{useMarketplaceTemplateGroups};//# sourceMappingURL=useMarketplaceTemplateGroups.js.map
|